blob: d852147a13174ba439edbef57228942ada7f85c7 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LLVM module linker.
11//
12// Specifically, this:
13// * Merges global variables between the two modules
14// * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15// * Merges functions between two modules
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Linker.h"
20#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Module.h"
23#include "llvm/TypeSymbolTable.h"
24#include "llvm/ValueSymbolTable.h"
25#include "llvm/Instructions.h"
26#include "llvm/Assembly/Writer.h"
27#include "llvm/Support/Streams.h"
28#include "llvm/System/Path.h"
29#include <sstream>
30using namespace llvm;
31
32// Error - Simple wrapper function to conditionally assign to E and return true.
33// This just makes error return conditions a little bit simpler...
34static inline bool Error(std::string *E, const std::string &Message) {
35 if (E) *E = Message;
36 return true;
37}
38
39// ToStr - Simple wrapper function to convert a type to a string.
40static std::string ToStr(const Type *Ty, const Module *M) {
41 std::ostringstream OS;
42 WriteTypeSymbolic(OS, Ty, M);
43 return OS.str();
44}
45
46//
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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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.
62//
63static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
Chris Lattnere05b43a2008-06-16 18:11:40 +000064 TypeSymbolTable *DestST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065 if (DestTy == SrcTy) return false; // If already equal, noop
66
67 // Does the type already exist in the module?
68 if (DestTy && !isa<OpaqueType>(DestTy)) { // Yup, the type already exists...
69 if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
71 } else {
72 return true; // Cannot link types... neither is opaque and not-equal
73 }
74 } else { // Type not in dest module. Add it now.
75 if (DestTy) // Type _is_ in module, just opaque...
76 const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77 ->refineAbstractTypeTo(SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 }
79 return false;
80}
81
82static const FunctionType *getFT(const PATypeHolder &TH) {
83 return cast<FunctionType>(TH.get());
84}
85static const StructType *getST(const PATypeHolder &TH) {
86 return cast<StructType>(TH.get());
87}
88
89// RecursiveResolveTypes - This is just like ResolveTypes, except that it
90// recurses down into derived types, merging the used types if the parent types
91// are compatible.
92static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
93 const PATypeHolder &SrcTy,
Chris Lattnere05b43a2008-06-16 18:11:40 +000094 TypeSymbolTable *DestST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
96 const Type *SrcTyT = SrcTy.get();
97 const Type *DestTyT = DestTy.get();
98 if (DestTyT == SrcTyT) return false; // If already equal, noop
99
100 // If we found our opaque type, resolve it now!
101 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
Chris Lattnere05b43a2008-06-16 18:11:40 +0000102 return ResolveTypes(DestTyT, SrcTyT, DestST);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103
104 // Two types cannot be resolved together if they are of different primitive
105 // type. For example, we cannot resolve an int to a float.
106 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
107
108 // Otherwise, resolve the used type used by this derived type...
109 switch (DestTyT->getTypeID()) {
110 case Type::IntegerTyID: {
111 if (cast<IntegerType>(DestTyT)->getBitWidth() !=
112 cast<IntegerType>(SrcTyT)->getBitWidth())
113 return true;
114 return false;
115 }
116 case Type::FunctionTyID: {
117 if (cast<FunctionType>(DestTyT)->isVarArg() !=
118 cast<FunctionType>(SrcTyT)->isVarArg() ||
119 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
120 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
121 return true;
122 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
123 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000124 getFT(SrcTy)->getContainedType(i), DestST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 Pointers))
126 return true;
127 return false;
128 }
129 case Type::StructTyID: {
130 if (getST(DestTy)->getNumContainedTypes() !=
131 getST(SrcTy)->getNumContainedTypes()) return 1;
132 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
133 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000134 getST(SrcTy)->getContainedType(i), DestST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 Pointers))
136 return true;
137 return false;
138 }
139 case Type::ArrayTyID: {
140 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
141 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
142 if (DAT->getNumElements() != SAT->getNumElements()) return true;
143 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000144 DestST, Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 }
146 case Type::PointerTyID: {
147 // If this is a pointer type, check to see if we have already seen it. If
148 // so, we are in a recursive branch. Cut off the search now. We cannot use
149 // an associative container for this search, because the type pointers (keys
150 // in the container) change whenever types get resolved...
151 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
152 if (Pointers[i].first == DestTy)
153 return Pointers[i].second != SrcTy;
154
155 // Otherwise, add the current pointers to the vector to stop recursion on
156 // this pair.
157 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
158 bool Result =
159 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
160 cast<PointerType>(SrcTy.get())->getElementType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000161 DestST, Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 Pointers.pop_back();
163 return Result;
164 }
165 default: assert(0 && "Unexpected type!"); return true;
166 }
167}
168
169static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
170 const PATypeHolder &SrcTy,
Chris Lattnere05b43a2008-06-16 18:11:40 +0000171 TypeSymbolTable *DestST){
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
Chris Lattnere05b43a2008-06-16 18:11:40 +0000173 return RecursiveResolveTypesI(DestTy, SrcTy, DestST, PointerTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174}
175
176
177// LinkTypes - Go through the symbol table of the Src module and see if any
178// types are named in the src module that are not named in the Dst module.
179// Make sure there are no type name conflicts.
180static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
181 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
182 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
183
184 // Look for a type plane for Type's...
185 TypeSymbolTable::const_iterator TI = SrcST->begin();
186 TypeSymbolTable::const_iterator TE = SrcST->end();
187 if (TI == TE) return false; // No named types, do nothing.
188
189 // Some types cannot be resolved immediately because they depend on other
190 // types being resolved to each other first. This contains a list of types we
191 // are waiting to recheck.
192 std::vector<std::string> DelayedTypesToResolve;
193
194 for ( ; TI != TE; ++TI ) {
195 const std::string &Name = TI->first;
196 const Type *RHS = TI->second;
197
198 // Check to see if this type name is already in the dest module...
199 Type *Entry = DestST->lookup(Name);
200
Chris Lattnere05b43a2008-06-16 18:11:40 +0000201 if (Entry == 0 && !Name.empty())
202 DestST->insert(Name, const_cast<Type*>(RHS));
203 else if (ResolveTypes(Entry, RHS, DestST)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 // They look different, save the types 'till later to resolve.
205 DelayedTypesToResolve.push_back(Name);
206 }
207 }
208
209 // Iteratively resolve types while we can...
210 while (!DelayedTypesToResolve.empty()) {
211 // Loop over all of the types, attempting to resolve them if possible...
212 unsigned OldSize = DelayedTypesToResolve.size();
213
214 // Try direct resolution by name...
215 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
216 const std::string &Name = DelayedTypesToResolve[i];
217 Type *T1 = SrcST->lookup(Name);
218 Type *T2 = DestST->lookup(Name);
Chris Lattnere05b43a2008-06-16 18:11:40 +0000219 if (!ResolveTypes(T2, T1, DestST)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 // We are making progress!
221 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
222 --i;
223 }
224 }
225
226 // Did we not eliminate any types?
227 if (DelayedTypesToResolve.size() == OldSize) {
228 // Attempt to resolve subelements of types. This allows us to merge these
229 // two types: { int* } and { opaque* }
230 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
231 const std::string &Name = DelayedTypesToResolve[i];
232 PATypeHolder T1(SrcST->lookup(Name));
233 PATypeHolder T2(DestST->lookup(Name));
234
Chris Lattnere05b43a2008-06-16 18:11:40 +0000235 if (!RecursiveResolveTypes(T2, T1, DestST)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 // We are making progress!
237 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
238
239 // Go back to the main loop, perhaps we can resolve directly by name
240 // now...
241 break;
242 }
243 }
244
245 // If we STILL cannot resolve the types, then there is something wrong.
246 if (DelayedTypesToResolve.size() == OldSize) {
247 // Remove the symbol name from the destination.
248 DelayedTypesToResolve.pop_back();
249 }
250 }
251 }
252
253
254 return false;
255}
256
257static void PrintMap(const std::map<const Value*, Value*> &M) {
258 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
259 I != E; ++I) {
260 cerr << " Fr: " << (void*)I->first << " ";
261 I->first->dump();
262 cerr << " To: " << (void*)I->second << " ";
263 I->second->dump();
264 cerr << "\n";
265 }
266}
267
268
269// RemapOperand - Use ValueMap to convert constants from one module to another.
270static Value *RemapOperand(const Value *In,
271 std::map<const Value*, Value*> &ValueMap) {
272 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
273 if (I != ValueMap.end())
274 return I->second;
275
276 // Check to see if it's a constant that we are interested in transforming.
277 Value *Result = 0;
278 if (const Constant *CPV = dyn_cast<Constant>(In)) {
279 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
280 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
281 return const_cast<Constant*>(CPV); // Simple constants stay identical.
282
283 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
284 std::vector<Constant*> Operands(CPA->getNumOperands());
285 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
286 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
287 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
288 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
289 std::vector<Constant*> Operands(CPS->getNumOperands());
290 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
291 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
292 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
293 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
294 Result = const_cast<Constant*>(CPV);
295 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
296 std::vector<Constant*> Operands(CP->getNumOperands());
297 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
298 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
299 Result = ConstantVector::get(Operands);
300 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
301 std::vector<Constant*> Ops;
302 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
303 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
304 Result = CE->getWithOperands(Ops);
305 } else if (isa<GlobalValue>(CPV)) {
306 assert(0 && "Unmapped global?");
307 } else {
308 assert(0 && "Unknown type of derived type constant value!");
309 }
310 } else if (isa<InlineAsm>(In)) {
311 Result = const_cast<Value*>(In);
312 }
313
314 // Cache the mapping in our local map structure
315 if (Result) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000316 ValueMap[In] = Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 return Result;
318 }
319
320
321 cerr << "LinkModules ValueMap: \n";
322 PrintMap(ValueMap);
323
324 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
325 assert(0 && "Couldn't remap value!");
326 return 0;
327}
328
329/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
330/// in the symbol table. This is good for all clients except for us. Go
331/// through the trouble to force this back.
332static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
333 assert(GV->getName() != Name && "Can't force rename to self");
334 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
335
336 // If there is a conflict, rename the conflict.
337 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
338 assert(ConflictGV->hasInternalLinkage() &&
339 "Not conflicting with a static global, should link instead!");
340 GV->takeName(ConflictGV);
341 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
342 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
343 } else {
344 GV->setName(Name); // Force the name back
345 }
346}
347
348/// CopyGVAttributes - copy additional attributes (those not needed to construct
349/// a GlobalValue) from the SrcGV to the DestGV.
350static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands0cc90582008-05-26 19:58:59 +0000351 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
352 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
353 DestGV->copyAttributesFrom(SrcGV);
354 DestGV->setAlignment(Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355}
356
357/// GetLinkageResult - This analyzes the two global values and determines what
358/// the result will look like in the destination module. In particular, it
359/// computes the resultant linkage type, computes whether the global in the
360/// source should be copied over to the destination (replacing the existing
361/// one), and computes whether this linkage is an error or not. It also performs
362/// visibility checks: we cannot link together two symbols with different
363/// visibilities.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000364static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
366 std::string *Err) {
367 assert((!Dest || !Src->hasInternalLinkage()) &&
368 "If Src has internal linkage, Dest shouldn't be set!");
369 if (!Dest) {
370 // Linking something to nothing.
371 LinkFromSrc = true;
372 LT = Src->getLinkage();
373 } else if (Src->isDeclaration()) {
Anton Korobeynikov15520982008-03-10 22:33:22 +0000374 // If Src is external or if both Src & Dest are external.. Just link the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 // external globals, we aren't adding anything.
376 if (Src->hasDLLImportLinkage()) {
377 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
378 if (Dest->isDeclaration()) {
379 LinkFromSrc = true;
380 LT = Src->getLinkage();
381 }
382 } else if (Dest->hasExternalWeakLinkage()) {
383 //If the Dest is weak, use the source linkage
384 LinkFromSrc = true;
385 LT = Src->getLinkage();
386 } else {
387 LinkFromSrc = false;
388 LT = Dest->getLinkage();
389 }
390 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
391 // If Dest is external but Src is not:
392 LinkFromSrc = true;
393 LT = Src->getLinkage();
394 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
395 if (Src->getLinkage() != Dest->getLinkage())
396 return Error(Err, "Linking globals named '" + Src->getName() +
397 "': can only link appending global with another appending global!");
398 LinkFromSrc = true; // Special cased.
399 LT = Src->getLinkage();
Dale Johannesen49c44122008-05-14 20:12:51 +0000400 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
401 Src->hasCommonLinkage()) {
402 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
403 // or DLL* linkage.
404 if ((Dest->hasLinkOnceLinkage() &&
405 (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 Dest->hasExternalWeakLinkage()) {
407 LinkFromSrc = true;
408 LT = Src->getLinkage();
409 } else {
410 LinkFromSrc = false;
411 LT = Dest->getLinkage();
412 }
Dale Johannesen49c44122008-05-14 20:12:51 +0000413 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
414 Dest->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 // At this point we know that Src has External* or DLL* linkage.
416 if (Src->hasExternalWeakLinkage()) {
417 LinkFromSrc = false;
418 LT = Dest->getLinkage();
419 } else {
420 LinkFromSrc = true;
421 LT = GlobalValue::ExternalLinkage;
422 }
423 } else {
424 assert((Dest->hasExternalLinkage() ||
425 Dest->hasDLLImportLinkage() ||
426 Dest->hasDLLExportLinkage() ||
427 Dest->hasExternalWeakLinkage()) &&
428 (Src->hasExternalLinkage() ||
429 Src->hasDLLImportLinkage() ||
430 Src->hasDLLExportLinkage() ||
431 Src->hasExternalWeakLinkage()) &&
432 "Unexpected linkage type!");
433 return Error(Err, "Linking globals named '" + Src->getName() +
434 "': symbol multiply defined!");
435 }
436
437 // Check visibility
438 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000439 if (!Src->isDeclaration() && !Dest->isDeclaration())
440 return Error(Err, "Linking globals named '" + Src->getName() +
441 "': symbols have different visibilities!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 return false;
443}
444
445// LinkGlobals - Loop through the global variables in the src module and merge
446// them into the dest module.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000447static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 std::map<const Value*, Value*> &ValueMap,
449 std::multimap<std::string, GlobalVariable *> &AppendingVars,
450 std::string *Err) {
451 // Loop over all of the globals in the src module, mapping them over as we go
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000452 for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000453 I != E; ++I) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000454 const GlobalVariable *SGV = I;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000455 GlobalValue *DGV = 0;
456
457 // Check to see if may have to link the global with the global
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000458 if (SGV->hasName() && !SGV->hasInternalLinkage()) {
459 DGV = Dest->getGlobalVariable(SGV->getName());
460 if (DGV && DGV->getType() != SGV->getType())
461 // If types don't agree due to opaque types, try to resolve them.
462 RecursiveResolveTypes(SGV->getType(), DGV->getType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000463 &Dest->getTypeSymbolTable());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 }
465
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000466 // Check to see if may have to link the global with the alias
Anton Korobeynikov702d1cd2008-03-10 22:35:31 +0000467 if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000468 DGV = Dest->getNamedAlias(SGV->getName());
469 if (DGV && DGV->getType() != SGV->getType())
470 // If types don't agree due to opaque types, try to resolve them.
471 RecursiveResolveTypes(SGV->getType(), DGV->getType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000472 &Dest->getTypeSymbolTable());
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000473 }
474
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 if (DGV && DGV->hasInternalLinkage())
476 DGV = 0;
477
Dan Gohman930191f2007-10-08 15:13:30 +0000478 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
479 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 "Global must either be external or have an initializer!");
481
482 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
483 bool LinkFromSrc = false;
484 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
485 return true;
486
487 if (!DGV) {
488 // No linking to be performed, simply create an identical version of the
489 // symbol over in the dest module... the initializer will be filled in
490 // later by LinkGlobalInits...
491 GlobalVariable *NewDGV =
492 new GlobalVariable(SGV->getType()->getElementType(),
493 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikov2bde2d82008-03-07 18:32:18 +0000494 SGV->getName(), Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 // Propagate alignment, visibility and section info.
496 CopyGVAttributes(NewDGV, SGV);
497
498 // If the LLVM runtime renamed the global, but it is an externally visible
499 // symbol, DGV must be an existing global with internal linkage. Rename
500 // it.
501 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
502 ForceRenaming(NewDGV, SGV->getName());
503
504 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000505 ValueMap[SGV] = NewDGV;
506
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507 if (SGV->hasAppendingLinkage())
508 // Keep track that this is an appending variable...
509 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
510 } else if (DGV->hasAppendingLinkage()) {
511 // No linking is performed yet. Just insert a new copy of the global, and
512 // keep track of the fact that it is an appending variable in the
513 // AppendingVars map. The name is cleared out so that no linkage is
514 // performed.
515 GlobalVariable *NewDGV =
516 new GlobalVariable(SGV->getType()->getElementType(),
517 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikov2bde2d82008-03-07 18:32:18 +0000518 "", Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000520 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000522 // Propagate alignment, section and visibility info.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 CopyGVAttributes(NewDGV, SGV);
524
525 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000526 ValueMap[SGV] = NewDGV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527
528 // Keep track that this is an appending variable...
529 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000530 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
531 // SGV is global, but DGV is alias. The only valid mapping is when SGV is
532 // external declaration, which is effectively a no-op. Also make sure
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000533 // linkage calculation was correct.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000534 if (SGV->isDeclaration() && !LinkFromSrc) {
535 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000536 ValueMap[SGV] = DGA;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000537 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000538 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
539 "': symbol multiple defined");
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000540 } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000541 // Otherwise, perform the global-global mapping as instructed by
542 // GetLinkageResult.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 if (LinkFromSrc) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000544 // Propagate alignment, section, and visibility info.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000545 CopyGVAttributes(DGVar, SGV);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000546
547 // If the types don't match, and if we are to link from the source, nuke
548 // DGV and create a new one of the appropriate type.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000549 if (SGV->getType() != DGVar->getType()) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000550 GlobalVariable *NewDGV =
551 new GlobalVariable(SGV->getType()->getElementType(),
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000552 DGVar->isConstant(), DGVar->getLinkage(),
553 /*init*/0, DGVar->getName(), Dest);
554 CopyGVAttributes(NewDGV, DGVar);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000555 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000556 DGVar->getType()));
557 // DGVar will conflict with NewDGV because they both had the same
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000558 // name. We must erase this now so ForceRenaming doesn't assert
559 // because DGV might not have internal linkage.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000560 DGVar->eraseFromParent();
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000561
562 // If the symbol table renamed the global, but it is an externally
563 // visible symbol, DGV must be an existing global with internal
564 // linkage. Rename it.
565 if (NewDGV->getName() != SGV->getName() &&
566 !NewDGV->hasInternalLinkage())
567 ForceRenaming(NewDGV, SGV->getName());
568
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000569 DGVar = NewDGV;
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000570 }
571
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572 // Inherit const as appropriate
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000573 DGVar->setConstant(SGV->isConstant());
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000574
575 // Set initializer to zero, so we can link the stuff later
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000576 DGVar->setInitializer(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 } else {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000578 // Special case for const propagation
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000579 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
580 DGVar->setConstant(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 }
582
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000583 // Set calculated linkage
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000584 DGVar->setLinkage(NewLinkage);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000585
586 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000587 ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 }
589 }
590 return false;
591}
592
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000593static GlobalValue::LinkageTypes
594CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
595 if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
596 return GlobalValue::ExternalLinkage;
597 else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
598 return GlobalValue::WeakLinkage;
599 else {
600 assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
601 "Unexpected linkage type");
602 return GlobalValue::InternalLinkage;
603 }
604}
605
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000607// dest module. We're assuming, that all functions/global variables were already
608// linked in.
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000609static bool LinkAlias(Module *Dest, const Module *Src,
610 std::map<const Value*, Value*> &ValueMap,
611 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612 // Loop over all alias in the src module
613 for (Module::const_alias_iterator I = Src->alias_begin(),
614 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000615 const GlobalAlias *SGA = I;
616 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
617 GlobalAlias *NewGA = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000619 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000620 // of SAliasee in Dest.
Ted Kremenekd40cdd22008-03-09 18:32:50 +0000621 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
622 assert(VMI != ValueMap.end() && "Aliasee not linked");
623 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000624 GlobalValue* DGV = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000626 // Try to find something 'similar' to SGA in destination module.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000627 if (!DGV && !SGA->hasInternalLinkage()) {
628 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000629
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000630 // If types don't agree due to opaque types, try to resolve them.
631 if (DGV && DGV->getType() != SGA->getType())
632 if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000633 &Dest->getTypeSymbolTable()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000634 return Error(Err, "Alias Collision on '" + SGA->getName()+
635 "': aliases have different types");
636 }
637
638 if (!DGV && !SGA->hasInternalLinkage()) {
639 DGV = Dest->getGlobalVariable(SGA->getName());
640
641 // If types don't agree due to opaque types, try to resolve them.
642 if (DGV && DGV->getType() != SGA->getType())
643 if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000644 &Dest->getTypeSymbolTable()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000645 return Error(Err, "Alias Collision on '" + SGA->getName()+
646 "': aliases have different types");
647 }
648
649 if (!DGV && !SGA->hasInternalLinkage()) {
650 DGV = Dest->getFunction(SGA->getName());
651
652 // If types don't agree due to opaque types, try to resolve them.
653 if (DGV && DGV->getType() != SGA->getType())
654 if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000655 &Dest->getTypeSymbolTable()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000656 return Error(Err, "Alias Collision on '" + SGA->getName()+
657 "': aliases have different types");
658 }
659
660 // No linking to be performed on internal stuff.
661 if (DGV && DGV->hasInternalLinkage())
662 DGV = NULL;
663
664 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
665 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000666 // globals are already linked we just need query ValueMap to find the
667 // mapping.
668 if (DAliasee == DGA->getAliasedGlobal()) {
669 // This is just two copies of the same alias. Propagate linkage, if
670 // necessary.
671 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
672
673 NewGA = DGA;
674 // Proceed to 'common' steps
675 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000676 return Error(Err, "Alias Collision on '" + SGA->getName()+
677 "': aliases have different aliasees");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000678 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000679 // The only allowed way is to link alias with external declaration.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000680 if (DGVar->isDeclaration()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000681 // But only if aliasee is global too...
682 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000683 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
684 "': aliasee is not global variable");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000685
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000686 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
687 SGA->getName(), DAliasee, Dest);
688 CopyGVAttributes(NewGA, SGA);
689
690 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000691 if (SGA->getType() != DGVar->getType())
692 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
693 DGVar->getType()));
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000694 else
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000695 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000696
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000697 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000698 // name. We must erase this now so ForceRenaming doesn't assert
699 // because DGV might not have internal linkage.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000700 DGVar->eraseFromParent();
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000701
702 // Proceed to 'common' steps
703 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000704 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
705 "': symbol multiple defined");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000706 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000707 // The only allowed way is to link alias with external declaration.
708 if (DF->isDeclaration()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000709 // But only if aliasee is function too...
710 if (!isa<Function>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000711 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
712 "': aliasee is not function");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000713
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000714 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
715 SGA->getName(), DAliasee, Dest);
716 CopyGVAttributes(NewGA, SGA);
717
718 // Any uses of DF need to change to NewGA, with cast, if needed.
719 if (SGA->getType() != DF->getType())
720 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
721 DF->getType()));
722 else
723 DF->replaceAllUsesWith(NewGA);
724
725 // DF will conflict with NewGA because they both had the same
726 // name. We must erase this now so ForceRenaming doesn't assert
727 // because DF might not have internal linkage.
728 DF->eraseFromParent();
729
730 // Proceed to 'common' steps
731 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000732 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
733 "': symbol multiple defined");
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000734 } else {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000735 // No linking to be performed, simply create an identical version of the
736 // alias over in the dest module...
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000737
738 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
739 SGA->getName(), DAliasee, Dest);
740 CopyGVAttributes(NewGA, SGA);
741
742 // Proceed to 'common' steps
743 }
744
745 assert(NewGA && "No alias was created in destination module!");
746
Anton Korobeynikov552ccce2008-03-10 22:36:35 +0000747 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000748 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000749 if (NewGA->getName() != SGA->getName() &&
750 !NewGA->hasInternalLinkage())
751 ForceRenaming(NewGA, SGA->getName());
752
753 // Remember this mapping so uses in the source module get remapped
754 // later by RemapOperand.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000755 ValueMap[SGA] = NewGA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000756 }
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000757
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 return false;
759}
760
761
762// LinkGlobalInits - Update the initializers in the Dest module now that all
763// globals that may be referenced are in Dest.
764static bool LinkGlobalInits(Module *Dest, const Module *Src,
765 std::map<const Value*, Value*> &ValueMap,
766 std::string *Err) {
767
768 // Loop over all of the globals in the src module, mapping them over as we go
769 for (Module::const_global_iterator I = Src->global_begin(),
770 E = Src->global_end(); I != E; ++I) {
771 const GlobalVariable *SGV = I;
772
773 if (SGV->hasInitializer()) { // Only process initialized GV's
774 // Figure out what the initializer looks like in the dest module...
775 Constant *SInit =
776 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
777
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +0000778 GlobalVariable *DGV =
779 cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 if (DGV->hasInitializer()) {
781 if (SGV->hasExternalLinkage()) {
782 if (DGV->getInitializer() != SInit)
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000783 return Error(Err, "Global Variable Collision on '" + SGV->getName() +
784 "': global variables have different initializers");
Dale Johannesen49c44122008-05-14 20:12:51 +0000785 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
786 DGV->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 // Nothing is required, mapped values will take the new global
788 // automatically.
Dale Johannesen49c44122008-05-14 20:12:51 +0000789 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
790 SGV->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791 // Nothing is required, mapped values will take the new global
792 // automatically.
793 } else if (DGV->hasAppendingLinkage()) {
794 assert(0 && "Appending linkage unimplemented!");
795 } else {
796 assert(0 && "Unknown linkage!");
797 }
798 } else {
799 // Copy the initializer over now...
800 DGV->setInitializer(SInit);
801 }
802 }
803 }
804 return false;
805}
806
807// LinkFunctionProtos - Link the functions together between the two modules,
808// without doing function bodies... this just adds external function prototypes
809// to the Dest function...
810//
811static bool LinkFunctionProtos(Module *Dest, const Module *Src,
812 std::map<const Value*, Value*> &ValueMap,
813 std::string *Err) {
814 // Loop over all of the functions in the src module, mapping them over
815 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
816 const Function *SF = I; // SrcFunction
Chris Lattner1426bfa2008-06-09 07:36:11 +0000817
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 Function *DF = 0;
Chris Lattner1426bfa2008-06-09 07:36:11 +0000819
820 // If this function is internal or has no name, it doesn't participate in
821 // linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 if (SF->hasName() && !SF->hasInternalLinkage()) {
823 // Check to see if may have to link the function.
824 DF = Dest->getFunction(SF->getName());
Chris Lattner1426bfa2008-06-09 07:36:11 +0000825 if (DF && DF->hasInternalLinkage())
826 DF = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 }
Chris Lattnerf7e84192008-06-09 07:25:28 +0000828
Chris Lattner1426bfa2008-06-09 07:36:11 +0000829 // If there is no linkage to be performed, just bring over SF without
830 // modifying it.
831 if (DF == 0) {
832 // Function does not already exist, simply insert an function signature
833 // identical to SF into the dest module.
834 Function *NewDF = Function::Create(SF->getFunctionType(),
835 SF->getLinkage(),
836 SF->getName(), Dest);
837 CopyGVAttributes(NewDF, SF);
838
839 // If the LLVM runtime renamed the function, but it is an externally
840 // visible symbol, DF must be an existing function with internal linkage.
841 // Rename it.
842 if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
843 ForceRenaming(NewDF, SF->getName());
844
845 // ... and remember this mapping...
846 ValueMap[SF] = NewDF;
847 continue;
848 }
849
850
851 // If types don't agree because of opaque, try to resolve them.
852 if (SF->getType() != DF->getType())
853 RecursiveResolveTypes(SF->getType(), DF->getType(),
Chris Lattnere05b43a2008-06-16 18:11:40 +0000854 &Dest->getTypeSymbolTable());
Chris Lattner1426bfa2008-06-09 07:36:11 +0000855
856 // Check visibility, merging if a definition overrides a prototype.
857 if (SF->getVisibility() != DF->getVisibility()) {
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000858 // If one is a prototype, ignore its visibility. Prototypes are always
859 // overridden by the definition.
860 if (!SF->isDeclaration() && !DF->isDeclaration())
861 return Error(Err, "Linking functions named '" + SF->getName() +
862 "': symbols have different visibilities!");
Chris Lattnerf7e84192008-06-09 07:25:28 +0000863
864 // Otherwise, replace the visibility of DF if DF is a prototype.
865 if (DF->isDeclaration())
866 DF->setVisibility(SF->getVisibility());
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000867 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868
Chris Lattner1426bfa2008-06-09 07:36:11 +0000869 if (DF->getType() != SF->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 if (DF->isDeclaration() && !SF->isDeclaration()) {
871 // We have a definition of the same name but different type in the
872 // source module. Copy the prototype to the destination and replace
873 // uses of the destination's prototype with the new prototype.
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000874 Function *NewDF = Function::Create(SF->getFunctionType(),
875 SF->getLinkage(),
Gabor Greifd6da1d02008-04-06 20:25:17 +0000876 SF->getName(), Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 CopyGVAttributes(NewDF, SF);
878
879 // Any uses of DF need to change to NewDF, with cast
880 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
881
882 // DF will conflict with NewDF because they both had the same. We must
883 // erase this now so ForceRenaming doesn't assert because DF might
884 // not have internal linkage.
885 DF->eraseFromParent();
886
887 // If the symbol table renamed the function, but it is an externally
888 // visible symbol, DF must be an existing function with internal
889 // linkage. Rename it.
890 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
891 ForceRenaming(NewDF, SF->getName());
892
893 // Remember this mapping so uses in the source module get remapped
894 // later by RemapOperand.
895 ValueMap[SF] = NewDF;
896 } else if (SF->isDeclaration()) {
897 // We have two functions of the same name but different type and the
898 // source is a declaration while the destination is not. Any use of
899 // the source must be mapped to the destination, with a cast.
900 ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType());
901 } else {
902 // We have two functions of the same name but different types and they
903 // are both definitions. This is an error.
904 return Error(Err, "Function '" + DF->getName() + "' defined as both '" +
905 ToStr(SF->getFunctionType(), Src) + "' and '" +
906 ToStr(DF->getFunctionType(), Dest) + "'");
907 }
Chris Lattner1426bfa2008-06-09 07:36:11 +0000908 continue;
909 }
910
911 if (SF->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 // If SF is a declaration or if both SF & DF are declarations, just link
913 // the declarations, we aren't adding anything.
914 if (SF->hasDLLImportLinkage()) {
915 if (DF->isDeclaration()) {
Chris Lattnerc082fd42008-06-09 07:47:34 +0000916 ValueMap[SF] = DF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000918 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 } else {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000920 ValueMap[SF] = DF;
Chris Lattnerc082fd42008-06-09 07:47:34 +0000921 }
922 continue;
923 }
924
925 // If DF is external but SF is not, link the external functions, update
926 // linkage qualifiers.
927 if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 ValueMap.insert(std::make_pair(SF, DF));
929 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000930 continue;
931 }
932
933 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
934 if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
935 SF->hasCommonLinkage()) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000936 ValueMap[SF] = DF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937
938 // Linkonce+Weak = Weak
939 // *+External Weak = *
Dale Johannesen49c44122008-05-14 20:12:51 +0000940 if ((DF->hasLinkOnceLinkage() &&
941 (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 DF->hasExternalWeakLinkage())
943 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000944 continue;
945 }
946
947 if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
948 DF->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949 // At this point we know that SF has LinkOnce or External* linkage.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000950 ValueMap[SF] = DF;
Chris Lattnerc082fd42008-06-09 07:47:34 +0000951
952 // If the source function has stronger linkage than the destination,
953 // its body and linkage should override ours.
954 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
955 // Don't inherit linkonce & external weak linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000957 DF->deleteBody();
958 }
959 continue;
960 }
961
962 if (SF->getLinkage() != DF->getLinkage())
963 return Error(Err, "Functions named '" + SF->getName() +
964 "' have different linkage specifiers!");
965
966 // The function is defined identically in both modules!
967 if (SF->hasExternalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000968 return Error(Err, "Function '" +
969 ToStr(SF->getFunctionType(), Src) + "':\"" +
970 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc082fd42008-06-09 07:47:34 +0000971 assert(0 && "Unknown linkage configuration found!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 }
973 return false;
974}
975
976// LinkFunctionBody - Copy the source function over into the dest function and
977// fix up references to values. At this point we know that Dest is an external
978// function, and that Src is not.
979static bool LinkFunctionBody(Function *Dest, Function *Src,
980 std::map<const Value*, Value*> &ValueMap,
981 std::string *Err) {
982 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
983
984 // Go through and convert function arguments over, remembering the mapping.
985 Function::arg_iterator DI = Dest->arg_begin();
986 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
987 I != E; ++I, ++DI) {
Owen Andersonab567f82008-04-14 17:38:21 +0000988 DI->setName(I->getName()); // Copy the name information over...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989
990 // Add a mapping to our local map
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000991 ValueMap[I] = DI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 }
993
994 // Splice the body of the source function into the dest function.
995 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
996
997 // At this point, all of the instructions and values of the function are now
998 // copied over. The only problem is that they are still referencing values in
999 // the Source function as operands. Loop through all of the operands of the
1000 // functions and patch them up to point to the local versions...
1001 //
1002 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1003 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1004 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1005 OI != OE; ++OI)
1006 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1007 *OI = RemapOperand(*OI, ValueMap);
1008
1009 // There is no need to map the arguments anymore.
1010 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1011 I != E; ++I)
1012 ValueMap.erase(I);
1013
1014 return false;
1015}
1016
1017
1018// LinkFunctionBodies - Link in the function bodies that are defined in the
1019// source module into the DestModule. This consists basically of copying the
1020// function over and fixing up references to values.
1021static bool LinkFunctionBodies(Module *Dest, Module *Src,
1022 std::map<const Value*, Value*> &ValueMap,
1023 std::string *Err) {
1024
1025 // Loop over all of the functions in the src module, mapping them over as we
1026 // go
1027 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1028 if (!SF->isDeclaration()) { // No body if function is external
1029 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
1030
1031 // DF not external SF external?
1032 if (DF->isDeclaration())
1033 // Only provide the function body if there isn't one already.
1034 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1035 return true;
1036 }
1037 }
1038 return false;
1039}
1040
1041// LinkAppendingVars - If there were any appending global variables, link them
1042// together now. Return true on error.
1043static bool LinkAppendingVars(Module *M,
1044 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1045 std::string *ErrorMsg) {
1046 if (AppendingVars.empty()) return false; // Nothing to do.
1047
1048 // Loop over the multimap of appending vars, processing any variables with the
1049 // same name, forming a new appending global variable with both of the
1050 // initializers merged together, then rewrite references to the old variables
1051 // and delete them.
1052 std::vector<Constant*> Inits;
1053 while (AppendingVars.size() > 1) {
1054 // Get the first two elements in the map...
1055 std::multimap<std::string,
1056 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1057
1058 // If the first two elements are for different names, there is no pair...
1059 // Otherwise there is a pair, so link them together...
1060 if (First->first == Second->first) {
1061 GlobalVariable *G1 = First->second, *G2 = Second->second;
1062 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1063 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1064
1065 // Check to see that they two arrays agree on type...
1066 if (T1->getElementType() != T2->getElementType())
1067 return Error(ErrorMsg,
1068 "Appending variables with different element types need to be linked!");
1069 if (G1->isConstant() != G2->isConstant())
1070 return Error(ErrorMsg,
1071 "Appending variables linked with different const'ness!");
1072
1073 if (G1->getAlignment() != G2->getAlignment())
1074 return Error(ErrorMsg,
1075 "Appending variables with different alignment need to be linked!");
1076
1077 if (G1->getVisibility() != G2->getVisibility())
1078 return Error(ErrorMsg,
1079 "Appending variables with different visibility need to be linked!");
1080
1081 if (G1->getSection() != G2->getSection())
1082 return Error(ErrorMsg,
1083 "Appending variables with different section name need to be linked!");
1084
1085 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1086 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1087
1088 G1->setName(""); // Clear G1's name in case of a conflict!
1089
1090 // Create the new global variable...
1091 GlobalVariable *NG =
1092 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
1093 /*init*/0, First->first, M, G1->isThreadLocal());
1094
1095 // Propagate alignment, visibility and section info.
1096 CopyGVAttributes(NG, G1);
1097
1098 // Merge the initializer...
1099 Inits.reserve(NewSize);
1100 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1101 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1102 Inits.push_back(I->getOperand(i));
1103 } else {
1104 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1105 Constant *CV = Constant::getNullValue(T1->getElementType());
1106 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1107 Inits.push_back(CV);
1108 }
1109 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1110 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1111 Inits.push_back(I->getOperand(i));
1112 } else {
1113 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1114 Constant *CV = Constant::getNullValue(T2->getElementType());
1115 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1116 Inits.push_back(CV);
1117 }
1118 NG->setInitializer(ConstantArray::get(NewType, Inits));
1119 Inits.clear();
1120
1121 // Replace any uses of the two global variables with uses of the new
1122 // global...
1123
1124 // FIXME: This should rewrite simple/straight-forward uses such as
1125 // getelementptr instructions to not use the Cast!
1126 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1127 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
1128
1129 // Remove the two globals from the module now...
1130 M->getGlobalList().erase(G1);
1131 M->getGlobalList().erase(G2);
1132
1133 // Put the new global into the AppendingVars map so that we can handle
1134 // linking of more than two vars...
1135 Second->second = NG;
1136 }
1137 AppendingVars.erase(First);
1138 }
1139
1140 return false;
1141}
1142
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001143static bool ResolveAliases(Module *Dest) {
1144 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov82192622008-03-11 22:51:09 +00001145 I != E; ++I)
1146 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1147 if (!GV->isDeclaration())
1148 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001149
1150 return false;
1151}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152
1153// LinkModules - This function links two modules together, with the resulting
1154// left module modified to be the composite of the two input modules. If an
1155// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1156// the problem. Upon failure, the Dest module could be in a modified state, and
1157// shouldn't be relied on to be consistent.
1158bool
1159Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1160 assert(Dest != 0 && "Invalid Destination module");
1161 assert(Src != 0 && "Invalid Source Module");
1162
1163 if (Dest->getDataLayout().empty()) {
1164 if (!Src->getDataLayout().empty()) {
1165 Dest->setDataLayout(Src->getDataLayout());
1166 } else {
1167 std::string DataLayout;
1168
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001169 if (Dest->getEndianness() == Module::AnyEndianness) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 if (Src->getEndianness() == Module::BigEndian)
1171 DataLayout.append("E");
1172 else if (Src->getEndianness() == Module::LittleEndian)
1173 DataLayout.append("e");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001174 }
1175
1176 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177 if (Src->getPointerSize() == Module::Pointer64)
1178 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1179 else if (Src->getPointerSize() == Module::Pointer32)
1180 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001181 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 Dest->setDataLayout(DataLayout);
1183 }
1184 }
1185
Chris Lattner85dd49c2008-02-19 18:49:08 +00001186 // Copy the target triple from the source to dest if the dest's is empty.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1188 Dest->setTargetTriple(Src->getTargetTriple());
1189
1190 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1191 Src->getDataLayout() != Dest->getDataLayout())
1192 cerr << "WARNING: Linking two modules of different data layouts!\n";
1193 if (!Src->getTargetTriple().empty() &&
1194 Dest->getTargetTriple() != Src->getTargetTriple())
1195 cerr << "WARNING: Linking two modules of different target triples!\n";
1196
Chris Lattner85dd49c2008-02-19 18:49:08 +00001197 // Append the module inline asm string.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 if (!Src->getModuleInlineAsm().empty()) {
1199 if (Dest->getModuleInlineAsm().empty())
1200 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1201 else
1202 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1203 Src->getModuleInlineAsm());
1204 }
1205
1206 // Update the destination module's dependent libraries list with the libraries
1207 // from the source module. There's no opportunity for duplicates here as the
1208 // Module ensures that duplicate insertions are discarded.
Chris Lattner85dd49c2008-02-19 18:49:08 +00001209 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1210 SI != SE; ++SI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 Dest->addLibrary(*SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001212
1213 // LinkTypes - Go through the symbol table of the Src module and see if any
1214 // types are named in the src module that are not named in the Dst module.
1215 // Make sure there are no type name conflicts.
1216 if (LinkTypes(Dest, Src, ErrorMsg))
1217 return true;
1218
1219 // ValueMap - Mapping of values from what they used to be in Src, to what they
1220 // are now in Dest.
1221 std::map<const Value*, Value*> ValueMap;
1222
1223 // AppendingVars - Keep track of global variables in the destination module
1224 // with appending linkage. After the module is linked together, they are
1225 // appended and the module is rewritten.
1226 std::multimap<std::string, GlobalVariable *> AppendingVars;
1227 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1228 I != E; ++I) {
1229 // Add all of the appending globals already in the Dest module to
1230 // AppendingVars.
1231 if (I->hasAppendingLinkage())
1232 AppendingVars.insert(std::make_pair(I->getName(), I));
1233 }
1234
1235 // Insert all of the globals in src into the Dest module... without linking
1236 // initializers (which could refer to functions not yet mapped over).
1237 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1238 return true;
1239
1240 // Link the functions together between the two modules, without doing function
1241 // bodies... this just adds external function prototypes to the Dest
1242 // function... We do this so that when we begin processing function bodies,
1243 // all of the global values that may be referenced are available in our
1244 // ValueMap.
1245 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1246 return true;
1247
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +00001248 // If there were any alias, link them now. We really need to do this now,
1249 // because all of the aliases that may be referenced need to be available in
1250 // ValueMap
1251 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1252
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253 // Update the initializers in the Dest module now that all globals that may
1254 // be referenced are in Dest.
1255 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1256
1257 // Link in the function bodies that are defined in the source module into the
1258 // DestModule. This consists basically of copying the function over and
1259 // fixing up references to values.
1260 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1261
1262 // If there were any appending global variables, link them together now.
1263 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1264
Anton Korobeynikova68796c2008-03-05 23:08:47 +00001265 // Resolve all uses of aliases with aliasees
1266 if (ResolveAliases(Dest)) return true;
1267
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 // If the source library's module id is in the dependent library list of the
1269 // destination library, remove it since that module is now linked in.
1270 sys::Path modId;
1271 modId.set(Src->getModuleIdentifier());
1272 if (!modId.isEmpty())
1273 Dest->removeLibrary(modId.getBasename());
1274
1275 return false;
1276}
1277
1278// vim: sw=2