blob: e36fbafc6faf2fbeb5b4b16d2c2263ed33828a76 [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//
Chris Lattner06638ab2008-06-16 18:19:05 +000063static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064 if (DestTy == SrcTy) return false; // If already equal, noop
Chris Lattner06638ab2008-06-16 18:19:05 +000065 assert(DestTy && SrcTy && "Can't handle null types");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066
Chris Lattner06638ab2008-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 }
75 return false;
76}
77
78static const FunctionType *getFT(const PATypeHolder &TH) {
79 return cast<FunctionType>(TH.get());
80}
81static const StructType *getST(const PATypeHolder &TH) {
82 return cast<StructType>(TH.get());
83}
84
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.
88static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
89 const PATypeHolder &SrcTy,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
91 const Type *SrcTyT = SrcTy.get();
92 const Type *DestTyT = DestTy.get();
93 if (DestTyT == SrcTyT) return false; // If already equal, noop
94
95 // If we found our opaque type, resolve it now!
96 if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
Chris Lattner06638ab2008-06-16 18:19:05 +000097 return ResolveTypes(DestTyT, SrcTyT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098
99 // Two types cannot be resolved together if they are of different primitive
100 // type. For example, we cannot resolve an int to a float.
101 if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
102
103 // Otherwise, resolve the used type used by this derived type...
104 switch (DestTyT->getTypeID()) {
105 case Type::IntegerTyID: {
106 if (cast<IntegerType>(DestTyT)->getBitWidth() !=
107 cast<IntegerType>(SrcTyT)->getBitWidth())
108 return true;
109 return false;
110 }
111 case Type::FunctionTyID: {
112 if (cast<FunctionType>(DestTyT)->isVarArg() !=
113 cast<FunctionType>(SrcTyT)->isVarArg() ||
114 cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
115 cast<FunctionType>(SrcTyT)->getNumContainedTypes())
116 return true;
117 for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
118 if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
Chris Lattner06638ab2008-06-16 18:19:05 +0000119 getFT(SrcTy)->getContainedType(i), Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 return true;
121 return false;
122 }
123 case Type::StructTyID: {
124 if (getST(DestTy)->getNumContainedTypes() !=
125 getST(SrcTy)->getNumContainedTypes()) return 1;
126 for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
127 if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
Chris Lattner06638ab2008-06-16 18:19:05 +0000128 getST(SrcTy)->getContainedType(i), Pointers))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 return true;
130 return false;
131 }
132 case Type::ArrayTyID: {
133 const ArrayType *DAT = cast<ArrayType>(DestTy.get());
134 const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
135 if (DAT->getNumElements() != SAT->getNumElements()) return true;
136 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
Chris Lattner06638ab2008-06-16 18:19:05 +0000137 Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 }
139 case Type::PointerTyID: {
140 // If this is a pointer type, check to see if we have already seen it. If
141 // so, we are in a recursive branch. Cut off the search now. We cannot use
142 // an associative container for this search, because the type pointers (keys
143 // in the container) change whenever types get resolved...
144 for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
145 if (Pointers[i].first == DestTy)
146 return Pointers[i].second != SrcTy;
147
148 // Otherwise, add the current pointers to the vector to stop recursion on
149 // this pair.
150 Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
151 bool Result =
152 RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
153 cast<PointerType>(SrcTy.get())->getElementType(),
Chris Lattner06638ab2008-06-16 18:19:05 +0000154 Pointers);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 Pointers.pop_back();
156 return Result;
157 }
158 default: assert(0 && "Unexpected type!"); return true;
159 }
160}
161
162static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
Chris Lattner06638ab2008-06-16 18:19:05 +0000163 const PATypeHolder &SrcTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164 std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
Chris Lattner06638ab2008-06-16 18:19:05 +0000165 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166}
167
168
169// LinkTypes - Go through the symbol table of the Src module and see if any
170// types are named in the src module that are not named in the Dst module.
171// Make sure there are no type name conflicts.
172static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
173 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
174 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
175
176 // Look for a type plane for Type's...
177 TypeSymbolTable::const_iterator TI = SrcST->begin();
178 TypeSymbolTable::const_iterator TE = SrcST->end();
179 if (TI == TE) return false; // No named types, do nothing.
180
181 // Some types cannot be resolved immediately because they depend on other
182 // types being resolved to each other first. This contains a list of types we
183 // are waiting to recheck.
184 std::vector<std::string> DelayedTypesToResolve;
185
186 for ( ; TI != TE; ++TI ) {
187 const std::string &Name = TI->first;
188 const Type *RHS = TI->second;
189
Chris Lattner06638ab2008-06-16 18:19:05 +0000190 // Check to see if this type name is already in the dest module.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 Type *Entry = DestST->lookup(Name);
192
Chris Lattner06638ab2008-06-16 18:19:05 +0000193 // If the name is just in the source module, bring it over to the dest.
194 if (Entry == 0) {
195 if (!Name.empty())
196 DestST->insert(Name, const_cast<Type*>(RHS));
197 } else if (ResolveTypes(Entry, RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 // They look different, save the types 'till later to resolve.
199 DelayedTypesToResolve.push_back(Name);
200 }
201 }
202
203 // Iteratively resolve types while we can...
204 while (!DelayedTypesToResolve.empty()) {
205 // Loop over all of the types, attempting to resolve them if possible...
206 unsigned OldSize = DelayedTypesToResolve.size();
207
208 // Try direct resolution by name...
209 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
210 const std::string &Name = DelayedTypesToResolve[i];
211 Type *T1 = SrcST->lookup(Name);
212 Type *T2 = DestST->lookup(Name);
Chris Lattner06638ab2008-06-16 18:19:05 +0000213 if (!ResolveTypes(T2, T1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 // We are making progress!
215 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
216 --i;
217 }
218 }
219
220 // Did we not eliminate any types?
221 if (DelayedTypesToResolve.size() == OldSize) {
222 // Attempt to resolve subelements of types. This allows us to merge these
223 // two types: { int* } and { opaque* }
224 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
225 const std::string &Name = DelayedTypesToResolve[i];
226 PATypeHolder T1(SrcST->lookup(Name));
227 PATypeHolder T2(DestST->lookup(Name));
228
Chris Lattner06638ab2008-06-16 18:19:05 +0000229 if (!RecursiveResolveTypes(T2, T1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 // We are making progress!
231 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
232
233 // Go back to the main loop, perhaps we can resolve directly by name
234 // now...
235 break;
236 }
237 }
238
239 // If we STILL cannot resolve the types, then there is something wrong.
240 if (DelayedTypesToResolve.size() == OldSize) {
241 // Remove the symbol name from the destination.
242 DelayedTypesToResolve.pop_back();
243 }
244 }
245 }
246
247
248 return false;
249}
250
251static void PrintMap(const std::map<const Value*, Value*> &M) {
252 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
253 I != E; ++I) {
254 cerr << " Fr: " << (void*)I->first << " ";
255 I->first->dump();
256 cerr << " To: " << (void*)I->second << " ";
257 I->second->dump();
258 cerr << "\n";
259 }
260}
261
262
263// RemapOperand - Use ValueMap to convert constants from one module to another.
264static Value *RemapOperand(const Value *In,
265 std::map<const Value*, Value*> &ValueMap) {
266 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
267 if (I != ValueMap.end())
268 return I->second;
269
270 // Check to see if it's a constant that we are interested in transforming.
271 Value *Result = 0;
272 if (const Constant *CPV = dyn_cast<Constant>(In)) {
273 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
274 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
275 return const_cast<Constant*>(CPV); // Simple constants stay identical.
276
277 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
278 std::vector<Constant*> Operands(CPA->getNumOperands());
279 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
280 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
281 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
282 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
283 std::vector<Constant*> Operands(CPS->getNumOperands());
284 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
285 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
286 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
287 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
288 Result = const_cast<Constant*>(CPV);
289 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
290 std::vector<Constant*> Operands(CP->getNumOperands());
291 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
292 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
293 Result = ConstantVector::get(Operands);
294 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
295 std::vector<Constant*> Ops;
296 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
297 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
298 Result = CE->getWithOperands(Ops);
299 } else if (isa<GlobalValue>(CPV)) {
300 assert(0 && "Unmapped global?");
301 } else {
302 assert(0 && "Unknown type of derived type constant value!");
303 }
304 } else if (isa<InlineAsm>(In)) {
305 Result = const_cast<Value*>(In);
306 }
307
308 // Cache the mapping in our local map structure
309 if (Result) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000310 ValueMap[In] = Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311 return Result;
312 }
313
314
315 cerr << "LinkModules ValueMap: \n";
316 PrintMap(ValueMap);
317
318 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
319 assert(0 && "Couldn't remap value!");
320 return 0;
321}
322
323/// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
324/// in the symbol table. This is good for all clients except for us. Go
325/// through the trouble to force this back.
326static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
327 assert(GV->getName() != Name && "Can't force rename to self");
328 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
329
330 // If there is a conflict, rename the conflict.
331 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
332 assert(ConflictGV->hasInternalLinkage() &&
333 "Not conflicting with a static global, should link instead!");
334 GV->takeName(ConflictGV);
335 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
336 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
337 } else {
338 GV->setName(Name); // Force the name back
339 }
340}
341
342/// CopyGVAttributes - copy additional attributes (those not needed to construct
343/// a GlobalValue) from the SrcGV to the DestGV.
344static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
Duncan Sands0cc90582008-05-26 19:58:59 +0000345 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
346 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
347 DestGV->copyAttributesFrom(SrcGV);
348 DestGV->setAlignment(Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349}
350
351/// GetLinkageResult - This analyzes the two global values and determines what
352/// the result will look like in the destination module. In particular, it
353/// computes the resultant linkage type, computes whether the global in the
354/// source should be copied over to the destination (replacing the existing
355/// one), and computes whether this linkage is an error or not. It also performs
356/// visibility checks: we cannot link together two symbols with different
357/// visibilities.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000358static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
360 std::string *Err) {
361 assert((!Dest || !Src->hasInternalLinkage()) &&
362 "If Src has internal linkage, Dest shouldn't be set!");
363 if (!Dest) {
364 // Linking something to nothing.
365 LinkFromSrc = true;
366 LT = Src->getLinkage();
367 } else if (Src->isDeclaration()) {
Anton Korobeynikov15520982008-03-10 22:33:22 +0000368 // If Src is external or if both Src & Dest are external.. Just link the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369 // external globals, we aren't adding anything.
370 if (Src->hasDLLImportLinkage()) {
371 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
372 if (Dest->isDeclaration()) {
373 LinkFromSrc = true;
374 LT = Src->getLinkage();
375 }
376 } else if (Dest->hasExternalWeakLinkage()) {
377 //If the Dest is weak, use the source linkage
378 LinkFromSrc = true;
379 LT = Src->getLinkage();
380 } else {
381 LinkFromSrc = false;
382 LT = Dest->getLinkage();
383 }
384 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
385 // If Dest is external but Src is not:
386 LinkFromSrc = true;
387 LT = Src->getLinkage();
388 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
389 if (Src->getLinkage() != Dest->getLinkage())
390 return Error(Err, "Linking globals named '" + Src->getName() +
391 "': can only link appending global with another appending global!");
392 LinkFromSrc = true; // Special cased.
393 LT = Src->getLinkage();
Dale Johannesen49c44122008-05-14 20:12:51 +0000394 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
395 Src->hasCommonLinkage()) {
396 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
397 // or DLL* linkage.
398 if ((Dest->hasLinkOnceLinkage() &&
399 (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 Dest->hasExternalWeakLinkage()) {
401 LinkFromSrc = true;
402 LT = Src->getLinkage();
403 } else {
404 LinkFromSrc = false;
405 LT = Dest->getLinkage();
406 }
Dale Johannesen49c44122008-05-14 20:12:51 +0000407 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
408 Dest->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 // At this point we know that Src has External* or DLL* linkage.
410 if (Src->hasExternalWeakLinkage()) {
411 LinkFromSrc = false;
412 LT = Dest->getLinkage();
413 } else {
414 LinkFromSrc = true;
415 LT = GlobalValue::ExternalLinkage;
416 }
417 } else {
418 assert((Dest->hasExternalLinkage() ||
419 Dest->hasDLLImportLinkage() ||
420 Dest->hasDLLExportLinkage() ||
421 Dest->hasExternalWeakLinkage()) &&
422 (Src->hasExternalLinkage() ||
423 Src->hasDLLImportLinkage() ||
424 Src->hasDLLExportLinkage() ||
425 Src->hasExternalWeakLinkage()) &&
426 "Unexpected linkage type!");
427 return Error(Err, "Linking globals named '" + Src->getName() +
428 "': symbol multiply defined!");
429 }
430
431 // Check visibility
432 if (Dest && Src->getVisibility() != Dest->getVisibility())
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000433 if (!Src->isDeclaration() && !Dest->isDeclaration())
434 return Error(Err, "Linking globals named '" + Src->getName() +
435 "': symbols have different visibilities!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 return false;
437}
438
439// LinkGlobals - Loop through the global variables in the src module and merge
440// them into the dest module.
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000441static bool LinkGlobals(Module *Dest, const Module *Src,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 std::map<const Value*, Value*> &ValueMap,
443 std::multimap<std::string, GlobalVariable *> &AppendingVars,
444 std::string *Err) {
445 // Loop over all of the globals in the src module, mapping them over as we go
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000446 for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000447 I != E; ++I) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000448 const GlobalVariable *SGV = I;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000449 GlobalValue *DGV = 0;
450
451 // Check to see if may have to link the global with the global
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 if (SGV->hasName() && !SGV->hasInternalLinkage()) {
453 DGV = Dest->getGlobalVariable(SGV->getName());
454 if (DGV && DGV->getType() != SGV->getType())
455 // If types don't agree due to opaque types, try to resolve them.
Chris Lattner06638ab2008-06-16 18:19:05 +0000456 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 }
458
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000459 // Check to see if may have to link the global with the alias
Anton Korobeynikov702d1cd2008-03-10 22:35:31 +0000460 if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000461 DGV = Dest->getNamedAlias(SGV->getName());
462 if (DGV && DGV->getType() != SGV->getType())
463 // If types don't agree due to opaque types, try to resolve them.
Chris Lattner06638ab2008-06-16 18:19:05 +0000464 RecursiveResolveTypes(SGV->getType(), DGV->getType());
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000465 }
466
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 if (DGV && DGV->hasInternalLinkage())
468 DGV = 0;
469
Dan Gohman930191f2007-10-08 15:13:30 +0000470 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
471 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 "Global must either be external or have an initializer!");
473
474 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
475 bool LinkFromSrc = false;
476 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
477 return true;
478
479 if (!DGV) {
480 // No linking to be performed, simply create an identical version of the
481 // symbol over in the dest module... the initializer will be filled in
482 // later by LinkGlobalInits...
483 GlobalVariable *NewDGV =
484 new GlobalVariable(SGV->getType()->getElementType(),
485 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikov2bde2d82008-03-07 18:32:18 +0000486 SGV->getName(), Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 // Propagate alignment, visibility and section info.
488 CopyGVAttributes(NewDGV, SGV);
489
490 // If the LLVM runtime renamed the global, but it is an externally visible
491 // symbol, DGV must be an existing global with internal linkage. Rename
492 // it.
493 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
494 ForceRenaming(NewDGV, SGV->getName());
495
496 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000497 ValueMap[SGV] = NewDGV;
498
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499 if (SGV->hasAppendingLinkage())
500 // Keep track that this is an appending variable...
501 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
502 } else if (DGV->hasAppendingLinkage()) {
503 // No linking is performed yet. Just insert a new copy of the global, and
504 // keep track of the fact that it is an appending variable in the
505 // AppendingVars map. The name is cleared out so that no linkage is
506 // performed.
507 GlobalVariable *NewDGV =
508 new GlobalVariable(SGV->getType()->getElementType(),
509 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
Anton Korobeynikov2bde2d82008-03-07 18:32:18 +0000510 "", Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000512 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 NewDGV->setAlignment(DGV->getAlignment());
Anton Korobeynikov4da527c2008-03-07 18:34:50 +0000514 // Propagate alignment, section and visibility info.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 CopyGVAttributes(NewDGV, SGV);
516
517 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000518 ValueMap[SGV] = NewDGV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519
520 // Keep track that this is an appending variable...
521 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000522 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
523 // SGV is global, but DGV is alias. The only valid mapping is when SGV is
524 // external declaration, which is effectively a no-op. Also make sure
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000525 // linkage calculation was correct.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000526 if (SGV->isDeclaration() && !LinkFromSrc) {
527 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000528 ValueMap[SGV] = DGA;
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000529 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000530 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
531 "': symbol multiple defined");
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000532 } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000533 // Otherwise, perform the global-global mapping as instructed by
534 // GetLinkageResult.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 if (LinkFromSrc) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000536 // Propagate alignment, section, and visibility info.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000537 CopyGVAttributes(DGVar, SGV);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000538
539 // If the types don't match, and if we are to link from the source, nuke
540 // DGV and create a new one of the appropriate type.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000541 if (SGV->getType() != DGVar->getType()) {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000542 GlobalVariable *NewDGV =
543 new GlobalVariable(SGV->getType()->getElementType(),
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000544 DGVar->isConstant(), DGVar->getLinkage(),
545 /*init*/0, DGVar->getName(), Dest);
546 CopyGVAttributes(NewDGV, DGVar);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000547 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000548 DGVar->getType()));
549 // DGVar will conflict with NewDGV because they both had the same
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000550 // name. We must erase this now so ForceRenaming doesn't assert
551 // because DGV might not have internal linkage.
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000552 DGVar->eraseFromParent();
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000553
554 // If the symbol table renamed the global, but it is an externally
555 // visible symbol, DGV must be an existing global with internal
556 // linkage. Rename it.
557 if (NewDGV->getName() != SGV->getName() &&
558 !NewDGV->hasInternalLinkage())
559 ForceRenaming(NewDGV, SGV->getName());
560
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000561 DGVar = NewDGV;
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000562 }
563
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 // Inherit const as appropriate
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000565 DGVar->setConstant(SGV->isConstant());
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000566
567 // Set initializer to zero, so we can link the stuff later
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000568 DGVar->setInitializer(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000569 } else {
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000570 // Special case for const propagation
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000571 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
572 DGVar->setConstant(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573 }
574
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000575 // Set calculated linkage
Anton Korobeynikov30dd7162008-03-10 22:34:28 +0000576 DGVar->setLinkage(NewLinkage);
Anton Korobeynikovebb58502008-03-10 22:33:53 +0000577
578 // Make sure to remember this mapping...
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000579 ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580 }
581 }
582 return false;
583}
584
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000585static GlobalValue::LinkageTypes
586CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
587 if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
588 return GlobalValue::ExternalLinkage;
589 else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
590 return GlobalValue::WeakLinkage;
591 else {
592 assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
593 "Unexpected linkage type");
594 return GlobalValue::InternalLinkage;
595 }
596}
597
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598// LinkAlias - Loop through the alias in the src module and link them into the
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000599// dest module. We're assuming, that all functions/global variables were already
600// linked in.
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000601static bool LinkAlias(Module *Dest, const Module *Src,
602 std::map<const Value*, Value*> &ValueMap,
603 std::string *Err) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 // Loop over all alias in the src module
605 for (Module::const_alias_iterator I = Src->alias_begin(),
606 E = Src->alias_end(); I != E; ++I) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000607 const GlobalAlias *SGA = I;
608 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
609 GlobalAlias *NewGA = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000611 // Globals were already linked, thus we can just query ValueMap for variant
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000612 // of SAliasee in Dest.
Ted Kremenekd40cdd22008-03-09 18:32:50 +0000613 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
614 assert(VMI != ValueMap.end() && "Aliasee not linked");
615 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000616 GlobalValue* DGV = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000618 // Try to find something 'similar' to SGA in destination module.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000619 if (!DGV && !SGA->hasInternalLinkage()) {
620 DGV = Dest->getNamedAlias(SGA->getName());
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +0000621
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000622 // If types don't agree due to opaque types, try to resolve them.
623 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000624 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000625 return Error(Err, "Alias Collision on '" + SGA->getName()+
626 "': aliases have different types");
627 }
628
629 if (!DGV && !SGA->hasInternalLinkage()) {
630 DGV = Dest->getGlobalVariable(SGA->getName());
631
632 // If types don't agree due to opaque types, try to resolve them.
633 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000634 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000635 return Error(Err, "Alias Collision on '" + SGA->getName()+
636 "': aliases have different types");
637 }
638
639 if (!DGV && !SGA->hasInternalLinkage()) {
640 DGV = Dest->getFunction(SGA->getName());
641
642 // If types don't agree due to opaque types, try to resolve them.
643 if (DGV && DGV->getType() != SGA->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000644 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000645 return Error(Err, "Alias Collision on '" + SGA->getName()+
646 "': aliases have different types");
647 }
648
649 // No linking to be performed on internal stuff.
650 if (DGV && DGV->hasInternalLinkage())
651 DGV = NULL;
652
653 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
654 // Types are known to be the same, check whether aliasees equal. As
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000655 // globals are already linked we just need query ValueMap to find the
656 // mapping.
657 if (DAliasee == DGA->getAliasedGlobal()) {
658 // This is just two copies of the same alias. Propagate linkage, if
659 // necessary.
660 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
661
662 NewGA = DGA;
663 // Proceed to 'common' steps
664 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000665 return Error(Err, "Alias Collision on '" + SGA->getName()+
666 "': aliases have different aliasees");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000667 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000668 // The only allowed way is to link alias with external declaration.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000669 if (DGVar->isDeclaration()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000670 // But only if aliasee is global too...
671 if (!isa<GlobalVariable>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000672 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
673 "': aliasee is not global variable");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000674
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000675 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
676 SGA->getName(), DAliasee, Dest);
677 CopyGVAttributes(NewGA, SGA);
678
679 // Any uses of DGV need to change to NewGA, with cast, if needed.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000680 if (SGA->getType() != DGVar->getType())
681 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
682 DGVar->getType()));
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000683 else
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000684 DGVar->replaceAllUsesWith(NewGA);
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000685
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000686 // DGVar will conflict with NewGA because they both had the same
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000687 // name. We must erase this now so ForceRenaming doesn't assert
688 // because DGV might not have internal linkage.
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000689 DGVar->eraseFromParent();
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000690
691 // Proceed to 'common' steps
692 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000693 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
694 "': symbol multiple defined");
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000695 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000696 // The only allowed way is to link alias with external declaration.
697 if (DF->isDeclaration()) {
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000698 // But only if aliasee is function too...
699 if (!isa<Function>(DAliasee))
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000700 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
701 "': aliasee is not function");
Anton Korobeynikov0a67e052008-03-10 22:36:53 +0000702
Anton Korobeynikovcdf208a2008-03-05 23:08:16 +0000703 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
704 SGA->getName(), DAliasee, Dest);
705 CopyGVAttributes(NewGA, SGA);
706
707 // Any uses of DF need to change to NewGA, with cast, if needed.
708 if (SGA->getType() != DF->getType())
709 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
710 DF->getType()));
711 else
712 DF->replaceAllUsesWith(NewGA);
713
714 // DF will conflict with NewGA because they both had the same
715 // name. We must erase this now so ForceRenaming doesn't assert
716 // because DF might not have internal linkage.
717 DF->eraseFromParent();
718
719 // Proceed to 'common' steps
720 } else
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000721 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
722 "': symbol multiple defined");
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000723 } else {
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000724 // No linking to be performed, simply create an identical version of the
725 // alias over in the dest module...
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000726
727 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
728 SGA->getName(), DAliasee, Dest);
729 CopyGVAttributes(NewGA, SGA);
730
731 // Proceed to 'common' steps
732 }
733
734 assert(NewGA && "No alias was created in destination module!");
735
Anton Korobeynikov552ccce2008-03-10 22:36:35 +0000736 // If the symbol table renamed the alias, but it is an externally visible
Anton Korobeynikov1b4f1f72008-05-10 14:41:43 +0000737 // symbol, DGA must be an global value with internal linkage. Rename it.
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000738 if (NewGA->getName() != SGA->getName() &&
739 !NewGA->hasInternalLinkage())
740 ForceRenaming(NewGA, SGA->getName());
741
742 // Remember this mapping so uses in the source module get remapped
743 // later by RemapOperand.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000744 ValueMap[SGA] = NewGA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 }
Anton Korobeynikovd0391562008-03-05 22:22:46 +0000746
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 return false;
748}
749
750
751// LinkGlobalInits - Update the initializers in the Dest module now that all
752// globals that may be referenced are in Dest.
753static bool LinkGlobalInits(Module *Dest, const Module *Src,
754 std::map<const Value*, Value*> &ValueMap,
755 std::string *Err) {
756
757 // Loop over all of the globals in the src module, mapping them over as we go
758 for (Module::const_global_iterator I = Src->global_begin(),
759 E = Src->global_end(); I != E; ++I) {
760 const GlobalVariable *SGV = I;
761
762 if (SGV->hasInitializer()) { // Only process initialized GV's
763 // Figure out what the initializer looks like in the dest module...
764 Constant *SInit =
765 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
766
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +0000767 GlobalVariable *DGV =
768 cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 if (DGV->hasInitializer()) {
770 if (SGV->hasExternalLinkage()) {
771 if (DGV->getInitializer() != SInit)
Anton Korobeynikov82a21e42008-03-10 22:34:46 +0000772 return Error(Err, "Global Variable Collision on '" + SGV->getName() +
773 "': global variables have different initializers");
Dale Johannesen49c44122008-05-14 20:12:51 +0000774 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
775 DGV->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000776 // Nothing is required, mapped values will take the new global
777 // automatically.
Dale Johannesen49c44122008-05-14 20:12:51 +0000778 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
779 SGV->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 // Nothing is required, mapped values will take the new global
781 // automatically.
782 } else if (DGV->hasAppendingLinkage()) {
783 assert(0 && "Appending linkage unimplemented!");
784 } else {
785 assert(0 && "Unknown linkage!");
786 }
787 } else {
788 // Copy the initializer over now...
789 DGV->setInitializer(SInit);
790 }
791 }
792 }
793 return false;
794}
795
796// LinkFunctionProtos - Link the functions together between the two modules,
797// without doing function bodies... this just adds external function prototypes
798// to the Dest function...
799//
800static bool LinkFunctionProtos(Module *Dest, const Module *Src,
801 std::map<const Value*, Value*> &ValueMap,
802 std::string *Err) {
803 // Loop over all of the functions in the src module, mapping them over
804 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
805 const Function *SF = I; // SrcFunction
Chris Lattner1426bfa2008-06-09 07:36:11 +0000806
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 Function *DF = 0;
Chris Lattner1426bfa2008-06-09 07:36:11 +0000808
809 // If this function is internal or has no name, it doesn't participate in
810 // linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 if (SF->hasName() && !SF->hasInternalLinkage()) {
812 // Check to see if may have to link the function.
813 DF = Dest->getFunction(SF->getName());
Chris Lattner1426bfa2008-06-09 07:36:11 +0000814 if (DF && DF->hasInternalLinkage())
815 DF = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000816 }
Chris Lattnerf7e84192008-06-09 07:25:28 +0000817
Chris Lattner1426bfa2008-06-09 07:36:11 +0000818 // If there is no linkage to be performed, just bring over SF without
819 // modifying it.
820 if (DF == 0) {
821 // Function does not already exist, simply insert an function signature
822 // identical to SF into the dest module.
823 Function *NewDF = Function::Create(SF->getFunctionType(),
824 SF->getLinkage(),
825 SF->getName(), Dest);
826 CopyGVAttributes(NewDF, SF);
827
828 // If the LLVM runtime renamed the function, but it is an externally
829 // visible symbol, DF must be an existing function with internal linkage.
830 // Rename it.
831 if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
832 ForceRenaming(NewDF, SF->getName());
833
834 // ... and remember this mapping...
835 ValueMap[SF] = NewDF;
836 continue;
837 }
838
839
840 // If types don't agree because of opaque, try to resolve them.
841 if (SF->getType() != DF->getType())
Chris Lattner06638ab2008-06-16 18:19:05 +0000842 RecursiveResolveTypes(SF->getType(), DF->getType());
Chris Lattner1426bfa2008-06-09 07:36:11 +0000843
844 // Check visibility, merging if a definition overrides a prototype.
845 if (SF->getVisibility() != DF->getVisibility()) {
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000846 // If one is a prototype, ignore its visibility. Prototypes are always
847 // overridden by the definition.
848 if (!SF->isDeclaration() && !DF->isDeclaration())
849 return Error(Err, "Linking functions named '" + SF->getName() +
850 "': symbols have different visibilities!");
Chris Lattnerf7e84192008-06-09 07:25:28 +0000851
852 // Otherwise, replace the visibility of DF if DF is a prototype.
853 if (DF->isDeclaration())
854 DF->setVisibility(SF->getVisibility());
Chris Lattnerb69fcb82007-08-19 22:22:54 +0000855 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856
Chris Lattner1426bfa2008-06-09 07:36:11 +0000857 if (DF->getType() != SF->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 if (DF->isDeclaration() && !SF->isDeclaration()) {
859 // We have a definition of the same name but different type in the
860 // source module. Copy the prototype to the destination and replace
861 // uses of the destination's prototype with the new prototype.
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000862 Function *NewDF = Function::Create(SF->getFunctionType(),
863 SF->getLinkage(),
Gabor Greifd6da1d02008-04-06 20:25:17 +0000864 SF->getName(), Dest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 CopyGVAttributes(NewDF, SF);
866
867 // Any uses of DF need to change to NewDF, with cast
868 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
869
870 // DF will conflict with NewDF because they both had the same. We must
871 // erase this now so ForceRenaming doesn't assert because DF might
872 // not have internal linkage.
873 DF->eraseFromParent();
874
875 // If the symbol table renamed the function, but it is an externally
876 // visible symbol, DF must be an existing function with internal
877 // linkage. Rename it.
878 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
879 ForceRenaming(NewDF, SF->getName());
880
881 // Remember this mapping so uses in the source module get remapped
882 // later by RemapOperand.
883 ValueMap[SF] = NewDF;
884 } else if (SF->isDeclaration()) {
885 // We have two functions of the same name but different type and the
886 // source is a declaration while the destination is not. Any use of
887 // the source must be mapped to the destination, with a cast.
888 ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType());
889 } else {
890 // We have two functions of the same name but different types and they
891 // are both definitions. This is an error.
892 return Error(Err, "Function '" + DF->getName() + "' defined as both '" +
893 ToStr(SF->getFunctionType(), Src) + "' and '" +
894 ToStr(DF->getFunctionType(), Dest) + "'");
895 }
Chris Lattner1426bfa2008-06-09 07:36:11 +0000896 continue;
897 }
898
899 if (SF->isDeclaration()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 // If SF is a declaration or if both SF & DF are declarations, just link
901 // the declarations, we aren't adding anything.
902 if (SF->hasDLLImportLinkage()) {
903 if (DF->isDeclaration()) {
Chris Lattnerc082fd42008-06-09 07:47:34 +0000904 ValueMap[SF] = DF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000906 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 } else {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000908 ValueMap[SF] = DF;
Chris Lattnerc082fd42008-06-09 07:47:34 +0000909 }
910 continue;
911 }
912
913 // If DF is external but SF is not, link the external functions, update
914 // linkage qualifiers.
915 if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 ValueMap.insert(std::make_pair(SF, DF));
917 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000918 continue;
919 }
920
921 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
922 if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
923 SF->hasCommonLinkage()) {
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000924 ValueMap[SF] = DF;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925
926 // Linkonce+Weak = Weak
927 // *+External Weak = *
Dale Johannesen49c44122008-05-14 20:12:51 +0000928 if ((DF->hasLinkOnceLinkage() &&
929 (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 DF->hasExternalWeakLinkage())
931 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000932 continue;
933 }
934
935 if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
936 DF->hasCommonLinkage()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 // At this point we know that SF has LinkOnce or External* linkage.
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000938 ValueMap[SF] = DF;
Chris Lattnerc082fd42008-06-09 07:47:34 +0000939
940 // If the source function has stronger linkage than the destination,
941 // its body and linkage should override ours.
942 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
943 // Don't inherit linkonce & external weak linkage.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 DF->setLinkage(SF->getLinkage());
Chris Lattnerc082fd42008-06-09 07:47:34 +0000945 DF->deleteBody();
946 }
947 continue;
948 }
949
950 if (SF->getLinkage() != DF->getLinkage())
951 return Error(Err, "Functions named '" + SF->getName() +
952 "' have different linkage specifiers!");
953
954 // The function is defined identically in both modules!
955 if (SF->hasExternalLinkage())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 return Error(Err, "Function '" +
957 ToStr(SF->getFunctionType(), Src) + "':\"" +
958 SF->getName() + "\" - Function is already defined!");
Chris Lattnerc082fd42008-06-09 07:47:34 +0000959 assert(0 && "Unknown linkage configuration found!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960 }
961 return false;
962}
963
964// LinkFunctionBody - Copy the source function over into the dest function and
965// fix up references to values. At this point we know that Dest is an external
966// function, and that Src is not.
967static bool LinkFunctionBody(Function *Dest, Function *Src,
968 std::map<const Value*, Value*> &ValueMap,
969 std::string *Err) {
970 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
971
972 // Go through and convert function arguments over, remembering the mapping.
973 Function::arg_iterator DI = Dest->arg_begin();
974 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
975 I != E; ++I, ++DI) {
Owen Andersonab567f82008-04-14 17:38:21 +0000976 DI->setName(I->getName()); // Copy the name information over...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977
978 // Add a mapping to our local map
Anton Korobeynikovef1eb5e2008-03-10 22:36:08 +0000979 ValueMap[I] = DI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 }
981
982 // Splice the body of the source function into the dest function.
983 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
984
985 // At this point, all of the instructions and values of the function are now
986 // copied over. The only problem is that they are still referencing values in
987 // the Source function as operands. Loop through all of the operands of the
988 // functions and patch them up to point to the local versions...
989 //
990 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
991 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
992 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
993 OI != OE; ++OI)
994 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
995 *OI = RemapOperand(*OI, ValueMap);
996
997 // There is no need to map the arguments anymore.
998 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
999 I != E; ++I)
1000 ValueMap.erase(I);
1001
1002 return false;
1003}
1004
1005
1006// LinkFunctionBodies - Link in the function bodies that are defined in the
1007// source module into the DestModule. This consists basically of copying the
1008// function over and fixing up references to values.
1009static bool LinkFunctionBodies(Module *Dest, Module *Src,
1010 std::map<const Value*, Value*> &ValueMap,
1011 std::string *Err) {
1012
1013 // Loop over all of the functions in the src module, mapping them over as we
1014 // go
1015 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1016 if (!SF->isDeclaration()) { // No body if function is external
1017 Function *DF = cast<Function>(ValueMap[SF]); // Destination function
1018
1019 // DF not external SF external?
1020 if (DF->isDeclaration())
1021 // Only provide the function body if there isn't one already.
1022 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1023 return true;
1024 }
1025 }
1026 return false;
1027}
1028
1029// LinkAppendingVars - If there were any appending global variables, link them
1030// together now. Return true on error.
1031static bool LinkAppendingVars(Module *M,
1032 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1033 std::string *ErrorMsg) {
1034 if (AppendingVars.empty()) return false; // Nothing to do.
1035
1036 // Loop over the multimap of appending vars, processing any variables with the
1037 // same name, forming a new appending global variable with both of the
1038 // initializers merged together, then rewrite references to the old variables
1039 // and delete them.
1040 std::vector<Constant*> Inits;
1041 while (AppendingVars.size() > 1) {
1042 // Get the first two elements in the map...
1043 std::multimap<std::string,
1044 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1045
1046 // If the first two elements are for different names, there is no pair...
1047 // Otherwise there is a pair, so link them together...
1048 if (First->first == Second->first) {
1049 GlobalVariable *G1 = First->second, *G2 = Second->second;
1050 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1051 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1052
1053 // Check to see that they two arrays agree on type...
1054 if (T1->getElementType() != T2->getElementType())
1055 return Error(ErrorMsg,
1056 "Appending variables with different element types need to be linked!");
1057 if (G1->isConstant() != G2->isConstant())
1058 return Error(ErrorMsg,
1059 "Appending variables linked with different const'ness!");
1060
1061 if (G1->getAlignment() != G2->getAlignment())
1062 return Error(ErrorMsg,
1063 "Appending variables with different alignment need to be linked!");
1064
1065 if (G1->getVisibility() != G2->getVisibility())
1066 return Error(ErrorMsg,
1067 "Appending variables with different visibility need to be linked!");
1068
1069 if (G1->getSection() != G2->getSection())
1070 return Error(ErrorMsg,
1071 "Appending variables with different section name need to be linked!");
1072
1073 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1074 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1075
1076 G1->setName(""); // Clear G1's name in case of a conflict!
1077
1078 // Create the new global variable...
1079 GlobalVariable *NG =
1080 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
1081 /*init*/0, First->first, M, G1->isThreadLocal());
1082
1083 // Propagate alignment, visibility and section info.
1084 CopyGVAttributes(NG, G1);
1085
1086 // Merge the initializer...
1087 Inits.reserve(NewSize);
1088 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1089 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1090 Inits.push_back(I->getOperand(i));
1091 } else {
1092 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1093 Constant *CV = Constant::getNullValue(T1->getElementType());
1094 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1095 Inits.push_back(CV);
1096 }
1097 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1098 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1099 Inits.push_back(I->getOperand(i));
1100 } else {
1101 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1102 Constant *CV = Constant::getNullValue(T2->getElementType());
1103 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1104 Inits.push_back(CV);
1105 }
1106 NG->setInitializer(ConstantArray::get(NewType, Inits));
1107 Inits.clear();
1108
1109 // Replace any uses of the two global variables with uses of the new
1110 // global...
1111
1112 // FIXME: This should rewrite simple/straight-forward uses such as
1113 // getelementptr instructions to not use the Cast!
1114 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1115 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
1116
1117 // Remove the two globals from the module now...
1118 M->getGlobalList().erase(G1);
1119 M->getGlobalList().erase(G2);
1120
1121 // Put the new global into the AppendingVars map so that we can handle
1122 // linking of more than two vars...
1123 Second->second = NG;
1124 }
1125 AppendingVars.erase(First);
1126 }
1127
1128 return false;
1129}
1130
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001131static bool ResolveAliases(Module *Dest) {
1132 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
Anton Korobeynikov82192622008-03-11 22:51:09 +00001133 I != E; ++I)
1134 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1135 if (!GV->isDeclaration())
1136 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
Anton Korobeynikovfdad2d82008-03-05 23:21:39 +00001137
1138 return false;
1139}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140
1141// LinkModules - This function links two modules together, with the resulting
1142// left module modified to be the composite of the two input modules. If an
1143// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1144// the problem. Upon failure, the Dest module could be in a modified state, and
1145// shouldn't be relied on to be consistent.
1146bool
1147Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1148 assert(Dest != 0 && "Invalid Destination module");
1149 assert(Src != 0 && "Invalid Source Module");
1150
1151 if (Dest->getDataLayout().empty()) {
1152 if (!Src->getDataLayout().empty()) {
1153 Dest->setDataLayout(Src->getDataLayout());
1154 } else {
1155 std::string DataLayout;
1156
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001157 if (Dest->getEndianness() == Module::AnyEndianness) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 if (Src->getEndianness() == Module::BigEndian)
1159 DataLayout.append("E");
1160 else if (Src->getEndianness() == Module::LittleEndian)
1161 DataLayout.append("e");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001162 }
1163
1164 if (Dest->getPointerSize() == Module::AnyPointerSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 if (Src->getPointerSize() == Module::Pointer64)
1166 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1167 else if (Src->getPointerSize() == Module::Pointer32)
1168 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
Anton Korobeynikovfb782ce2008-02-20 11:27:04 +00001169 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 Dest->setDataLayout(DataLayout);
1171 }
1172 }
1173
Chris Lattner85dd49c2008-02-19 18:49:08 +00001174 // Copy the target triple from the source to dest if the dest's is empty.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1176 Dest->setTargetTriple(Src->getTargetTriple());
1177
1178 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1179 Src->getDataLayout() != Dest->getDataLayout())
1180 cerr << "WARNING: Linking two modules of different data layouts!\n";
1181 if (!Src->getTargetTriple().empty() &&
1182 Dest->getTargetTriple() != Src->getTargetTriple())
1183 cerr << "WARNING: Linking two modules of different target triples!\n";
1184
Chris Lattner85dd49c2008-02-19 18:49:08 +00001185 // Append the module inline asm string.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 if (!Src->getModuleInlineAsm().empty()) {
1187 if (Dest->getModuleInlineAsm().empty())
1188 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1189 else
1190 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1191 Src->getModuleInlineAsm());
1192 }
1193
1194 // Update the destination module's dependent libraries list with the libraries
1195 // from the source module. There's no opportunity for duplicates here as the
1196 // Module ensures that duplicate insertions are discarded.
Chris Lattner85dd49c2008-02-19 18:49:08 +00001197 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1198 SI != SE; ++SI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001199 Dest->addLibrary(*SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200
1201 // LinkTypes - Go through the symbol table of the Src module and see if any
1202 // types are named in the src module that are not named in the Dst module.
1203 // Make sure there are no type name conflicts.
1204 if (LinkTypes(Dest, Src, ErrorMsg))
1205 return true;
1206
1207 // ValueMap - Mapping of values from what they used to be in Src, to what they
1208 // are now in Dest.
1209 std::map<const Value*, Value*> ValueMap;
1210
1211 // AppendingVars - Keep track of global variables in the destination module
1212 // with appending linkage. After the module is linked together, they are
1213 // appended and the module is rewritten.
1214 std::multimap<std::string, GlobalVariable *> AppendingVars;
1215 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1216 I != E; ++I) {
1217 // Add all of the appending globals already in the Dest module to
1218 // AppendingVars.
1219 if (I->hasAppendingLinkage())
1220 AppendingVars.insert(std::make_pair(I->getName(), I));
1221 }
1222
1223 // Insert all of the globals in src into the Dest module... without linking
1224 // initializers (which could refer to functions not yet mapped over).
1225 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1226 return true;
1227
1228 // Link the functions together between the two modules, without doing function
1229 // bodies... this just adds external function prototypes to the Dest
1230 // function... We do this so that when we begin processing function bodies,
1231 // all of the global values that may be referenced are available in our
1232 // ValueMap.
1233 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1234 return true;
1235
Anton Korobeynikov3cfecfd2008-03-05 15:27:21 +00001236 // If there were any alias, link them now. We really need to do this now,
1237 // because all of the aliases that may be referenced need to be available in
1238 // ValueMap
1239 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1240
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 // Update the initializers in the Dest module now that all globals that may
1242 // be referenced are in Dest.
1243 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1244
1245 // Link in the function bodies that are defined in the source module into the
1246 // DestModule. This consists basically of copying the function over and
1247 // fixing up references to values.
1248 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1249
1250 // If there were any appending global variables, link them together now.
1251 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1252
Anton Korobeynikova68796c2008-03-05 23:08:47 +00001253 // Resolve all uses of aliases with aliasees
1254 if (ResolveAliases(Dest)) return true;
1255
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 // If the source library's module id is in the dependent library list of the
1257 // destination library, remove it since that module is now linked in.
1258 sys::Path modId;
1259 modId.set(Src->getModuleIdentifier());
1260 if (!modId.isEmpty())
1261 Dest->removeLibrary(modId.getBasename());
1262
1263 return false;
1264}
1265
1266// vim: sw=2