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/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Transforms/Utils/ValueMapper.h"
33 #include "llvm/ADT/DenseMap.h"
36 // Error - Simple wrapper function to conditionally assign to E and return true.
37 // This just makes error return conditions a little bit simpler...
38 static inline bool Error(std::string *E, const Twine &Message) {
39 if (E) *E = Message.str();
43 // Function: ResolveTypes()
46 // Attempt to link the two specified types together.
49 // DestTy - The type to which we wish to resolve.
50 // SrcTy - The original type which we want to resolve.
53 // DestST - The symbol table in which the new type should be placed.
56 // true - There is an error and the types cannot yet be linked.
59 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
60 if (DestTy == SrcTy) return false; // If already equal, noop
61 assert(DestTy && SrcTy && "Can't handle null types");
63 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
64 // Type _is_ in module, just opaque...
65 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
66 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
67 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
69 return true; // Cannot link types... not-equal and neither is opaque.
74 /// LinkerTypeMap - This implements a map of types that is stable
75 /// even if types are resolved/refined to other types. This is not a general
76 /// purpose map, it is specific to the linker's use.
78 class LinkerTypeMap : public AbstractTypeUser {
79 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
82 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
83 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
87 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
88 E = TheMap.end(); I != E; ++I)
89 I->first->removeAbstractTypeUser(this);
92 /// lookup - Return the value for the specified type or null if it doesn't
94 const Type *lookup(const Type *Ty) const {
95 TheMapTy::const_iterator I = TheMap.find(Ty);
96 if (I != TheMap.end()) return I->second;
100 /// insert - This returns true if the pointer was new to the set, false if it
101 /// was already in the set.
102 bool insert(const Type *Src, const Type *Dst) {
103 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
104 return false; // Already in map.
105 if (Src->isAbstract())
106 Src->addAbstractTypeUser(this);
111 /// refineAbstractType - The callback method invoked when an abstract type is
112 /// resolved to another type. An object must override this method to update
113 /// its internal state to reference NewType instead of OldType.
115 virtual void refineAbstractType(const DerivedType *OldTy,
117 TheMapTy::iterator I = TheMap.find(OldTy);
118 const Type *DstTy = I->second;
121 if (OldTy->isAbstract())
122 OldTy->removeAbstractTypeUser(this);
124 // Don't reinsert into the map if the key is concrete now.
125 if (NewTy->isAbstract())
126 insert(NewTy, DstTy);
129 /// The other case which AbstractTypeUsers must be aware of is when a type
130 /// makes the transition from being abstract (where it has clients on it's
131 /// AbstractTypeUsers list) to concrete (where it does not). This method
132 /// notifies ATU's when this occurs for a type.
133 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
135 AbsTy->removeAbstractTypeUser(this);
139 virtual void dump() const {
140 dbgs() << "AbstractTypeSet!\n";
146 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
147 // recurses down into derived types, merging the used types if the parent types
149 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
150 LinkerTypeMap &Pointers) {
151 if (DstTy == SrcTy) return false; // If already equal, noop
153 // If we found our opaque type, resolve it now!
154 if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy())
155 return ResolveTypes(DstTy, SrcTy);
157 // Two types cannot be resolved together if they are of different primitive
158 // type. For example, we cannot resolve an int to a float.
159 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
161 // If neither type is abstract, then they really are just different types.
162 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
165 // Otherwise, resolve the used type used by this derived type...
166 switch (DstTy->getTypeID()) {
169 case Type::FunctionTyID: {
170 const FunctionType *DstFT = cast<FunctionType>(DstTy);
171 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
172 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
173 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
176 // Use TypeHolder's so recursive resolution won't break us.
177 PATypeHolder ST(SrcFT), DT(DstFT);
178 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
179 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
180 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
185 case Type::StructTyID: {
186 const StructType *DstST = cast<StructType>(DstTy);
187 const StructType *SrcST = cast<StructType>(SrcTy);
188 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
191 PATypeHolder ST(SrcST), DT(DstST);
192 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
193 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
194 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
199 case Type::ArrayTyID: {
200 const ArrayType *DAT = cast<ArrayType>(DstTy);
201 const ArrayType *SAT = cast<ArrayType>(SrcTy);
202 if (DAT->getNumElements() != SAT->getNumElements()) return true;
203 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
206 case Type::VectorTyID: {
207 const VectorType *DVT = cast<VectorType>(DstTy);
208 const VectorType *SVT = cast<VectorType>(SrcTy);
209 if (DVT->getNumElements() != SVT->getNumElements()) return true;
210 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
213 case Type::PointerTyID: {
214 const PointerType *DstPT = cast<PointerType>(DstTy);
215 const PointerType *SrcPT = cast<PointerType>(SrcTy);
217 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
220 // If this is a pointer type, check to see if we have already seen it. If
221 // so, we are in a recursive branch. Cut off the search now. We cannot use
222 // an associative container for this search, because the type pointers (keys
223 // in the container) change whenever types get resolved.
224 if (SrcPT->isAbstract())
225 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
226 return ExistingDestTy != DstPT;
228 if (DstPT->isAbstract())
229 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
230 return ExistingSrcTy != SrcPT;
231 // Otherwise, add the current pointers to the vector to stop recursion on
233 if (DstPT->isAbstract())
234 Pointers.insert(DstPT, SrcPT);
235 if (SrcPT->isAbstract())
236 Pointers.insert(SrcPT, DstPT);
238 return RecursiveResolveTypesI(DstPT->getElementType(),
239 SrcPT->getElementType(), Pointers);
244 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
245 LinkerTypeMap PointerTypes;
246 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
250 // LinkTypes - Go through the symbol table of the Src module and see if any
251 // types are named in the src module that are not named in the Dst module.
252 // Make sure there are no type name conflicts.
253 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
254 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
255 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
257 // Look for a type plane for Type's...
258 TypeSymbolTable::const_iterator TI = SrcST->begin();
259 TypeSymbolTable::const_iterator TE = SrcST->end();
260 if (TI == TE) return false; // No named types, do nothing.
262 // Some types cannot be resolved immediately because they depend on other
263 // types being resolved to each other first. This contains a list of types we
264 // are waiting to recheck.
265 std::vector<std::string> DelayedTypesToResolve;
267 for ( ; TI != TE; ++TI ) {
268 const std::string &Name = TI->first;
269 const Type *RHS = TI->second;
271 // Check to see if this type name is already in the dest module.
272 Type *Entry = DestST->lookup(Name);
274 // If the name is just in the source module, bring it over to the dest.
277 DestST->insert(Name, const_cast<Type*>(RHS));
278 } else if (ResolveTypes(Entry, RHS)) {
279 // They look different, save the types 'till later to resolve.
280 DelayedTypesToResolve.push_back(Name);
284 // Iteratively resolve types while we can...
285 while (!DelayedTypesToResolve.empty()) {
286 // Loop over all of the types, attempting to resolve them if possible...
287 unsigned OldSize = DelayedTypesToResolve.size();
289 // Try direct resolution by name...
290 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
291 const std::string &Name = DelayedTypesToResolve[i];
292 Type *T1 = SrcST->lookup(Name);
293 Type *T2 = DestST->lookup(Name);
294 if (!ResolveTypes(T2, T1)) {
295 // We are making progress!
296 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
301 // Did we not eliminate any types?
302 if (DelayedTypesToResolve.size() == OldSize) {
303 // Attempt to resolve subelements of types. This allows us to merge these
304 // two types: { int* } and { opaque* }
305 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
306 const std::string &Name = DelayedTypesToResolve[i];
307 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
308 // We are making progress!
309 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
311 // Go back to the main loop, perhaps we can resolve directly by name
317 // If we STILL cannot resolve the types, then there is something wrong.
318 if (DelayedTypesToResolve.size() == OldSize) {
319 // Remove the symbol name from the destination.
320 DelayedTypesToResolve.pop_back();
329 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
330 /// in the symbol table. This is good for all clients except for us. Go
331 /// through the trouble to force this back.
332 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
333 assert(GV->getName() != Name && "Can't force rename to self");
334 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
336 // If there is a conflict, rename the conflict.
337 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
338 assert(ConflictGV->hasLocalLinkage() &&
339 "Not conflicting with a static global, should link instead!");
340 GV->takeName(ConflictGV);
341 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
342 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
344 GV->setName(Name); // Force the name back
348 /// CopyGVAttributes - copy additional attributes (those not needed to construct
349 /// a GlobalValue) from the SrcGV to the DestGV.
350 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
351 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
352 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
353 DestGV->copyAttributesFrom(SrcGV);
354 DestGV->setAlignment(Alignment);
357 /// GetLinkageResult - This analyzes the two global values and determines what
358 /// the result will look like in the destination module. In particular, it
359 /// computes the resultant linkage type, computes whether the global in the
360 /// source should be copied over to the destination (replacing the existing
361 /// one), and computes whether this linkage is an error or not. It also performs
362 /// visibility checks: we cannot link together two symbols with different
364 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
365 GlobalValue::LinkageTypes <, bool &LinkFromSrc,
367 assert((!Dest || !Src->hasLocalLinkage()) &&
368 "If Src has internal linkage, Dest shouldn't be set!");
370 // Linking something to nothing.
372 LT = Src->getLinkage();
373 } else if (Src->isDeclaration()) {
374 // If Src is external or if both Src & Dest are external.. Just link the
375 // external globals, we aren't adding anything.
376 if (Src->hasDLLImportLinkage()) {
377 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
378 if (Dest->isDeclaration()) {
380 LT = Src->getLinkage();
382 } else if (Dest->hasExternalWeakLinkage()) {
383 // If the Dest is weak, use the source linkage.
385 LT = Src->getLinkage();
388 LT = Dest->getLinkage();
390 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
391 // If Dest is external but Src is not:
393 LT = Src->getLinkage();
394 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
395 if (Src->getLinkage() != Dest->getLinkage())
396 return Error(Err, "Linking globals named '" + Src->getName() +
397 "': can only link appending global with another appending global!");
398 LinkFromSrc = true; // Special cased.
399 LT = Src->getLinkage();
400 } else if (Src->isWeakForLinker()) {
401 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
403 if (Dest->hasExternalWeakLinkage() ||
404 Dest->hasAvailableExternallyLinkage() ||
405 (Dest->hasLinkOnceLinkage() &&
406 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
408 LT = Src->getLinkage();
411 LT = Dest->getLinkage();
413 } else if (Dest->isWeakForLinker()) {
414 // At this point we know that Src has External* or DLL* linkage.
415 if (Src->hasExternalWeakLinkage()) {
417 LT = Dest->getLinkage();
420 LT = GlobalValue::ExternalLinkage;
423 assert((Dest->hasExternalLinkage() ||
424 Dest->hasDLLImportLinkage() ||
425 Dest->hasDLLExportLinkage() ||
426 Dest->hasExternalWeakLinkage()) &&
427 (Src->hasExternalLinkage() ||
428 Src->hasDLLImportLinkage() ||
429 Src->hasDLLExportLinkage() ||
430 Src->hasExternalWeakLinkage()) &&
431 "Unexpected linkage type!");
432 return Error(Err, "Linking globals named '" + Src->getName() +
433 "': symbol multiply defined!");
437 if (Dest && Src->getVisibility() != Dest->getVisibility() &&
438 !Src->isDeclaration() && !Dest->isDeclaration() &&
439 !Src->hasAvailableExternallyLinkage() &&
440 !Dest->hasAvailableExternallyLinkage())
441 return Error(Err, "Linking globals named '" + Src->getName() +
442 "': symbols have different visibilities!");
446 // Insert all of the named mdnoes in Src into the Dest module.
447 static void LinkNamedMDNodes(Module *Dest, Module *Src,
448 ValueToValueMapTy &ValueMap) {
449 for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
450 E = Src->named_metadata_end(); I != E; ++I) {
451 const NamedMDNode *SrcNMD = I;
452 NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName());
453 // Add Src elements into Dest node.
454 for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
455 DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i),
460 // LinkGlobals - Loop through the global variables in the src module and merge
461 // them into the dest module.
462 static bool LinkGlobals(Module *Dest, const Module *Src,
463 ValueToValueMapTy &ValueMap,
464 std::multimap<std::string, GlobalVariable *> &AppendingVars,
466 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
468 // Loop over all of the globals in the src module, mapping them over as we go
469 for (Module::const_global_iterator I = Src->global_begin(),
470 E = Src->global_end(); I != E; ++I) {
471 const GlobalVariable *SGV = I;
472 GlobalValue *DGV = 0;
474 // Check to see if may have to link the global with the global, alias or
476 if (SGV->hasName() && !SGV->hasLocalLinkage())
477 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
479 // If we found a global with the same name in the dest module, but it has
480 // internal linkage, we are really not doing any linkage here.
481 if (DGV && DGV->hasLocalLinkage())
484 // If types don't agree due to opaque types, try to resolve them.
485 if (DGV && DGV->getType() != SGV->getType())
486 RecursiveResolveTypes(SGV->getType(), DGV->getType());
488 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
489 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
490 "Global must either be external or have an initializer!");
492 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
493 bool LinkFromSrc = false;
494 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
498 // No linking to be performed, simply create an identical version of the
499 // symbol over in the dest module... the initializer will be filled in
500 // later by LinkGlobalInits.
501 GlobalVariable *NewDGV =
502 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
503 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
504 SGV->getName(), 0, false,
505 SGV->getType()->getAddressSpace());
506 // Propagate alignment, visibility and section info.
507 CopyGVAttributes(NewDGV, SGV);
509 // If the LLVM runtime renamed the global, but it is an externally visible
510 // symbol, DGV must be an existing global with internal linkage. Rename
512 if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
513 ForceRenaming(NewDGV, SGV->getName());
515 // Make sure to remember this mapping.
516 ValueMap[SGV] = NewDGV;
518 // Keep track that this is an appending variable.
519 if (SGV->hasAppendingLinkage())
520 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
524 bool HasUnnamedAddr = SGV->hasUnnamedAddr() && DGV->hasUnnamedAddr();
526 // If the visibilities of the symbols disagree and the destination is a
527 // prototype, take the visibility of its input.
528 if (DGV->isDeclaration())
529 DGV->setVisibility(SGV->getVisibility());
531 if (DGV->hasAppendingLinkage()) {
532 // No linking is performed yet. Just insert a new copy of the global, and
533 // keep track of the fact that it is an appending variable in the
534 // AppendingVars map. The name is cleared out so that no linkage is
536 GlobalVariable *NewDGV =
537 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
538 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
540 SGV->getType()->getAddressSpace());
542 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
543 NewDGV->setAlignment(DGV->getAlignment());
544 // Propagate alignment, section and visibility info.
545 CopyGVAttributes(NewDGV, SGV);
547 // Make sure to remember this mapping...
548 ValueMap[SGV] = NewDGV;
550 // Keep track that this is an appending variable...
551 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
556 if (isa<GlobalAlias>(DGV))
557 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
558 "': symbol multiple defined");
560 // If the types don't match, and if we are to link from the source, nuke
561 // DGV and create a new one of the appropriate type. Note that the thing
562 // we are replacing may be a function (if a prototype, weak, etc) or a
564 GlobalVariable *NewDGV =
565 new GlobalVariable(*Dest, SGV->getType()->getElementType(),
566 SGV->isConstant(), NewLinkage, /*init*/0,
567 DGV->getName(), 0, false,
568 SGV->getType()->getAddressSpace());
570 // Set the unnamed_addr.
571 NewDGV->setUnnamedAddr(HasUnnamedAddr);
573 // Propagate alignment, section, and visibility info.
574 CopyGVAttributes(NewDGV, SGV);
575 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
578 // DGV will conflict with NewDGV because they both had the same
579 // name. We must erase this now so ForceRenaming doesn't assert
580 // because DGV might not have internal linkage.
581 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
582 Var->eraseFromParent();
584 cast<Function>(DGV)->eraseFromParent();
586 // If the symbol table renamed the global, but it is an externally visible
587 // symbol, DGV must be an existing global with internal linkage. Rename.
588 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
589 ForceRenaming(NewDGV, SGV->getName());
591 // Inherit const as appropriate.
592 NewDGV->setConstant(SGV->isConstant());
594 // Make sure to remember this mapping.
595 ValueMap[SGV] = NewDGV;
599 // Not "link from source", keep the one in the DestModule and remap the
602 // Special case for const propagation.
603 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
604 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
605 DGVar->setConstant(true);
607 // SGV is global, but DGV is alias.
608 if (isa<GlobalAlias>(DGV)) {
609 // The only valid mappings are:
610 // - SGV is external declaration, which is effectively a no-op.
611 // - SGV is weak, when we just need to throw SGV out.
612 if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
613 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
614 "': symbol multiple defined");
617 // Set calculated linkage and unnamed_addr
618 DGV->setLinkage(NewLinkage);
619 DGV->setUnnamedAddr(HasUnnamedAddr);
621 // Make sure to remember this mapping...
622 ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
627 static GlobalValue::LinkageTypes
628 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
629 GlobalValue::LinkageTypes SL = SGV->getLinkage();
630 GlobalValue::LinkageTypes DL = DGV->getLinkage();
631 if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
632 return GlobalValue::ExternalLinkage;
633 else if (SL == GlobalValue::WeakAnyLinkage ||
634 DL == GlobalValue::WeakAnyLinkage)
635 return GlobalValue::WeakAnyLinkage;
636 else if (SL == GlobalValue::WeakODRLinkage ||
637 DL == GlobalValue::WeakODRLinkage)
638 return GlobalValue::WeakODRLinkage;
639 else if (SL == GlobalValue::InternalLinkage &&
640 DL == GlobalValue::InternalLinkage)
641 return GlobalValue::InternalLinkage;
642 else if (SL == GlobalValue::LinkerPrivateLinkage &&
643 DL == GlobalValue::LinkerPrivateLinkage)
644 return GlobalValue::LinkerPrivateLinkage;
645 else if (SL == GlobalValue::LinkerPrivateWeakLinkage &&
646 DL == GlobalValue::LinkerPrivateWeakLinkage)
647 return GlobalValue::LinkerPrivateWeakLinkage;
648 else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage &&
649 DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage)
650 return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
652 assert (SL == GlobalValue::PrivateLinkage &&
653 DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
654 return GlobalValue::PrivateLinkage;
658 // LinkAlias - Loop through the alias in the src module and link them into the
659 // dest module. We're assuming, that all functions/global variables were already
661 static bool LinkAlias(Module *Dest, const Module *Src,
662 ValueToValueMapTy &ValueMap,
664 // Loop over all alias in the src module
665 for (Module::const_alias_iterator I = Src->alias_begin(),
666 E = Src->alias_end(); I != E; ++I) {
667 const GlobalAlias *SGA = I;
668 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
669 GlobalAlias *NewGA = NULL;
671 // Globals were already linked, thus we can just query ValueMap for variant
672 // of SAliasee in Dest.
673 ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee);
674 assert(VMI != ValueMap.end() && "Aliasee not linked");
675 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
676 GlobalValue* DGV = NULL;
678 // Fixup aliases to bitcasts. Note that aliases to GEPs are still broken
679 // by this, but aliases to GEPs are broken to a lot of other things, so
680 // it's less important.
681 Constant *DAliaseeConst = DAliasee;
682 if (SGA->getType() != DAliasee->getType())
683 DAliaseeConst = ConstantExpr::getBitCast(DAliasee, SGA->getType());
685 // Try to find something 'similar' to SGA in destination module.
686 if (!DGV && !SGA->hasLocalLinkage()) {
687 DGV = Dest->getNamedAlias(SGA->getName());
689 // If types don't agree due to opaque types, try to resolve them.
690 if (DGV && DGV->getType() != SGA->getType())
691 RecursiveResolveTypes(SGA->getType(), DGV->getType());
694 if (!DGV && !SGA->hasLocalLinkage()) {
695 DGV = Dest->getGlobalVariable(SGA->getName());
697 // If types don't agree due to opaque types, try to resolve them.
698 if (DGV && DGV->getType() != SGA->getType())
699 RecursiveResolveTypes(SGA->getType(), DGV->getType());
702 if (!DGV && !SGA->hasLocalLinkage()) {
703 DGV = Dest->getFunction(SGA->getName());
705 // If types don't agree due to opaque types, try to resolve them.
706 if (DGV && DGV->getType() != SGA->getType())
707 RecursiveResolveTypes(SGA->getType(), DGV->getType());
710 // No linking to be performed on internal stuff.
711 if (DGV && DGV->hasLocalLinkage())
714 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
715 // Types are known to be the same, check whether aliasees equal. As
716 // globals are already linked we just need query ValueMap to find the
718 if (DAliasee == DGA->getAliasedGlobal()) {
719 // This is just two copies of the same alias. Propagate linkage, if
721 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
724 // Proceed to 'common' steps
726 return Error(Err, "Alias Collision on '" + SGA->getName()+
727 "': aliases have different aliasees");
728 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
729 // The only allowed way is to link alias with external declaration or weak
731 if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
732 // But only if aliasee is global too...
733 if (!isa<GlobalVariable>(DAliasee))
734 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
735 "': aliasee is not global variable");
737 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
738 SGA->getName(), DAliaseeConst, Dest);
739 CopyGVAttributes(NewGA, SGA);
741 // Any uses of DGV need to change to NewGA, with cast, if needed.
742 if (SGA->getType() != DGVar->getType())
743 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
746 DGVar->replaceAllUsesWith(NewGA);
748 // DGVar will conflict with NewGA because they both had the same
749 // name. We must erase this now so ForceRenaming doesn't assert
750 // because DGV might not have internal linkage.
751 DGVar->eraseFromParent();
753 // Proceed to 'common' steps
755 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
756 "': symbol multiple defined");
757 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
758 // The only allowed way is to link alias with external declaration or weak
760 if (DF->isDeclaration() || DF->isWeakForLinker()) {
761 // But only if aliasee is function too...
762 if (!isa<Function>(DAliasee))
763 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
764 "': aliasee is not function");
766 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
767 SGA->getName(), DAliaseeConst, Dest);
768 CopyGVAttributes(NewGA, SGA);
770 // Any uses of DF need to change to NewGA, with cast, if needed.
771 if (SGA->getType() != DF->getType())
772 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
775 DF->replaceAllUsesWith(NewGA);
777 // DF will conflict with NewGA because they both had the same
778 // name. We must erase this now so ForceRenaming doesn't assert
779 // because DF might not have internal linkage.
780 DF->eraseFromParent();
782 // Proceed to 'common' steps
784 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
785 "': symbol multiple defined");
787 // No linking to be performed, simply create an identical version of the
788 // alias over in the dest module...
789 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
790 SGA->getName(), DAliaseeConst, Dest);
791 CopyGVAttributes(NewGA, SGA);
793 // Proceed to 'common' steps
796 assert(NewGA && "No alias was created in destination module!");
798 // If the symbol table renamed the alias, but it is an externally visible
799 // symbol, DGA must be an global value with internal linkage. Rename it.
800 if (NewGA->getName() != SGA->getName() &&
801 !NewGA->hasLocalLinkage())
802 ForceRenaming(NewGA, SGA->getName());
804 // Remember this mapping so uses in the source module get remapped
805 // later by MapValue.
806 ValueMap[SGA] = NewGA;
813 // LinkGlobalInits - Update the initializers in the Dest module now that all
814 // globals that may be referenced are in Dest.
815 static bool LinkGlobalInits(Module *Dest, const Module *Src,
816 ValueToValueMapTy &ValueMap,
818 // Loop over all of the globals in the src module, mapping them over as we go
819 for (Module::const_global_iterator I = Src->global_begin(),
820 E = Src->global_end(); I != E; ++I) {
821 const GlobalVariable *SGV = I;
823 if (SGV->hasInitializer()) { // Only process initialized GV's
824 // Figure out what the initializer looks like in the dest module.
826 cast<Constant>(MapValue(SGV->getInitializer(), ValueMap));
827 // Grab destination global variable or alias.
828 GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
830 // If dest if global variable, check that initializers match.
831 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
832 if (DGVar->hasInitializer()) {
833 if (SGV->hasExternalLinkage()) {
834 if (DGVar->getInitializer() != SInit)
835 return Error(Err, "Global Variable Collision on '" +
837 "': global variables have different initializers");
838 } else if (DGVar->isWeakForLinker()) {
839 // Nothing is required, mapped values will take the new global
841 } else if (SGV->isWeakForLinker()) {
842 // Nothing is required, mapped values will take the new global
844 } else if (DGVar->hasAppendingLinkage()) {
845 llvm_unreachable("Appending linkage unimplemented!");
847 llvm_unreachable("Unknown linkage!");
850 // Copy the initializer over now...
851 DGVar->setInitializer(SInit);
854 // Destination is alias, the only valid situation is when source is
855 // weak. Also, note, that we already checked linkage in LinkGlobals(),
856 // thus we assert here.
857 // FIXME: Should we weaken this assumption, 'dereference' alias and
858 // check for initializer of aliasee?
859 assert(SGV->isWeakForLinker());
866 // LinkFunctionProtos - Link the functions together between the two modules,
867 // without doing function bodies... this just adds external function prototypes
868 // to the Dest function...
870 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
871 ValueToValueMapTy &ValueMap,
873 ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
875 // Loop over all of the functions in the src module, mapping them over
876 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
877 const Function *SF = I; // SrcFunction
878 GlobalValue *DGV = 0;
880 // Check to see if may have to link the function with the global, alias or
882 if (SF->hasName() && !SF->hasLocalLinkage())
883 DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
885 // If we found a global with the same name in the dest module, but it has
886 // internal linkage, we are really not doing any linkage here.
887 if (DGV && DGV->hasLocalLinkage())
890 // If types don't agree due to opaque types, try to resolve them.
891 if (DGV && DGV->getType() != SF->getType())
892 RecursiveResolveTypes(SF->getType(), DGV->getType());
894 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
895 bool LinkFromSrc = false;
896 if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
899 // If there is no linkage to be performed, just bring over SF without
902 // Function does not already exist, simply insert an function signature
903 // identical to SF into the dest module.
904 Function *NewDF = Function::Create(SF->getFunctionType(),
906 SF->getName(), Dest);
907 CopyGVAttributes(NewDF, SF);
909 // If the LLVM runtime renamed the function, but it is an externally
910 // visible symbol, DF must be an existing function with internal linkage.
912 if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
913 ForceRenaming(NewDF, SF->getName());
915 // ... and remember this mapping...
916 ValueMap[SF] = NewDF;
920 // If the visibilities of the symbols disagree and the destination is a
921 // prototype, take the visibility of its input.
922 if (DGV->isDeclaration())
923 DGV->setVisibility(SF->getVisibility());
926 if (isa<GlobalAlias>(DGV))
927 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
928 "': symbol multiple defined");
930 // We have a definition of the same name but different type in the
931 // source module. Copy the prototype to the destination and replace
932 // uses of the destination's prototype with the new prototype.
933 Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
934 SF->getName(), Dest);
935 CopyGVAttributes(NewDF, SF);
937 // Any uses of DF need to change to NewDF, with cast
938 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
941 // DF will conflict with NewDF because they both had the same. We must
942 // erase this now so ForceRenaming doesn't assert because DF might
943 // not have internal linkage.
944 if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
945 Var->eraseFromParent();
947 cast<Function>(DGV)->eraseFromParent();
949 // If the symbol table renamed the function, but it is an externally
950 // visible symbol, DF must be an existing function with internal
951 // linkage. Rename it.
952 if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
953 ForceRenaming(NewDF, SF->getName());
955 // Remember this mapping so uses in the source module get remapped
956 // later by MapValue.
957 ValueMap[SF] = NewDF;
961 // Not "link from source", keep the one in the DestModule and remap the
964 if (isa<GlobalAlias>(DGV)) {
965 // The only valid mappings are:
966 // - SF is external declaration, which is effectively a no-op.
967 // - SF is weak, when we just need to throw SF out.
968 if (!SF->isDeclaration() && !SF->isWeakForLinker())
969 return Error(Err, "Function-Alias Collision on '" + SF->getName() +
970 "': symbol multiple defined");
973 // Set calculated linkage
974 DGV->setLinkage(NewLinkage);
976 // Make sure to remember this mapping.
977 ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
982 // LinkFunctionBody - Copy the source function over into the dest function and
983 // fix up references to values. At this point we know that Dest is an external
984 // function, and that Src is not.
985 static bool LinkFunctionBody(Function *Dest, Function *Src,
986 ValueToValueMapTy &ValueMap,
988 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
990 // Go through and convert function arguments over, remembering the mapping.
991 Function::arg_iterator DI = Dest->arg_begin();
992 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
994 DI->setName(I->getName()); // Copy the name information over...
996 // Add a mapping to our local map
1000 // Splice the body of the source function into the dest function.
1001 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1003 // At this point, all of the instructions and values of the function are now
1004 // copied over. The only problem is that they are still referencing values in
1005 // the Source function as operands. Loop through all of the operands of the
1006 // functions and patch them up to point to the local versions.
1007 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1008 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1009 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries);
1011 // There is no need to map the arguments anymore.
1012 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1020 // LinkFunctionBodies - Link in the function bodies that are defined in the
1021 // source module into the DestModule. This consists basically of copying the
1022 // function over and fixing up references to values.
1023 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1024 ValueToValueMapTy &ValueMap,
1027 // Loop over all of the functions in the src module, mapping them over as we
1029 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1030 if (!SF->isDeclaration()) { // No body if function is external
1031 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1033 // DF not external SF external?
1034 if (DF && DF->isDeclaration())
1035 // Only provide the function body if there isn't one already.
1036 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1043 // LinkAppendingVars - If there were any appending global variables, link them
1044 // together now. Return true on error.
1045 static bool LinkAppendingVars(Module *M,
1046 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1047 std::string *ErrorMsg) {
1048 if (AppendingVars.empty()) return false; // Nothing to do.
1050 // Loop over the multimap of appending vars, processing any variables with the
1051 // same name, forming a new appending global variable with both of the
1052 // initializers merged together, then rewrite references to the old variables
1054 std::vector<Constant*> Inits;
1055 while (AppendingVars.size() > 1) {
1056 // Get the first two elements in the map...
1057 std::multimap<std::string,
1058 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1060 // If the first two elements are for different names, there is no pair...
1061 // Otherwise there is a pair, so link them together...
1062 if (First->first == Second->first) {
1063 GlobalVariable *G1 = First->second, *G2 = Second->second;
1064 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1065 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1067 // Check to see that they two arrays agree on type...
1068 if (T1->getElementType() != T2->getElementType())
1069 return Error(ErrorMsg,
1070 "Appending variables with different element types need to be linked!");
1071 if (G1->isConstant() != G2->isConstant())
1072 return Error(ErrorMsg,
1073 "Appending variables linked with different const'ness!");
1075 if (G1->getAlignment() != G2->getAlignment())
1076 return Error(ErrorMsg,
1077 "Appending variables with different alignment need to be linked!");
1079 if (G1->getVisibility() != G2->getVisibility())
1080 return Error(ErrorMsg,
1081 "Appending variables with different visibility need to be linked!");
1083 if (G1->getSection() != G2->getSection())
1084 return Error(ErrorMsg,
1085 "Appending variables with different section name need to be linked!");
1087 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1088 ArrayType *NewType = ArrayType::get(T1->getElementType(),
1091 G1->setName(""); // Clear G1's name in case of a conflict!
1093 // Create the new global variable...
1094 GlobalVariable *NG =
1095 new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1096 /*init*/0, First->first, 0, G1->isThreadLocal(),
1097 G1->getType()->getAddressSpace());
1099 // Propagate alignment, visibility and section info.
1100 CopyGVAttributes(NG, G1);
1102 // Merge the initializer...
1103 Inits.reserve(NewSize);
1104 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1105 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1106 Inits.push_back(I->getOperand(i));
1108 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1109 Constant *CV = Constant::getNullValue(T1->getElementType());
1110 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1111 Inits.push_back(CV);
1113 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1114 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1115 Inits.push_back(I->getOperand(i));
1117 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1118 Constant *CV = Constant::getNullValue(T2->getElementType());
1119 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1120 Inits.push_back(CV);
1122 NG->setInitializer(ConstantArray::get(NewType, Inits));
1125 // Replace any uses of the two global variables with uses of the new
1128 // FIXME: This should rewrite simple/straight-forward uses such as
1129 // getelementptr instructions to not use the Cast!
1130 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1132 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1135 // Remove the two globals from the module now...
1136 M->getGlobalList().erase(G1);
1137 M->getGlobalList().erase(G2);
1139 // Put the new global into the AppendingVars map so that we can handle
1140 // linking of more than two vars...
1141 Second->second = NG;
1143 AppendingVars.erase(First);
1149 static bool ResolveAliases(Module *Dest) {
1150 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1152 // We can't sue resolveGlobalAlias here because we need to preserve
1153 // bitcasts and GEPs.
1154 if (const Constant *C = I->getAliasee()) {
1155 while (dyn_cast<GlobalAlias>(C))
1156 C = cast<GlobalAlias>(C)->getAliasee();
1157 const GlobalValue *GV = dyn_cast<GlobalValue>(C);
1158 if (C != I && !(GV && GV->isDeclaration()))
1159 I->replaceAllUsesWith(const_cast<Constant*>(C));
1165 // LinkModules - This function links two modules together, with the resulting
1166 // left module modified to be the composite of the two input modules. If an
1167 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1168 // the problem. Upon failure, the Dest module could be in a modified state, and
1169 // shouldn't be relied on to be consistent.
1171 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1172 assert(Dest != 0 && "Invalid Destination module");
1173 assert(Src != 0 && "Invalid Source Module");
1175 if (Dest->getDataLayout().empty()) {
1176 if (!Src->getDataLayout().empty()) {
1177 Dest->setDataLayout(Src->getDataLayout());
1179 std::string DataLayout;
1181 if (Dest->getEndianness() == Module::AnyEndianness) {
1182 if (Src->getEndianness() == Module::BigEndian)
1183 DataLayout.append("E");
1184 else if (Src->getEndianness() == Module::LittleEndian)
1185 DataLayout.append("e");
1188 if (Dest->getPointerSize() == Module::AnyPointerSize) {
1189 if (Src->getPointerSize() == Module::Pointer64)
1190 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1191 else if (Src->getPointerSize() == Module::Pointer32)
1192 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1194 Dest->setDataLayout(DataLayout);
1198 // Copy the target triple from the source to dest if the dest's is empty.
1199 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1200 Dest->setTargetTriple(Src->getTargetTriple());
1202 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1203 Src->getDataLayout() != Dest->getDataLayout())
1204 errs() << "WARNING: Linking two modules of different data layouts!\n";
1205 if (!Src->getTargetTriple().empty() &&
1206 Dest->getTargetTriple() != Src->getTargetTriple()) {
1207 errs() << "WARNING: Linking two modules of different target triples: ";
1208 if (!Src->getModuleIdentifier().empty())
1209 errs() << Src->getModuleIdentifier() << ": ";
1210 errs() << "'" << Src->getTargetTriple() << "' and '"
1211 << Dest->getTargetTriple() << "'\n";
1214 // Append the module inline asm string.
1215 if (!Src->getModuleInlineAsm().empty()) {
1216 if (Dest->getModuleInlineAsm().empty())
1217 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1219 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1220 Src->getModuleInlineAsm());
1223 // Update the destination module's dependent libraries list with the libraries
1224 // from the source module. There's no opportunity for duplicates here as the
1225 // Module ensures that duplicate insertions are discarded.
1226 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1228 Dest->addLibrary(*SI);
1230 // LinkTypes - Go through the symbol table of the Src module and see if any
1231 // types are named in the src module that are not named in the Dst module.
1232 // Make sure there are no type name conflicts.
1233 if (LinkTypes(Dest, Src, ErrorMsg))
1236 // ValueMap - Mapping of values from what they used to be in Src, to what they
1237 // are now in Dest. ValueToValueMapTy is a ValueMap, which involves some
1238 // overhead due to the use of Value handles which the Linker doesn't actually
1239 // need, but this allows us to reuse the ValueMapper code.
1240 ValueToValueMapTy ValueMap;
1242 // AppendingVars - Keep track of global variables in the destination module
1243 // with appending linkage. After the module is linked together, they are
1244 // appended and the module is rewritten.
1245 std::multimap<std::string, GlobalVariable *> AppendingVars;
1246 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1248 // Add all of the appending globals already in the Dest module to
1250 if (I->hasAppendingLinkage())
1251 AppendingVars.insert(std::make_pair(I->getName(), I));
1254 // Insert all of the globals in src into the Dest module... without linking
1255 // initializers (which could refer to functions not yet mapped over).
1256 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1259 // Link the functions together between the two modules, without doing function
1260 // bodies... this just adds external function prototypes to the Dest
1261 // function... We do this so that when we begin processing function bodies,
1262 // all of the global values that may be referenced are available in our
1264 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1267 // If there were any alias, link them now. We really need to do this now,
1268 // because all of the aliases that may be referenced need to be available in
1270 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1272 // Update the initializers in the Dest module now that all globals that may
1273 // be referenced are in Dest.
1274 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1276 // Link in the function bodies that are defined in the source module into the
1277 // DestModule. This consists basically of copying the function over and
1278 // fixing up references to values.
1279 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1281 // If there were any appending global variables, link them together now.
1282 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1284 // Resolve all uses of aliases with aliasees
1285 if (ResolveAliases(Dest)) return true;
1287 // Remap all of the named mdnoes in Src into the Dest module. We do this
1288 // after linking GlobalValues so that MDNodes that reference GlobalValues
1289 // are properly remapped.
1290 LinkNamedMDNodes(Dest, Src, ValueMap);
1292 // If the source library's module id is in the dependent library list of the
1293 // destination library, remove it since that module is now linked in.
1294 const std::string &modId = Src->getModuleIdentifier();
1296 Dest->removeLibrary(sys::path::stem(modId));