1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM module linker.
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
17 //===----------------------------------------------------------------------===//
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 "llvm/ADT/DenseMap.h"
33 // Error - Simple wrapper function to conditionally assign to E and return true.
34 // This just makes error return conditions a little bit simpler...
35 static inline bool Error(std::string
*E
, const std::string
&Message
) {
40 // Function: ResolveTypes()
43 // Attempt to link the two specified types together.
46 // DestTy - The type to which we wish to resolve.
47 // SrcTy - The original type which we want to resolve.
50 // DestST - The symbol table in which the new type should be placed.
53 // true - There is an error and the types cannot yet be linked.
56 static bool ResolveTypes(const Type
*DestTy
, const Type
*SrcTy
) {
57 if (DestTy
== SrcTy
) return false; // If already equal, noop
58 assert(DestTy
&& SrcTy
&& "Can't handle null types");
60 if (const OpaqueType
*OT
= dyn_cast
<OpaqueType
>(DestTy
)) {
61 // Type _is_ in module, just opaque...
62 const_cast<OpaqueType
*>(OT
)->refineAbstractTypeTo(SrcTy
);
63 } else if (const OpaqueType
*OT
= dyn_cast
<OpaqueType
>(SrcTy
)) {
64 const_cast<OpaqueType
*>(OT
)->refineAbstractTypeTo(DestTy
);
66 return true; // Cannot link types... not-equal and neither is opaque.
71 /// LinkerTypeMap - This implements a map of types that is stable
72 /// even if types are resolved/refined to other types. This is not a general
73 /// purpose map, it is specific to the linker's use.
75 class LinkerTypeMap
: public AbstractTypeUser
{
76 typedef DenseMap
<const Type
*, PATypeHolder
> TheMapTy
;
79 LinkerTypeMap(const LinkerTypeMap
&); // DO NOT IMPLEMENT
80 void operator=(const LinkerTypeMap
&); // DO NOT IMPLEMENT
84 for (DenseMap
<const Type
*, PATypeHolder
>::iterator I
= TheMap
.begin(),
85 E
= TheMap
.end(); I
!= E
; ++I
)
86 I
->first
->removeAbstractTypeUser(this);
89 /// lookup - Return the value for the specified type or null if it doesn't
91 const Type
*lookup(const Type
*Ty
) const {
92 TheMapTy::const_iterator I
= TheMap
.find(Ty
);
93 if (I
!= TheMap
.end()) return I
->second
;
97 /// erase - Remove the specified type, returning true if it was in the set.
98 bool erase(const Type
*Ty
) {
99 if (!TheMap
.erase(Ty
))
101 if (Ty
->isAbstract())
102 Ty
->removeAbstractTypeUser(this);
106 /// insert - This returns true if the pointer was new to the set, false if it
107 /// was already in the set.
108 bool insert(const Type
*Src
, const Type
*Dst
) {
109 if (!TheMap
.insert(std::make_pair(Src
, PATypeHolder(Dst
))).second
)
110 return false; // Already in map.
111 if (Src
->isAbstract())
112 Src
->addAbstractTypeUser(this);
117 /// refineAbstractType - The callback method invoked when an abstract type is
118 /// resolved to another type. An object must override this method to update
119 /// its internal state to reference NewType instead of OldType.
121 virtual void refineAbstractType(const DerivedType
*OldTy
,
123 TheMapTy::iterator I
= TheMap
.find(OldTy
);
124 const Type
*DstTy
= I
->second
;
127 if (OldTy
->isAbstract())
128 OldTy
->removeAbstractTypeUser(this);
130 // Don't reinsert into the map if the key is concrete now.
131 if (NewTy
->isAbstract())
132 insert(NewTy
, DstTy
);
135 /// The other case which AbstractTypeUsers must be aware of is when a type
136 /// makes the transition from being abstract (where it has clients on it's
137 /// AbstractTypeUsers list) to concrete (where it does not). This method
138 /// notifies ATU's when this occurs for a type.
139 virtual void typeBecameConcrete(const DerivedType
*AbsTy
) {
141 AbsTy
->removeAbstractTypeUser(this);
145 virtual void dump() const {
146 cerr
<< "AbstractTypeSet!\n";
152 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
153 // recurses down into derived types, merging the used types if the parent types
155 static bool RecursiveResolveTypesI(const Type
*DstTy
, const Type
*SrcTy
,
156 LinkerTypeMap
&Pointers
) {
157 if (DstTy
== SrcTy
) return false; // If already equal, noop
159 // If we found our opaque type, resolve it now!
160 if (isa
<OpaqueType
>(DstTy
) || isa
<OpaqueType
>(SrcTy
))
161 return ResolveTypes(DstTy
, SrcTy
);
163 // Two types cannot be resolved together if they are of different primitive
164 // type. For example, we cannot resolve an int to a float.
165 if (DstTy
->getTypeID() != SrcTy
->getTypeID()) return true;
167 // If neither type is abstract, then they really are just different types.
168 if (!DstTy
->isAbstract() && !SrcTy
->isAbstract())
171 // Otherwise, resolve the used type used by this derived type...
172 switch (DstTy
->getTypeID()) {
175 case Type::FunctionTyID
: {
176 const FunctionType
*DstFT
= cast
<FunctionType
>(DstTy
);
177 const FunctionType
*SrcFT
= cast
<FunctionType
>(SrcTy
);
178 if (DstFT
->isVarArg() != SrcFT
->isVarArg() ||
179 DstFT
->getNumContainedTypes() != SrcFT
->getNumContainedTypes())
182 // Use TypeHolder's so recursive resolution won't break us.
183 PATypeHolder
ST(SrcFT
), DT(DstFT
);
184 for (unsigned i
= 0, e
= DstFT
->getNumContainedTypes(); i
!= e
; ++i
) {
185 const Type
*SE
= ST
->getContainedType(i
), *DE
= DT
->getContainedType(i
);
186 if (SE
!= DE
&& RecursiveResolveTypesI(DE
, SE
, Pointers
))
191 case Type::StructTyID
: {
192 const StructType
*DstST
= cast
<StructType
>(DstTy
);
193 const StructType
*SrcST
= cast
<StructType
>(SrcTy
);
194 if (DstST
->getNumContainedTypes() != SrcST
->getNumContainedTypes())
197 PATypeHolder
ST(SrcST
), DT(DstST
);
198 for (unsigned i
= 0, e
= DstST
->getNumContainedTypes(); i
!= e
; ++i
) {
199 const Type
*SE
= ST
->getContainedType(i
), *DE
= DT
->getContainedType(i
);
200 if (SE
!= DE
&& RecursiveResolveTypesI(DE
, SE
, Pointers
))
205 case Type::ArrayTyID
: {
206 const ArrayType
*DAT
= cast
<ArrayType
>(DstTy
);
207 const ArrayType
*SAT
= cast
<ArrayType
>(SrcTy
);
208 if (DAT
->getNumElements() != SAT
->getNumElements()) return true;
209 return RecursiveResolveTypesI(DAT
->getElementType(), SAT
->getElementType(),
212 case Type::VectorTyID
: {
213 const VectorType
*DVT
= cast
<VectorType
>(DstTy
);
214 const VectorType
*SVT
= cast
<VectorType
>(SrcTy
);
215 if (DVT
->getNumElements() != SVT
->getNumElements()) return true;
216 return RecursiveResolveTypesI(DVT
->getElementType(), SVT
->getElementType(),
219 case Type::PointerTyID
: {
220 const PointerType
*DstPT
= cast
<PointerType
>(DstTy
);
221 const PointerType
*SrcPT
= cast
<PointerType
>(SrcTy
);
223 if (DstPT
->getAddressSpace() != SrcPT
->getAddressSpace())
226 // If this is a pointer type, check to see if we have already seen it. If
227 // so, we are in a recursive branch. Cut off the search now. We cannot use
228 // an associative container for this search, because the type pointers (keys
229 // in the container) change whenever types get resolved.
230 if (SrcPT
->isAbstract())
231 if (const Type
*ExistingDestTy
= Pointers
.lookup(SrcPT
))
232 return ExistingDestTy
!= DstPT
;
234 if (DstPT
->isAbstract())
235 if (const Type
*ExistingSrcTy
= Pointers
.lookup(DstPT
))
236 return ExistingSrcTy
!= SrcPT
;
237 // Otherwise, add the current pointers to the vector to stop recursion on
239 if (DstPT
->isAbstract())
240 Pointers
.insert(DstPT
, SrcPT
);
241 if (SrcPT
->isAbstract())
242 Pointers
.insert(SrcPT
, DstPT
);
244 return RecursiveResolveTypesI(DstPT
->getElementType(),
245 SrcPT
->getElementType(), Pointers
);
250 static bool RecursiveResolveTypes(const Type
*DestTy
, const Type
*SrcTy
) {
251 LinkerTypeMap PointerTypes
;
252 return RecursiveResolveTypesI(DestTy
, SrcTy
, PointerTypes
);
256 // LinkTypes - Go through the symbol table of the Src module and see if any
257 // types are named in the src module that are not named in the Dst module.
258 // Make sure there are no type name conflicts.
259 static bool LinkTypes(Module
*Dest
, const Module
*Src
, std::string
*Err
) {
260 TypeSymbolTable
*DestST
= &Dest
->getTypeSymbolTable();
261 const TypeSymbolTable
*SrcST
= &Src
->getTypeSymbolTable();
263 // Look for a type plane for Type's...
264 TypeSymbolTable::const_iterator TI
= SrcST
->begin();
265 TypeSymbolTable::const_iterator TE
= SrcST
->end();
266 if (TI
== TE
) return false; // No named types, do nothing.
268 // Some types cannot be resolved immediately because they depend on other
269 // types being resolved to each other first. This contains a list of types we
270 // are waiting to recheck.
271 std::vector
<std::string
> DelayedTypesToResolve
;
273 for ( ; TI
!= TE
; ++TI
) {
274 const std::string
&Name
= TI
->first
;
275 const Type
*RHS
= TI
->second
;
277 // Check to see if this type name is already in the dest module.
278 Type
*Entry
= DestST
->lookup(Name
);
280 // If the name is just in the source module, bring it over to the dest.
283 DestST
->insert(Name
, const_cast<Type
*>(RHS
));
284 } else if (ResolveTypes(Entry
, RHS
)) {
285 // They look different, save the types 'till later to resolve.
286 DelayedTypesToResolve
.push_back(Name
);
290 // Iteratively resolve types while we can...
291 while (!DelayedTypesToResolve
.empty()) {
292 // Loop over all of the types, attempting to resolve them if possible...
293 unsigned OldSize
= DelayedTypesToResolve
.size();
295 // Try direct resolution by name...
296 for (unsigned i
= 0; i
!= DelayedTypesToResolve
.size(); ++i
) {
297 const std::string
&Name
= DelayedTypesToResolve
[i
];
298 Type
*T1
= SrcST
->lookup(Name
);
299 Type
*T2
= DestST
->lookup(Name
);
300 if (!ResolveTypes(T2
, T1
)) {
301 // We are making progress!
302 DelayedTypesToResolve
.erase(DelayedTypesToResolve
.begin()+i
);
307 // Did we not eliminate any types?
308 if (DelayedTypesToResolve
.size() == OldSize
) {
309 // Attempt to resolve subelements of types. This allows us to merge these
310 // two types: { int* } and { opaque* }
311 for (unsigned i
= 0, e
= DelayedTypesToResolve
.size(); i
!= e
; ++i
) {
312 const std::string
&Name
= DelayedTypesToResolve
[i
];
313 if (!RecursiveResolveTypes(SrcST
->lookup(Name
), DestST
->lookup(Name
))) {
314 // We are making progress!
315 DelayedTypesToResolve
.erase(DelayedTypesToResolve
.begin()+i
);
317 // Go back to the main loop, perhaps we can resolve directly by name
323 // If we STILL cannot resolve the types, then there is something wrong.
324 if (DelayedTypesToResolve
.size() == OldSize
) {
325 // Remove the symbol name from the destination.
326 DelayedTypesToResolve
.pop_back();
336 static void PrintMap(const std::map
<const Value
*, Value
*> &M
) {
337 for (std::map
<const Value
*, Value
*>::const_iterator I
= M
.begin(), E
=M
.end();
339 cerr
<< " Fr: " << (void*)I
->first
<< " ";
341 cerr
<< " To: " << (void*)I
->second
<< " ";
349 // RemapOperand - Use ValueMap to convert constants from one module to another.
350 static Value
*RemapOperand(const Value
*In
,
351 std::map
<const Value
*, Value
*> &ValueMap
) {
352 std::map
<const Value
*,Value
*>::const_iterator I
= ValueMap
.find(In
);
353 if (I
!= ValueMap
.end())
356 // Check to see if it's a constant that we are interested in transforming.
358 if (const Constant
*CPV
= dyn_cast
<Constant
>(In
)) {
359 if ((!isa
<DerivedType
>(CPV
->getType()) && !isa
<ConstantExpr
>(CPV
)) ||
360 isa
<ConstantInt
>(CPV
) || isa
<ConstantAggregateZero
>(CPV
))
361 return const_cast<Constant
*>(CPV
); // Simple constants stay identical.
363 if (const ConstantArray
*CPA
= dyn_cast
<ConstantArray
>(CPV
)) {
364 std::vector
<Constant
*> Operands(CPA
->getNumOperands());
365 for (unsigned i
= 0, e
= CPA
->getNumOperands(); i
!= e
; ++i
)
366 Operands
[i
] =cast
<Constant
>(RemapOperand(CPA
->getOperand(i
), ValueMap
));
367 Result
= ConstantArray::get(cast
<ArrayType
>(CPA
->getType()), Operands
);
368 } else if (const ConstantStruct
*CPS
= dyn_cast
<ConstantStruct
>(CPV
)) {
369 std::vector
<Constant
*> Operands(CPS
->getNumOperands());
370 for (unsigned i
= 0, e
= CPS
->getNumOperands(); i
!= e
; ++i
)
371 Operands
[i
] =cast
<Constant
>(RemapOperand(CPS
->getOperand(i
), ValueMap
));
372 Result
= ConstantStruct::get(cast
<StructType
>(CPS
->getType()), Operands
);
373 } else if (isa
<ConstantPointerNull
>(CPV
) || isa
<UndefValue
>(CPV
)) {
374 Result
= const_cast<Constant
*>(CPV
);
375 } else if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(CPV
)) {
376 std::vector
<Constant
*> Operands(CP
->getNumOperands());
377 for (unsigned i
= 0, e
= CP
->getNumOperands(); i
!= e
; ++i
)
378 Operands
[i
] = cast
<Constant
>(RemapOperand(CP
->getOperand(i
), ValueMap
));
379 Result
= ConstantVector::get(Operands
);
380 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(CPV
)) {
381 std::vector
<Constant
*> Ops
;
382 for (unsigned i
= 0, e
= CE
->getNumOperands(); i
!= e
; ++i
)
383 Ops
.push_back(cast
<Constant
>(RemapOperand(CE
->getOperand(i
),ValueMap
)));
384 Result
= CE
->getWithOperands(Ops
);
386 assert(!isa
<GlobalValue
>(CPV
) && "Unmapped global?");
387 assert(0 && "Unknown type of derived type constant value!");
389 } else if (isa
<InlineAsm
>(In
)) {
390 Result
= const_cast<Value
*>(In
);
393 // Cache the mapping in our local map structure
395 ValueMap
[In
] = Result
;
400 cerr
<< "LinkModules ValueMap: \n";
403 cerr
<< "Couldn't remap value: " << (void*)In
<< " " << *In
<< "\n";
404 assert(0 && "Couldn't remap value!");
409 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
410 /// in the symbol table. This is good for all clients except for us. Go
411 /// through the trouble to force this back.
412 static void ForceRenaming(GlobalValue
*GV
, const std::string
&Name
) {
413 assert(GV
->getName() != Name
&& "Can't force rename to self");
414 ValueSymbolTable
&ST
= GV
->getParent()->getValueSymbolTable();
416 // If there is a conflict, rename the conflict.
417 if (GlobalValue
*ConflictGV
= cast_or_null
<GlobalValue
>(ST
.lookup(Name
))) {
418 assert(ConflictGV
->hasLocalLinkage() &&
419 "Not conflicting with a static global, should link instead!");
420 GV
->takeName(ConflictGV
);
421 ConflictGV
->setName(Name
); // This will cause ConflictGV to get renamed
422 assert(ConflictGV
->getName() != Name
&& "ForceRenaming didn't work");
424 GV
->setName(Name
); // Force the name back
428 /// CopyGVAttributes - copy additional attributes (those not needed to construct
429 /// a GlobalValue) from the SrcGV to the DestGV.
430 static void CopyGVAttributes(GlobalValue
*DestGV
, const GlobalValue
*SrcGV
) {
431 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
432 unsigned Alignment
= std::max(DestGV
->getAlignment(), SrcGV
->getAlignment());
433 DestGV
->copyAttributesFrom(SrcGV
);
434 DestGV
->setAlignment(Alignment
);
437 /// GetLinkageResult - This analyzes the two global values and determines what
438 /// the result will look like in the destination module. In particular, it
439 /// computes the resultant linkage type, computes whether the global in the
440 /// source should be copied over to the destination (replacing the existing
441 /// one), and computes whether this linkage is an error or not. It also performs
442 /// visibility checks: we cannot link together two symbols with different
444 static bool GetLinkageResult(GlobalValue
*Dest
, const GlobalValue
*Src
,
445 GlobalValue::LinkageTypes
<
, bool &LinkFromSrc
,
447 assert((!Dest
|| !Src
->hasLocalLinkage()) &&
448 "If Src has internal linkage, Dest shouldn't be set!");
450 // Linking something to nothing.
452 LT
= Src
->getLinkage();
453 } else if (Src
->isDeclaration()) {
454 // If Src is external or if both Src & Dest are external.. Just link the
455 // external globals, we aren't adding anything.
456 if (Src
->hasDLLImportLinkage()) {
457 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
458 if (Dest
->isDeclaration()) {
460 LT
= Src
->getLinkage();
462 } else if (Dest
->hasExternalWeakLinkage()) {
463 // If the Dest is weak, use the source linkage.
465 LT
= Src
->getLinkage();
468 LT
= Dest
->getLinkage();
470 } else if (Dest
->isDeclaration() && !Dest
->hasDLLImportLinkage()) {
471 // If Dest is external but Src is not:
473 LT
= Src
->getLinkage();
474 } else if (Src
->hasAppendingLinkage() || Dest
->hasAppendingLinkage()) {
475 if (Src
->getLinkage() != Dest
->getLinkage())
476 return Error(Err
, "Linking globals named '" + Src
->getName() +
477 "': can only link appending global with another appending global!");
478 LinkFromSrc
= true; // Special cased.
479 LT
= Src
->getLinkage();
480 } else if (Src
->isWeakForLinker()) {
481 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
483 if (Dest
->hasExternalWeakLinkage() ||
484 Dest
->hasAvailableExternallyLinkage() ||
485 (Dest
->hasLinkOnceLinkage() &&
486 (Src
->hasWeakLinkage() || Src
->hasCommonLinkage()))) {
488 LT
= Src
->getLinkage();
491 LT
= Dest
->getLinkage();
493 } else if (Dest
->isWeakForLinker()) {
494 // At this point we know that Src has External* or DLL* linkage.
495 if (Src
->hasExternalWeakLinkage()) {
497 LT
= Dest
->getLinkage();
500 LT
= GlobalValue::ExternalLinkage
;
503 assert((Dest
->hasExternalLinkage() ||
504 Dest
->hasDLLImportLinkage() ||
505 Dest
->hasDLLExportLinkage() ||
506 Dest
->hasExternalWeakLinkage()) &&
507 (Src
->hasExternalLinkage() ||
508 Src
->hasDLLImportLinkage() ||
509 Src
->hasDLLExportLinkage() ||
510 Src
->hasExternalWeakLinkage()) &&
511 "Unexpected linkage type!");
512 return Error(Err
, "Linking globals named '" + Src
->getName() +
513 "': symbol multiply defined!");
517 if (Dest
&& Src
->getVisibility() != Dest
->getVisibility())
518 if (!Src
->isDeclaration() && !Dest
->isDeclaration())
519 return Error(Err
, "Linking globals named '" + Src
->getName() +
520 "': symbols have different visibilities!");
524 // LinkGlobals - Loop through the global variables in the src module and merge
525 // them into the dest module.
526 static bool LinkGlobals(Module
*Dest
, const Module
*Src
,
527 std::map
<const Value
*, Value
*> &ValueMap
,
528 std::multimap
<std::string
, GlobalVariable
*> &AppendingVars
,
530 ValueSymbolTable
&DestSymTab
= Dest
->getValueSymbolTable();
532 // Loop over all of the globals in the src module, mapping them over as we go
533 for (Module::const_global_iterator I
= Src
->global_begin(),
534 E
= Src
->global_end(); I
!= E
; ++I
) {
535 const GlobalVariable
*SGV
= I
;
536 GlobalValue
*DGV
= 0;
538 // Check to see if may have to link the global with the global, alias or
540 if (SGV
->hasName() && !SGV
->hasLocalLinkage())
541 DGV
= cast_or_null
<GlobalValue
>(DestSymTab
.lookup(SGV
->getNameStart(),
544 // If we found a global with the same name in the dest module, but it has
545 // internal linkage, we are really not doing any linkage here.
546 if (DGV
&& DGV
->hasLocalLinkage())
549 // If types don't agree due to opaque types, try to resolve them.
550 if (DGV
&& DGV
->getType() != SGV
->getType())
551 RecursiveResolveTypes(SGV
->getType(), DGV
->getType());
553 assert((SGV
->hasInitializer() || SGV
->hasExternalWeakLinkage() ||
554 SGV
->hasExternalLinkage() || SGV
->hasDLLImportLinkage()) &&
555 "Global must either be external or have an initializer!");
557 GlobalValue::LinkageTypes NewLinkage
= GlobalValue::InternalLinkage
;
558 bool LinkFromSrc
= false;
559 if (GetLinkageResult(DGV
, SGV
, NewLinkage
, LinkFromSrc
, Err
))
563 // No linking to be performed, simply create an identical version of the
564 // symbol over in the dest module... the initializer will be filled in
565 // later by LinkGlobalInits.
566 GlobalVariable
*NewDGV
=
567 new GlobalVariable(SGV
->getType()->getElementType(),
568 SGV
->isConstant(), SGV
->getLinkage(), /*init*/0,
569 SGV
->getName(), Dest
, false,
570 SGV
->getType()->getAddressSpace());
571 // Propagate alignment, visibility and section info.
572 CopyGVAttributes(NewDGV
, SGV
);
574 // If the LLVM runtime renamed the global, but it is an externally visible
575 // symbol, DGV must be an existing global with internal linkage. Rename
577 if (!NewDGV
->hasLocalLinkage() && NewDGV
->getName() != SGV
->getName())
578 ForceRenaming(NewDGV
, SGV
->getName());
580 // Make sure to remember this mapping.
581 ValueMap
[SGV
] = NewDGV
;
583 // Keep track that this is an appending variable.
584 if (SGV
->hasAppendingLinkage())
585 AppendingVars
.insert(std::make_pair(SGV
->getName(), NewDGV
));
589 // If the visibilities of the symbols disagree and the destination is a
590 // prototype, take the visibility of its input.
591 if (DGV
->isDeclaration())
592 DGV
->setVisibility(SGV
->getVisibility());
594 if (DGV
->hasAppendingLinkage()) {
595 // No linking is performed yet. Just insert a new copy of the global, and
596 // keep track of the fact that it is an appending variable in the
597 // AppendingVars map. The name is cleared out so that no linkage is
599 GlobalVariable
*NewDGV
=
600 new GlobalVariable(SGV
->getType()->getElementType(),
601 SGV
->isConstant(), SGV
->getLinkage(), /*init*/0,
603 SGV
->getType()->getAddressSpace());
605 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
606 NewDGV
->setAlignment(DGV
->getAlignment());
607 // Propagate alignment, section and visibility info.
608 CopyGVAttributes(NewDGV
, SGV
);
610 // Make sure to remember this mapping...
611 ValueMap
[SGV
] = NewDGV
;
613 // Keep track that this is an appending variable...
614 AppendingVars
.insert(std::make_pair(SGV
->getName(), NewDGV
));
619 if (isa
<GlobalAlias
>(DGV
))
620 return Error(Err
, "Global-Alias Collision on '" + SGV
->getName() +
621 "': symbol multiple defined");
623 // If the types don't match, and if we are to link from the source, nuke
624 // DGV and create a new one of the appropriate type. Note that the thing
625 // we are replacing may be a function (if a prototype, weak, etc) or a
627 GlobalVariable
*NewDGV
=
628 new GlobalVariable(SGV
->getType()->getElementType(), SGV
->isConstant(),
629 NewLinkage
, /*init*/0, DGV
->getName(), Dest
, false,
630 SGV
->getType()->getAddressSpace());
632 // Propagate alignment, section, and visibility info.
633 CopyGVAttributes(NewDGV
, SGV
);
634 DGV
->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV
, DGV
->getType()));
636 // DGV will conflict with NewDGV because they both had the same
637 // name. We must erase this now so ForceRenaming doesn't assert
638 // because DGV might not have internal linkage.
639 if (GlobalVariable
*Var
= dyn_cast
<GlobalVariable
>(DGV
))
640 Var
->eraseFromParent();
642 cast
<Function
>(DGV
)->eraseFromParent();
645 // If the symbol table renamed the global, but it is an externally visible
646 // symbol, DGV must be an existing global with internal linkage. Rename.
647 if (NewDGV
->getName() != SGV
->getName() && !NewDGV
->hasLocalLinkage())
648 ForceRenaming(NewDGV
, SGV
->getName());
650 // Inherit const as appropriate.
651 NewDGV
->setConstant(SGV
->isConstant());
653 // Make sure to remember this mapping.
654 ValueMap
[SGV
] = NewDGV
;
658 // Not "link from source", keep the one in the DestModule and remap the
661 // Special case for const propagation.
662 if (GlobalVariable
*DGVar
= dyn_cast
<GlobalVariable
>(DGV
))
663 if (DGVar
->isDeclaration() && SGV
->isConstant() && !DGVar
->isConstant())
664 DGVar
->setConstant(true);
666 // SGV is global, but DGV is alias.
667 if (isa
<GlobalAlias
>(DGV
)) {
668 // The only valid mappings are:
669 // - SGV is external declaration, which is effectively a no-op.
670 // - SGV is weak, when we just need to throw SGV out.
671 if (!SGV
->isDeclaration() && !SGV
->isWeakForLinker())
672 return Error(Err
, "Global-Alias Collision on '" + SGV
->getName() +
673 "': symbol multiple defined");
676 // Set calculated linkage
677 DGV
->setLinkage(NewLinkage
);
679 // Make sure to remember this mapping...
680 ValueMap
[SGV
] = ConstantExpr::getBitCast(DGV
, SGV
->getType());
685 static GlobalValue::LinkageTypes
686 CalculateAliasLinkage(const GlobalValue
*SGV
, const GlobalValue
*DGV
) {
687 GlobalValue::LinkageTypes SL
= SGV
->getLinkage();
688 GlobalValue::LinkageTypes DL
= DGV
->getLinkage();
689 if (SL
== GlobalValue::ExternalLinkage
|| DL
== GlobalValue::ExternalLinkage
)
690 return GlobalValue::ExternalLinkage
;
691 else if (SL
== GlobalValue::WeakAnyLinkage
||
692 DL
== GlobalValue::WeakAnyLinkage
)
693 return GlobalValue::WeakAnyLinkage
;
694 else if (SL
== GlobalValue::WeakODRLinkage
||
695 DL
== GlobalValue::WeakODRLinkage
)
696 return GlobalValue::WeakODRLinkage
;
697 else if (SL
== GlobalValue::InternalLinkage
&&
698 DL
== GlobalValue::InternalLinkage
)
699 return GlobalValue::InternalLinkage
;
701 assert (SL
== GlobalValue::PrivateLinkage
&&
702 DL
== GlobalValue::PrivateLinkage
&& "Unexpected linkage type");
703 return GlobalValue::PrivateLinkage
;
707 // LinkAlias - Loop through the alias in the src module and link them into the
708 // dest module. We're assuming, that all functions/global variables were already
710 static bool LinkAlias(Module
*Dest
, const Module
*Src
,
711 std::map
<const Value
*, Value
*> &ValueMap
,
713 // Loop over all alias in the src module
714 for (Module::const_alias_iterator I
= Src
->alias_begin(),
715 E
= Src
->alias_end(); I
!= E
; ++I
) {
716 const GlobalAlias
*SGA
= I
;
717 const GlobalValue
*SAliasee
= SGA
->getAliasedGlobal();
718 GlobalAlias
*NewGA
= NULL
;
720 // Globals were already linked, thus we can just query ValueMap for variant
721 // of SAliasee in Dest.
722 std::map
<const Value
*,Value
*>::const_iterator VMI
= ValueMap
.find(SAliasee
);
723 assert(VMI
!= ValueMap
.end() && "Aliasee not linked");
724 GlobalValue
* DAliasee
= cast
<GlobalValue
>(VMI
->second
);
725 GlobalValue
* DGV
= NULL
;
727 // Try to find something 'similar' to SGA in destination module.
728 if (!DGV
&& !SGA
->hasLocalLinkage()) {
729 DGV
= Dest
->getNamedAlias(SGA
->getName());
731 // If types don't agree due to opaque types, try to resolve them.
732 if (DGV
&& DGV
->getType() != SGA
->getType())
733 RecursiveResolveTypes(SGA
->getType(), DGV
->getType());
736 if (!DGV
&& !SGA
->hasLocalLinkage()) {
737 DGV
= Dest
->getGlobalVariable(SGA
->getName());
739 // If types don't agree due to opaque types, try to resolve them.
740 if (DGV
&& DGV
->getType() != SGA
->getType())
741 RecursiveResolveTypes(SGA
->getType(), DGV
->getType());
744 if (!DGV
&& !SGA
->hasLocalLinkage()) {
745 DGV
= Dest
->getFunction(SGA
->getName());
747 // If types don't agree due to opaque types, try to resolve them.
748 if (DGV
&& DGV
->getType() != SGA
->getType())
749 RecursiveResolveTypes(SGA
->getType(), DGV
->getType());
752 // No linking to be performed on internal stuff.
753 if (DGV
&& DGV
->hasLocalLinkage())
756 if (GlobalAlias
*DGA
= dyn_cast_or_null
<GlobalAlias
>(DGV
)) {
757 // Types are known to be the same, check whether aliasees equal. As
758 // globals are already linked we just need query ValueMap to find the
760 if (DAliasee
== DGA
->getAliasedGlobal()) {
761 // This is just two copies of the same alias. Propagate linkage, if
763 DGA
->setLinkage(CalculateAliasLinkage(SGA
, DGA
));
766 // Proceed to 'common' steps
768 return Error(Err
, "Alias Collision on '" + SGA
->getName()+
769 "': aliases have different aliasees");
770 } else if (GlobalVariable
*DGVar
= dyn_cast_or_null
<GlobalVariable
>(DGV
)) {
771 // The only allowed way is to link alias with external declaration or weak
773 if (DGVar
->isDeclaration() || DGVar
->isWeakForLinker()) {
774 // But only if aliasee is global too...
775 if (!isa
<GlobalVariable
>(DAliasee
))
776 return Error(Err
, "Global-Alias Collision on '" + SGA
->getName() +
777 "': aliasee is not global variable");
779 NewGA
= new GlobalAlias(SGA
->getType(), SGA
->getLinkage(),
780 SGA
->getName(), DAliasee
, Dest
);
781 CopyGVAttributes(NewGA
, SGA
);
783 // Any uses of DGV need to change to NewGA, with cast, if needed.
784 if (SGA
->getType() != DGVar
->getType())
785 DGVar
->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA
,
788 DGVar
->replaceAllUsesWith(NewGA
);
790 // DGVar will conflict with NewGA because they both had the same
791 // name. We must erase this now so ForceRenaming doesn't assert
792 // because DGV might not have internal linkage.
793 DGVar
->eraseFromParent();
795 // Proceed to 'common' steps
797 return Error(Err
, "Global-Alias Collision on '" + SGA
->getName() +
798 "': symbol multiple defined");
799 } else if (Function
*DF
= dyn_cast_or_null
<Function
>(DGV
)) {
800 // The only allowed way is to link alias with external declaration or weak
802 if (DF
->isDeclaration() || DF
->isWeakForLinker()) {
803 // But only if aliasee is function too...
804 if (!isa
<Function
>(DAliasee
))
805 return Error(Err
, "Function-Alias Collision on '" + SGA
->getName() +
806 "': aliasee is not function");
808 NewGA
= new GlobalAlias(SGA
->getType(), SGA
->getLinkage(),
809 SGA
->getName(), DAliasee
, Dest
);
810 CopyGVAttributes(NewGA
, SGA
);
812 // Any uses of DF need to change to NewGA, with cast, if needed.
813 if (SGA
->getType() != DF
->getType())
814 DF
->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA
,
817 DF
->replaceAllUsesWith(NewGA
);
819 // DF will conflict with NewGA because they both had the same
820 // name. We must erase this now so ForceRenaming doesn't assert
821 // because DF might not have internal linkage.
822 DF
->eraseFromParent();
824 // Proceed to 'common' steps
826 return Error(Err
, "Function-Alias Collision on '" + SGA
->getName() +
827 "': symbol multiple defined");
829 // No linking to be performed, simply create an identical version of the
830 // alias over in the dest module...
832 NewGA
= new GlobalAlias(SGA
->getType(), SGA
->getLinkage(),
833 SGA
->getName(), DAliasee
, Dest
);
834 CopyGVAttributes(NewGA
, SGA
);
836 // Proceed to 'common' steps
839 assert(NewGA
&& "No alias was created in destination module!");
841 // If the symbol table renamed the alias, but it is an externally visible
842 // symbol, DGA must be an global value with internal linkage. Rename it.
843 if (NewGA
->getName() != SGA
->getName() &&
844 !NewGA
->hasLocalLinkage())
845 ForceRenaming(NewGA
, SGA
->getName());
847 // Remember this mapping so uses in the source module get remapped
848 // later by RemapOperand.
849 ValueMap
[SGA
] = NewGA
;
856 // LinkGlobalInits - Update the initializers in the Dest module now that all
857 // globals that may be referenced are in Dest.
858 static bool LinkGlobalInits(Module
*Dest
, const Module
*Src
,
859 std::map
<const Value
*, Value
*> &ValueMap
,
861 // Loop over all of the globals in the src module, mapping them over as we go
862 for (Module::const_global_iterator I
= Src
->global_begin(),
863 E
= Src
->global_end(); I
!= E
; ++I
) {
864 const GlobalVariable
*SGV
= I
;
866 if (SGV
->hasInitializer()) { // Only process initialized GV's
867 // Figure out what the initializer looks like in the dest module...
869 cast
<Constant
>(RemapOperand(SGV
->getInitializer(), ValueMap
));
870 // Grab destination global variable or alias.
871 GlobalValue
*DGV
= cast
<GlobalValue
>(ValueMap
[SGV
]->stripPointerCasts());
873 // If dest if global variable, check that initializers match.
874 if (GlobalVariable
*DGVar
= dyn_cast
<GlobalVariable
>(DGV
)) {
875 if (DGVar
->hasInitializer()) {
876 if (SGV
->hasExternalLinkage()) {
877 if (DGVar
->getInitializer() != SInit
)
878 return Error(Err
, "Global Variable Collision on '" +
880 "': global variables have different initializers");
881 } else if (DGVar
->isWeakForLinker()) {
882 // Nothing is required, mapped values will take the new global
884 } else if (SGV
->isWeakForLinker()) {
885 // Nothing is required, mapped values will take the new global
887 } else if (DGVar
->hasAppendingLinkage()) {
888 assert(0 && "Appending linkage unimplemented!");
890 assert(0 && "Unknown linkage!");
893 // Copy the initializer over now...
894 DGVar
->setInitializer(SInit
);
897 // Destination is alias, the only valid situation is when source is
898 // weak. Also, note, that we already checked linkage in LinkGlobals(),
899 // thus we assert here.
900 // FIXME: Should we weaken this assumption, 'dereference' alias and
901 // check for initializer of aliasee?
902 assert(SGV
->isWeakForLinker());
909 // LinkFunctionProtos - Link the functions together between the two modules,
910 // without doing function bodies... this just adds external function prototypes
911 // to the Dest function...
913 static bool LinkFunctionProtos(Module
*Dest
, const Module
*Src
,
914 std::map
<const Value
*, Value
*> &ValueMap
,
916 ValueSymbolTable
&DestSymTab
= Dest
->getValueSymbolTable();
918 // Loop over all of the functions in the src module, mapping them over
919 for (Module::const_iterator I
= Src
->begin(), E
= Src
->end(); I
!= E
; ++I
) {
920 const Function
*SF
= I
; // SrcFunction
921 GlobalValue
*DGV
= 0;
923 // Check to see if may have to link the function with the global, alias or
925 if (SF
->hasName() && !SF
->hasLocalLinkage())
926 DGV
= cast_or_null
<GlobalValue
>(DestSymTab
.lookup(SF
->getNameStart(),
929 // If we found a global with the same name in the dest module, but it has
930 // internal linkage, we are really not doing any linkage here.
931 if (DGV
&& DGV
->hasLocalLinkage())
934 // If types don't agree due to opaque types, try to resolve them.
935 if (DGV
&& DGV
->getType() != SF
->getType())
936 RecursiveResolveTypes(SF
->getType(), DGV
->getType());
938 GlobalValue::LinkageTypes NewLinkage
= GlobalValue::InternalLinkage
;
939 bool LinkFromSrc
= false;
940 if (GetLinkageResult(DGV
, SF
, NewLinkage
, LinkFromSrc
, Err
))
943 // If there is no linkage to be performed, just bring over SF without
946 // Function does not already exist, simply insert an function signature
947 // identical to SF into the dest module.
948 Function
*NewDF
= Function::Create(SF
->getFunctionType(),
950 SF
->getName(), Dest
);
951 CopyGVAttributes(NewDF
, SF
);
953 // If the LLVM runtime renamed the function, but it is an externally
954 // visible symbol, DF must be an existing function with internal linkage.
956 if (!NewDF
->hasLocalLinkage() && NewDF
->getName() != SF
->getName())
957 ForceRenaming(NewDF
, SF
->getName());
959 // ... and remember this mapping...
960 ValueMap
[SF
] = NewDF
;
964 // If the visibilities of the symbols disagree and the destination is a
965 // prototype, take the visibility of its input.
966 if (DGV
->isDeclaration())
967 DGV
->setVisibility(SF
->getVisibility());
970 if (isa
<GlobalAlias
>(DGV
))
971 return Error(Err
, "Function-Alias Collision on '" + SF
->getName() +
972 "': symbol multiple defined");
974 // We have a definition of the same name but different type in the
975 // source module. Copy the prototype to the destination and replace
976 // uses of the destination's prototype with the new prototype.
977 Function
*NewDF
= Function::Create(SF
->getFunctionType(), NewLinkage
,
978 SF
->getName(), Dest
);
979 CopyGVAttributes(NewDF
, SF
);
981 // Any uses of DF need to change to NewDF, with cast
982 DGV
->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF
, DGV
->getType()));
984 // DF will conflict with NewDF because they both had the same. We must
985 // erase this now so ForceRenaming doesn't assert because DF might
986 // not have internal linkage.
987 if (GlobalVariable
*Var
= dyn_cast
<GlobalVariable
>(DGV
))
988 Var
->eraseFromParent();
990 cast
<Function
>(DGV
)->eraseFromParent();
992 // If the symbol table renamed the function, but it is an externally
993 // visible symbol, DF must be an existing function with internal
994 // linkage. Rename it.
995 if (NewDF
->getName() != SF
->getName() && !NewDF
->hasLocalLinkage())
996 ForceRenaming(NewDF
, SF
->getName());
998 // Remember this mapping so uses in the source module get remapped
999 // later by RemapOperand.
1000 ValueMap
[SF
] = NewDF
;
1004 // Not "link from source", keep the one in the DestModule and remap the
1007 if (isa
<GlobalAlias
>(DGV
)) {
1008 // The only valid mappings are:
1009 // - SF is external declaration, which is effectively a no-op.
1010 // - SF is weak, when we just need to throw SF out.
1011 if (!SF
->isDeclaration() && !SF
->isWeakForLinker())
1012 return Error(Err
, "Function-Alias Collision on '" + SF
->getName() +
1013 "': symbol multiple defined");
1016 // Set calculated linkage
1017 DGV
->setLinkage(NewLinkage
);
1019 // Make sure to remember this mapping.
1020 ValueMap
[SF
] = ConstantExpr::getBitCast(DGV
, SF
->getType());
1025 // LinkFunctionBody - Copy the source function over into the dest function and
1026 // fix up references to values. At this point we know that Dest is an external
1027 // function, and that Src is not.
1028 static bool LinkFunctionBody(Function
*Dest
, Function
*Src
,
1029 std::map
<const Value
*, Value
*> &ValueMap
,
1031 assert(Src
&& Dest
&& Dest
->isDeclaration() && !Src
->isDeclaration());
1033 // Go through and convert function arguments over, remembering the mapping.
1034 Function::arg_iterator DI
= Dest
->arg_begin();
1035 for (Function::arg_iterator I
= Src
->arg_begin(), E
= Src
->arg_end();
1036 I
!= E
; ++I
, ++DI
) {
1037 DI
->setName(I
->getName()); // Copy the name information over...
1039 // Add a mapping to our local map
1043 // Splice the body of the source function into the dest function.
1044 Dest
->getBasicBlockList().splice(Dest
->end(), Src
->getBasicBlockList());
1046 // At this point, all of the instructions and values of the function are now
1047 // copied over. The only problem is that they are still referencing values in
1048 // the Source function as operands. Loop through all of the operands of the
1049 // functions and patch them up to point to the local versions...
1051 for (Function::iterator BB
= Dest
->begin(), BE
= Dest
->end(); BB
!= BE
; ++BB
)
1052 for (BasicBlock::iterator I
= BB
->begin(), E
= BB
->end(); I
!= E
; ++I
)
1053 for (Instruction::op_iterator OI
= I
->op_begin(), OE
= I
->op_end();
1055 if (!isa
<Instruction
>(*OI
) && !isa
<BasicBlock
>(*OI
))
1056 *OI
= RemapOperand(*OI
, ValueMap
);
1058 // There is no need to map the arguments anymore.
1059 for (Function::arg_iterator I
= Src
->arg_begin(), E
= Src
->arg_end();
1067 // LinkFunctionBodies - Link in the function bodies that are defined in the
1068 // source module into the DestModule. This consists basically of copying the
1069 // function over and fixing up references to values.
1070 static bool LinkFunctionBodies(Module
*Dest
, Module
*Src
,
1071 std::map
<const Value
*, Value
*> &ValueMap
,
1074 // Loop over all of the functions in the src module, mapping them over as we
1076 for (Module::iterator SF
= Src
->begin(), E
= Src
->end(); SF
!= E
; ++SF
) {
1077 if (!SF
->isDeclaration()) { // No body if function is external
1078 Function
*DF
= dyn_cast
<Function
>(ValueMap
[SF
]); // Destination function
1080 // DF not external SF external?
1081 if (DF
&& DF
->isDeclaration())
1082 // Only provide the function body if there isn't one already.
1083 if (LinkFunctionBody(DF
, SF
, ValueMap
, Err
))
1090 // LinkAppendingVars - If there were any appending global variables, link them
1091 // together now. Return true on error.
1092 static bool LinkAppendingVars(Module
*M
,
1093 std::multimap
<std::string
, GlobalVariable
*> &AppendingVars
,
1094 std::string
*ErrorMsg
) {
1095 if (AppendingVars
.empty()) return false; // Nothing to do.
1097 // Loop over the multimap of appending vars, processing any variables with the
1098 // same name, forming a new appending global variable with both of the
1099 // initializers merged together, then rewrite references to the old variables
1101 std::vector
<Constant
*> Inits
;
1102 while (AppendingVars
.size() > 1) {
1103 // Get the first two elements in the map...
1104 std::multimap
<std::string
,
1105 GlobalVariable
*>::iterator Second
= AppendingVars
.begin(), First
=Second
++;
1107 // If the first two elements are for different names, there is no pair...
1108 // Otherwise there is a pair, so link them together...
1109 if (First
->first
== Second
->first
) {
1110 GlobalVariable
*G1
= First
->second
, *G2
= Second
->second
;
1111 const ArrayType
*T1
= cast
<ArrayType
>(G1
->getType()->getElementType());
1112 const ArrayType
*T2
= cast
<ArrayType
>(G2
->getType()->getElementType());
1114 // Check to see that they two arrays agree on type...
1115 if (T1
->getElementType() != T2
->getElementType())
1116 return Error(ErrorMsg
,
1117 "Appending variables with different element types need to be linked!");
1118 if (G1
->isConstant() != G2
->isConstant())
1119 return Error(ErrorMsg
,
1120 "Appending variables linked with different const'ness!");
1122 if (G1
->getAlignment() != G2
->getAlignment())
1123 return Error(ErrorMsg
,
1124 "Appending variables with different alignment need to be linked!");
1126 if (G1
->getVisibility() != G2
->getVisibility())
1127 return Error(ErrorMsg
,
1128 "Appending variables with different visibility need to be linked!");
1130 if (G1
->getSection() != G2
->getSection())
1131 return Error(ErrorMsg
,
1132 "Appending variables with different section name need to be linked!");
1134 unsigned NewSize
= T1
->getNumElements() + T2
->getNumElements();
1135 ArrayType
*NewType
= ArrayType::get(T1
->getElementType(), NewSize
);
1137 G1
->setName(""); // Clear G1's name in case of a conflict!
1139 // Create the new global variable...
1140 GlobalVariable
*NG
=
1141 new GlobalVariable(NewType
, G1
->isConstant(), G1
->getLinkage(),
1142 /*init*/0, First
->first
, M
, G1
->isThreadLocal(),
1143 G1
->getType()->getAddressSpace());
1145 // Propagate alignment, visibility and section info.
1146 CopyGVAttributes(NG
, G1
);
1148 // Merge the initializer...
1149 Inits
.reserve(NewSize
);
1150 if (ConstantArray
*I
= dyn_cast
<ConstantArray
>(G1
->getInitializer())) {
1151 for (unsigned i
= 0, e
= T1
->getNumElements(); i
!= e
; ++i
)
1152 Inits
.push_back(I
->getOperand(i
));
1154 assert(isa
<ConstantAggregateZero
>(G1
->getInitializer()));
1155 Constant
*CV
= Constant::getNullValue(T1
->getElementType());
1156 for (unsigned i
= 0, e
= T1
->getNumElements(); i
!= e
; ++i
)
1157 Inits
.push_back(CV
);
1159 if (ConstantArray
*I
= dyn_cast
<ConstantArray
>(G2
->getInitializer())) {
1160 for (unsigned i
= 0, e
= T2
->getNumElements(); i
!= e
; ++i
)
1161 Inits
.push_back(I
->getOperand(i
));
1163 assert(isa
<ConstantAggregateZero
>(G2
->getInitializer()));
1164 Constant
*CV
= Constant::getNullValue(T2
->getElementType());
1165 for (unsigned i
= 0, e
= T2
->getNumElements(); i
!= e
; ++i
)
1166 Inits
.push_back(CV
);
1168 NG
->setInitializer(ConstantArray::get(NewType
, Inits
));
1171 // Replace any uses of the two global variables with uses of the new
1174 // FIXME: This should rewrite simple/straight-forward uses such as
1175 // getelementptr instructions to not use the Cast!
1176 G1
->replaceAllUsesWith(ConstantExpr::getBitCast(NG
, G1
->getType()));
1177 G2
->replaceAllUsesWith(ConstantExpr::getBitCast(NG
, G2
->getType()));
1179 // Remove the two globals from the module now...
1180 M
->getGlobalList().erase(G1
);
1181 M
->getGlobalList().erase(G2
);
1183 // Put the new global into the AppendingVars map so that we can handle
1184 // linking of more than two vars...
1185 Second
->second
= NG
;
1187 AppendingVars
.erase(First
);
1193 static bool ResolveAliases(Module
*Dest
) {
1194 for (Module::alias_iterator I
= Dest
->alias_begin(), E
= Dest
->alias_end();
1196 if (const GlobalValue
*GV
= I
->resolveAliasedGlobal())
1197 if (GV
!= I
&& !GV
->isDeclaration())
1198 I
->replaceAllUsesWith(const_cast<GlobalValue
*>(GV
));
1203 // LinkModules - This function links two modules together, with the resulting
1204 // left module modified to be the composite of the two input modules. If an
1205 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1206 // the problem. Upon failure, the Dest module could be in a modified state, and
1207 // shouldn't be relied on to be consistent.
1209 Linker::LinkModules(Module
*Dest
, Module
*Src
, std::string
*ErrorMsg
) {
1210 assert(Dest
!= 0 && "Invalid Destination module");
1211 assert(Src
!= 0 && "Invalid Source Module");
1213 if (Dest
->getDataLayout().empty()) {
1214 if (!Src
->getDataLayout().empty()) {
1215 Dest
->setDataLayout(Src
->getDataLayout());
1217 std::string DataLayout
;
1219 if (Dest
->getEndianness() == Module::AnyEndianness
) {
1220 if (Src
->getEndianness() == Module::BigEndian
)
1221 DataLayout
.append("E");
1222 else if (Src
->getEndianness() == Module::LittleEndian
)
1223 DataLayout
.append("e");
1226 if (Dest
->getPointerSize() == Module::AnyPointerSize
) {
1227 if (Src
->getPointerSize() == Module::Pointer64
)
1228 DataLayout
.append(DataLayout
.length() == 0 ? "p:64:64" : "-p:64:64");
1229 else if (Src
->getPointerSize() == Module::Pointer32
)
1230 DataLayout
.append(DataLayout
.length() == 0 ? "p:32:32" : "-p:32:32");
1232 Dest
->setDataLayout(DataLayout
);
1236 // Copy the target triple from the source to dest if the dest's is empty.
1237 if (Dest
->getTargetTriple().empty() && !Src
->getTargetTriple().empty())
1238 Dest
->setTargetTriple(Src
->getTargetTriple());
1240 if (!Src
->getDataLayout().empty() && !Dest
->getDataLayout().empty() &&
1241 Src
->getDataLayout() != Dest
->getDataLayout())
1242 cerr
<< "WARNING: Linking two modules of different data layouts!\n";
1243 if (!Src
->getTargetTriple().empty() &&
1244 Dest
->getTargetTriple() != Src
->getTargetTriple())
1245 cerr
<< "WARNING: Linking two modules of different target triples!\n";
1247 // Append the module inline asm string.
1248 if (!Src
->getModuleInlineAsm().empty()) {
1249 if (Dest
->getModuleInlineAsm().empty())
1250 Dest
->setModuleInlineAsm(Src
->getModuleInlineAsm());
1252 Dest
->setModuleInlineAsm(Dest
->getModuleInlineAsm()+"\n"+
1253 Src
->getModuleInlineAsm());
1256 // Update the destination module's dependent libraries list with the libraries
1257 // from the source module. There's no opportunity for duplicates here as the
1258 // Module ensures that duplicate insertions are discarded.
1259 for (Module::lib_iterator SI
= Src
->lib_begin(), SE
= Src
->lib_end();
1261 Dest
->addLibrary(*SI
);
1263 // LinkTypes - Go through the symbol table of the Src module and see if any
1264 // types are named in the src module that are not named in the Dst module.
1265 // Make sure there are no type name conflicts.
1266 if (LinkTypes(Dest
, Src
, ErrorMsg
))
1269 // ValueMap - Mapping of values from what they used to be in Src, to what they
1271 std::map
<const Value
*, Value
*> ValueMap
;
1273 // AppendingVars - Keep track of global variables in the destination module
1274 // with appending linkage. After the module is linked together, they are
1275 // appended and the module is rewritten.
1276 std::multimap
<std::string
, GlobalVariable
*> AppendingVars
;
1277 for (Module::global_iterator I
= Dest
->global_begin(), E
= Dest
->global_end();
1279 // Add all of the appending globals already in the Dest module to
1281 if (I
->hasAppendingLinkage())
1282 AppendingVars
.insert(std::make_pair(I
->getName(), I
));
1285 // Insert all of the globals in src into the Dest module... without linking
1286 // initializers (which could refer to functions not yet mapped over).
1287 if (LinkGlobals(Dest
, Src
, ValueMap
, AppendingVars
, ErrorMsg
))
1290 // Link the functions together between the two modules, without doing function
1291 // bodies... this just adds external function prototypes to the Dest
1292 // function... We do this so that when we begin processing function bodies,
1293 // all of the global values that may be referenced are available in our
1295 if (LinkFunctionProtos(Dest
, Src
, ValueMap
, ErrorMsg
))
1298 // If there were any alias, link them now. We really need to do this now,
1299 // because all of the aliases that may be referenced need to be available in
1301 if (LinkAlias(Dest
, Src
, ValueMap
, ErrorMsg
)) return true;
1303 // Update the initializers in the Dest module now that all globals that may
1304 // be referenced are in Dest.
1305 if (LinkGlobalInits(Dest
, Src
, ValueMap
, ErrorMsg
)) return true;
1307 // Link in the function bodies that are defined in the source module into the
1308 // DestModule. This consists basically of copying the function over and
1309 // fixing up references to values.
1310 if (LinkFunctionBodies(Dest
, Src
, ValueMap
, ErrorMsg
)) return true;
1312 // If there were any appending global variables, link them together now.
1313 if (LinkAppendingVars(Dest
, AppendingVars
, ErrorMsg
)) return true;
1315 // Resolve all uses of aliases with aliasees
1316 if (ResolveAliases(Dest
)) return true;
1318 // If the source library's module id is in the dependent library list of the
1319 // destination library, remove it since that module is now linked in.
1321 modId
.set(Src
->getModuleIdentifier());
1322 if (!modId
.isEmpty())
1323 Dest
->removeLibrary(modId
.getBasename());