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 //===----------------------------------------------------------------------===//
14 #include "llvm/Linker.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Transforms/Utils/Cloning.h"
24 #include "llvm/Transforms/Utils/ValueMapper.h"
27 //===----------------------------------------------------------------------===//
28 // TypeMap implementation.
29 //===----------------------------------------------------------------------===//
32 class TypeMapTy : public ValueMapTypeRemapper {
33 /// MappedTypes - This is a mapping from a source type to a destination type
35 DenseMap<Type*, Type*> MappedTypes;
37 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
38 /// we speculatively add types to MappedTypes, but keep track of them here in
39 /// case we need to roll back.
40 SmallVector<Type*, 16> SpeculativeTypes;
42 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
43 /// source module that are mapped to an opaque struct in the destination
45 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
47 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
48 /// destination modules who are getting a body from the source module.
49 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
52 /// addTypeMapping - Indicate that the specified type in the destination
53 /// module is conceptually equivalent to the specified type in the source
55 void addTypeMapping(Type *DstTy, Type *SrcTy);
57 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
58 /// module from a type definition in the source module.
59 void linkDefinedTypeBodies();
61 /// get - Return the mapped type to use for the specified input type from the
63 Type *get(Type *SrcTy);
65 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
68 Type *getImpl(Type *T);
69 /// remapType - Implement the ValueMapTypeRemapper interface.
70 Type *remapType(Type *SrcTy) {
74 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
78 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
79 Type *&Entry = MappedTypes[SrcTy];
87 // Check to see if these types are recursively isomorphic and establish a
88 // mapping between them if so.
89 if (!areTypesIsomorphic(DstTy, SrcTy)) {
90 // Oops, they aren't isomorphic. Just discard this request by rolling out
91 // any speculative mappings we've established.
92 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
93 MappedTypes.erase(SpeculativeTypes[i]);
95 SpeculativeTypes.clear();
98 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
99 /// if they are isomorphic, false if they are not.
100 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
101 // Two types with differing kinds are clearly not isomorphic.
102 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
104 // If we have an entry in the MappedTypes table, then we have our answer.
105 Type *&Entry = MappedTypes[SrcTy];
107 return Entry == DstTy;
109 // Two identical types are clearly isomorphic. Remember this
110 // non-speculatively.
111 if (DstTy == SrcTy) {
116 // Okay, we have two types with identical kinds that we haven't seen before.
118 // If this is an opaque struct type, special case it.
119 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
120 // Mapping an opaque type to any struct, just keep the dest struct.
121 if (SSTy->isOpaque()) {
123 SpeculativeTypes.push_back(SrcTy);
127 // Mapping a non-opaque source type to an opaque dest. If this is the first
128 // type that we're mapping onto this destination type then we succeed. Keep
129 // the dest, but fill it in later. This doesn't need to be speculative. If
130 // this is the second (different) type that we're trying to map onto the
131 // same opaque type then we fail.
132 if (cast<StructType>(DstTy)->isOpaque()) {
133 // We can only map one source type onto the opaque destination type.
134 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
136 SrcDefinitionsToResolve.push_back(SSTy);
142 // If the number of subtypes disagree between the two types, then we fail.
143 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
146 // Fail if any of the extra properties (e.g. array size) of the type disagree.
147 if (isa<IntegerType>(DstTy))
148 return false; // bitwidth disagrees.
149 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
150 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
153 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
154 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
156 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
157 StructType *SSTy = cast<StructType>(SrcTy);
158 if (DSTy->isLiteral() != SSTy->isLiteral() ||
159 DSTy->isPacked() != SSTy->isPacked())
161 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
162 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
164 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
165 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
169 // Otherwise, we speculate that these two types will line up and recursively
170 // check the subelements.
172 SpeculativeTypes.push_back(SrcTy);
174 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
175 if (!areTypesIsomorphic(DstTy->getContainedType(i),
176 SrcTy->getContainedType(i)))
179 // If everything seems to have lined up, then everything is great.
183 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
184 /// module from a type definition in the source module.
185 void TypeMapTy::linkDefinedTypeBodies() {
186 SmallVector<Type*, 16> Elements;
187 SmallString<16> TmpName;
189 // Note that processing entries in this loop (calling 'get') can add new
190 // entries to the SrcDefinitionsToResolve vector.
191 while (!SrcDefinitionsToResolve.empty()) {
192 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
193 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
195 // TypeMap is a many-to-one mapping, if there were multiple types that
196 // provide a body for DstSTy then previous iterations of this loop may have
197 // already handled it. Just ignore this case.
198 if (!DstSTy->isOpaque()) continue;
199 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
201 // Map the body of the source type over to a new body for the dest type.
202 Elements.resize(SrcSTy->getNumElements());
203 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
204 Elements[i] = getImpl(SrcSTy->getElementType(i));
206 DstSTy->setBody(Elements, SrcSTy->isPacked());
208 // If DstSTy has no name or has a longer name than STy, then viciously steal
210 if (!SrcSTy->hasName()) continue;
211 StringRef SrcName = SrcSTy->getName();
213 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
214 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
216 DstSTy->setName(TmpName.str());
221 DstResolvedOpaqueTypes.clear();
225 /// get - Return the mapped type to use for the specified input type from the
227 Type *TypeMapTy::get(Type *Ty) {
228 Type *Result = getImpl(Ty);
230 // If this caused a reference to any struct type, resolve it before returning.
231 if (!SrcDefinitionsToResolve.empty())
232 linkDefinedTypeBodies();
236 /// getImpl - This is the recursive version of get().
237 Type *TypeMapTy::getImpl(Type *Ty) {
238 // If we already have an entry for this type, return it.
239 Type **Entry = &MappedTypes[Ty];
240 if (*Entry) return *Entry;
242 // If this is not a named struct type, then just map all of the elements and
243 // then rebuild the type from inside out.
244 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
245 // If there are no element types to map, then the type is itself. This is
246 // true for the anonymous {} struct, things like 'float', integers, etc.
247 if (Ty->getNumContainedTypes() == 0)
250 // Remap all of the elements, keeping track of whether any of them change.
251 bool AnyChange = false;
252 SmallVector<Type*, 4> ElementTypes;
253 ElementTypes.resize(Ty->getNumContainedTypes());
254 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
255 ElementTypes[i] = getImpl(Ty->getContainedType(i));
256 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
259 // If we found our type while recursively processing stuff, just use it.
260 Entry = &MappedTypes[Ty];
261 if (*Entry) return *Entry;
263 // If all of the element types mapped directly over, then the type is usable
268 // Otherwise, rebuild a modified type.
269 switch (Ty->getTypeID()) {
270 default: assert(0 && "unknown derived type to remap");
271 case Type::ArrayTyID:
272 return *Entry = ArrayType::get(ElementTypes[0],
273 cast<ArrayType>(Ty)->getNumElements());
274 case Type::VectorTyID:
275 return *Entry = VectorType::get(ElementTypes[0],
276 cast<VectorType>(Ty)->getNumElements());
277 case Type::PointerTyID:
278 return *Entry = PointerType::get(ElementTypes[0],
279 cast<PointerType>(Ty)->getAddressSpace());
280 case Type::FunctionTyID:
281 return *Entry = FunctionType::get(ElementTypes[0],
282 makeArrayRef(ElementTypes).slice(1),
283 cast<FunctionType>(Ty)->isVarArg());
284 case Type::StructTyID:
285 // Note that this is only reached for anonymous structs.
286 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
287 cast<StructType>(Ty)->isPacked());
291 // Otherwise, this is an unmapped named struct. If the struct can be directly
292 // mapped over, just use it as-is. This happens in a case when the linked-in
293 // module has something like:
294 // %T = type {%T*, i32}
295 // @GV = global %T* null
296 // where T does not exist at all in the destination module.
298 // The other case we watch for is when the type is not in the destination
299 // module, but that it has to be rebuilt because it refers to something that
300 // is already mapped. For example, if the destination module has:
302 // and the source module has something like
303 // %A' = type { i32 }
304 // %B = type { %A'* }
305 // @GV = global %B* null
306 // then we want to create a new type: "%B = type { %A*}" and have it take the
307 // pristine "%B" name from the source module.
309 // To determine which case this is, we have to recursively walk the type graph
310 // speculating that we'll be able to reuse it unmodified. Only if this is
311 // safe would we map the entire thing over. Because this is an optimization,
312 // and is not required for the prettiness of the linked module, we just skip
313 // it and always rebuild a type here.
314 StructType *STy = cast<StructType>(Ty);
316 // If the type is opaque, we can just use it directly.
320 // Otherwise we create a new type and resolve its body later. This will be
321 // resolved by the top level of get().
322 SrcDefinitionsToResolve.push_back(STy);
323 StructType *DTy = StructType::create(STy->getContext());
324 DstResolvedOpaqueTypes.insert(DTy);
330 //===----------------------------------------------------------------------===//
331 // ModuleLinker implementation.
332 //===----------------------------------------------------------------------===//
335 /// ModuleLinker - This is an implementation class for the LinkModules
336 /// function, which is the entrypoint for this file.
342 /// ValueMap - Mapping of values from what they used to be in Src, to what
343 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
344 /// some overhead due to the use of Value handles which the Linker doesn't
345 /// actually need, but this allows us to reuse the ValueMapper code.
346 ValueToValueMapTy ValueMap;
348 struct AppendingVarInfo {
349 GlobalVariable *NewGV; // New aggregate global in dest module.
350 Constant *DstInit; // Old initializer from dest module.
351 Constant *SrcInit; // Old initializer from src module.
354 std::vector<AppendingVarInfo> AppendingVars;
356 unsigned Mode; // Mode to treat source module.
358 // Set of items not to link in from source.
359 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
361 // Vector of functions to lazily link in.
362 std::vector<Function*> LazilyLinkFunctions;
365 std::string ErrorMsg;
367 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
368 : DstM(dstM), SrcM(srcM), Mode(mode) { }
373 /// emitError - Helper method for setting a message and returning an error
375 bool emitError(const Twine &Message) {
376 ErrorMsg = Message.str();
380 /// getLinkageResult - This analyzes the two global values and determines
381 /// what the result will look like in the destination module.
382 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
383 GlobalValue::LinkageTypes <,
384 GlobalValue::VisibilityTypes &Vis,
387 /// getLinkedToGlobal - Given a global in the source module, return the
388 /// global in the destination module that is being linked to, if any.
389 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
390 // If the source has no name it can't link. If it has local linkage,
391 // there is no name match-up going on.
392 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
395 // Otherwise see if we have a match in the destination module's symtab.
396 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
397 if (DGV == 0) return 0;
399 // If we found a global with the same name in the dest module, but it has
400 // internal linkage, we are really not doing any linkage here.
401 if (DGV->hasLocalLinkage())
404 // Otherwise, we do in fact link to the destination global.
408 void computeTypeMapping();
410 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
411 bool linkGlobalProto(GlobalVariable *SrcGV);
412 bool linkFunctionProto(Function *SrcF);
413 bool linkAliasProto(GlobalAlias *SrcA);
415 void linkAppendingVarInit(const AppendingVarInfo &AVI);
416 void linkGlobalInits();
417 void linkFunctionBody(Function *Dst, Function *Src);
418 void linkAliasBodies();
419 void linkNamedMDNodes();
425 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
426 /// in the symbol table. This is good for all clients except for us. Go
427 /// through the trouble to force this back.
428 static void forceRenaming(GlobalValue *GV, StringRef Name) {
429 // If the global doesn't force its name or if it already has the right name,
430 // there is nothing for us to do.
431 if (GV->hasLocalLinkage() || GV->getName() == Name)
434 Module *M = GV->getParent();
436 // If there is a conflict, rename the conflict.
437 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
438 GV->takeName(ConflictGV);
439 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
440 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
442 GV->setName(Name); // Force the name back
446 /// CopyGVAttributes - copy additional attributes (those not needed to construct
447 /// a GlobalValue) from the SrcGV to the DestGV.
448 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
449 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
450 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
451 DestGV->copyAttributesFrom(SrcGV);
452 DestGV->setAlignment(Alignment);
454 forceRenaming(DestGV, SrcGV->getName());
457 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
458 GlobalValue::VisibilityTypes b) {
459 if (a == GlobalValue::HiddenVisibility)
461 if (b == GlobalValue::HiddenVisibility)
463 if (a == GlobalValue::ProtectedVisibility)
465 if (b == GlobalValue::ProtectedVisibility)
470 /// getLinkageResult - This analyzes the two global values and determines what
471 /// the result will look like in the destination module. In particular, it
472 /// computes the resultant linkage type and visibility, computes whether the
473 /// global in the source should be copied over to the destination (replacing
474 /// the existing one), and computes whether this linkage is an error or not.
475 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
476 GlobalValue::LinkageTypes <,
477 GlobalValue::VisibilityTypes &Vis,
479 assert(Dest && "Must have two globals being queried");
480 assert(!Src->hasLocalLinkage() &&
481 "If Src has internal linkage, Dest shouldn't be set!");
483 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
484 bool DestIsDeclaration = Dest->isDeclaration();
486 if (SrcIsDeclaration) {
487 // If Src is external or if both Src & Dest are external.. Just link the
488 // external globals, we aren't adding anything.
489 if (Src->hasDLLImportLinkage()) {
490 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
491 if (DestIsDeclaration) {
493 LT = Src->getLinkage();
495 } else if (Dest->hasExternalWeakLinkage()) {
496 // If the Dest is weak, use the source linkage.
498 LT = Src->getLinkage();
501 LT = Dest->getLinkage();
503 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
504 // If Dest is external but Src is not:
506 LT = Src->getLinkage();
507 } else if (Src->isWeakForLinker()) {
508 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
510 if (Dest->hasExternalWeakLinkage() ||
511 Dest->hasAvailableExternallyLinkage() ||
512 (Dest->hasLinkOnceLinkage() &&
513 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
515 LT = Src->getLinkage();
518 LT = Dest->getLinkage();
520 } else if (Dest->isWeakForLinker()) {
521 // At this point we know that Src has External* or DLL* linkage.
522 if (Src->hasExternalWeakLinkage()) {
524 LT = Dest->getLinkage();
527 LT = GlobalValue::ExternalLinkage;
530 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
531 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
532 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
533 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
534 "Unexpected linkage type!");
535 return emitError("Linking globals named '" + Src->getName() +
536 "': symbol multiply defined!");
539 // Compute the visibility. We follow the rules in the System V Application
541 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
542 Dest->getVisibility() : Src->getVisibility();
546 /// computeTypeMapping - Loop over all of the linked values to compute type
547 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
548 /// we have two struct types 'Foo' but one got renamed when the module was
549 /// loaded into the same LLVMContext.
550 void ModuleLinker::computeTypeMapping() {
551 // Incorporate globals.
552 for (Module::global_iterator I = SrcM->global_begin(),
553 E = SrcM->global_end(); I != E; ++I) {
554 GlobalValue *DGV = getLinkedToGlobal(I);
555 if (DGV == 0) continue;
557 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
558 TypeMap.addTypeMapping(DGV->getType(), I->getType());
562 // Unify the element type of appending arrays.
563 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
564 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
565 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
568 // Incorporate functions.
569 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
570 if (GlobalValue *DGV = getLinkedToGlobal(I))
571 TypeMap.addTypeMapping(DGV->getType(), I->getType());
574 // Incorporate types by name, scanning all the types in the source module.
575 // At this point, the destination module may have a type "%foo = { i32 }" for
576 // example. When the source module got loaded into the same LLVMContext, if
577 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
578 // Though it isn't required for correctness, attempt to link these up to clean
580 std::vector<StructType*> SrcStructTypes;
581 SrcM->findUsedStructTypes(SrcStructTypes);
583 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
584 SrcStructTypes.end());
586 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
587 StructType *ST = SrcStructTypes[i];
588 if (!ST->hasName()) continue;
590 // Check to see if there is a dot in the name followed by a digit.
591 size_t DotPos = ST->getName().rfind('.');
592 if (DotPos == 0 || DotPos == StringRef::npos ||
593 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
596 // Check to see if the destination module has a struct with the prefix name.
597 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
598 // Don't use it if this actually came from the source module. They're in
599 // the same LLVMContext after all.
600 if (!SrcStructTypesSet.count(DST))
601 TypeMap.addTypeMapping(DST, ST);
605 // Don't bother incorporating aliases, they aren't generally typed well.
607 // Now that we have discovered all of the type equivalences, get a body for
608 // any 'opaque' types in the dest module that are now resolved.
609 TypeMap.linkDefinedTypeBodies();
612 /// linkAppendingVarProto - If there were any appending global variables, link
613 /// them together now. Return true on error.
614 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
615 GlobalVariable *SrcGV) {
617 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
618 return emitError("Linking globals named '" + SrcGV->getName() +
619 "': can only link appending global with another appending global!");
621 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
623 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
624 Type *EltTy = DstTy->getElementType();
626 // Check to see that they two arrays agree on type.
627 if (EltTy != SrcTy->getElementType())
628 return emitError("Appending variables with different element types!");
629 if (DstGV->isConstant() != SrcGV->isConstant())
630 return emitError("Appending variables linked with different const'ness!");
632 if (DstGV->getAlignment() != SrcGV->getAlignment())
634 "Appending variables with different alignment need to be linked!");
636 if (DstGV->getVisibility() != SrcGV->getVisibility())
638 "Appending variables with different visibility need to be linked!");
640 if (DstGV->getSection() != SrcGV->getSection())
642 "Appending variables with different section name need to be linked!");
644 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
645 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
647 // Create the new global variable.
649 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
650 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
651 DstGV->isThreadLocal(),
652 DstGV->getType()->getAddressSpace());
654 // Propagate alignment, visibility and section info.
655 CopyGVAttributes(NG, DstGV);
657 AppendingVarInfo AVI;
659 AVI.DstInit = DstGV->getInitializer();
660 AVI.SrcInit = SrcGV->getInitializer();
661 AppendingVars.push_back(AVI);
663 // Replace any uses of the two global variables with uses of the new
665 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
667 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
668 DstGV->eraseFromParent();
670 // Track the source variable so we don't try to link it.
671 DoNotLinkFromSource.insert(SrcGV);
676 /// linkGlobalProto - Loop through the global variables in the src module and
677 /// merge them into the dest module.
678 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
679 GlobalValue *DGV = getLinkedToGlobal(SGV);
680 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
683 // Concatenation of appending linkage variables is magic and handled later.
684 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
685 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
687 // Determine whether linkage of these two globals follows the source
688 // module's definition or the destination module's definition.
689 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
690 GlobalValue::VisibilityTypes NV;
691 bool LinkFromSrc = false;
692 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
696 // If we're not linking from the source, then keep the definition that we
699 // Special case for const propagation.
700 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
701 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
702 DGVar->setConstant(true);
704 // Set calculated linkage and visibility.
705 DGV->setLinkage(NewLinkage);
706 DGV->setVisibility(*NewVisibility);
708 // Make sure to remember this mapping.
709 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
711 // Track the source global so that we don't attempt to copy it over when
712 // processing global initializers.
713 DoNotLinkFromSource.insert(SGV);
719 // No linking to be performed or linking from the source: simply create an
720 // identical version of the symbol over in the dest module... the
721 // initializer will be filled in later by LinkGlobalInits.
722 GlobalVariable *NewDGV =
723 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
724 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
725 SGV->getName(), /*insertbefore*/0,
726 SGV->isThreadLocal(),
727 SGV->getType()->getAddressSpace());
728 // Propagate alignment, visibility and section info.
729 CopyGVAttributes(NewDGV, SGV);
731 NewDGV->setVisibility(*NewVisibility);
734 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
735 DGV->eraseFromParent();
738 // Make sure to remember this mapping.
739 ValueMap[SGV] = NewDGV;
743 /// linkFunctionProto - Link the function in the source module into the
744 /// destination module if needed, setting up mapping information.
745 bool ModuleLinker::linkFunctionProto(Function *SF) {
746 GlobalValue *DGV = getLinkedToGlobal(SF);
747 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
750 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
751 bool LinkFromSrc = false;
752 GlobalValue::VisibilityTypes NV;
753 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
758 // Set calculated linkage
759 DGV->setLinkage(NewLinkage);
760 DGV->setVisibility(*NewVisibility);
762 // Make sure to remember this mapping.
763 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
765 // Track the function from the source module so we don't attempt to remap
767 DoNotLinkFromSource.insert(SF);
773 // If there is no linkage to be performed or we are linking from the source,
775 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
776 SF->getLinkage(), SF->getName(), DstM);
777 CopyGVAttributes(NewDF, SF);
779 NewDF->setVisibility(*NewVisibility);
782 // Any uses of DF need to change to NewDF, with cast.
783 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
784 DGV->eraseFromParent();
786 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
787 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
788 SF->hasAvailableExternallyLinkage()) {
789 DoNotLinkFromSource.insert(SF);
790 LazilyLinkFunctions.push_back(SF);
794 ValueMap[SF] = NewDF;
798 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
800 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
801 GlobalValue *DGV = getLinkedToGlobal(SGA);
802 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
805 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
806 GlobalValue::VisibilityTypes NV;
807 bool LinkFromSrc = false;
808 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
813 // Set calculated linkage.
814 DGV->setLinkage(NewLinkage);
815 DGV->setVisibility(*NewVisibility);
817 // Make sure to remember this mapping.
818 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
820 // Track the alias from the source module so we don't attempt to remap it.
821 DoNotLinkFromSource.insert(SGA);
827 // If there is no linkage to be performed or we're linking from the source,
829 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
830 SGA->getLinkage(), SGA->getName(),
832 CopyGVAttributes(NewDA, SGA);
834 NewDA->setVisibility(*NewVisibility);
837 // Any uses of DGV need to change to NewDA, with cast.
838 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
839 DGV->eraseFromParent();
842 ValueMap[SGA] = NewDA;
846 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
847 // Merge the initializer.
848 SmallVector<Constant*, 16> Elements;
849 if (ConstantArray *I = dyn_cast<ConstantArray>(AVI.DstInit)) {
850 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
851 Elements.push_back(I->getOperand(i));
853 assert(isa<ConstantAggregateZero>(AVI.DstInit));
854 ArrayType *DstAT = cast<ArrayType>(AVI.DstInit->getType());
855 Type *EltTy = DstAT->getElementType();
856 Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy));
859 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
860 if (const ConstantArray *I = dyn_cast<ConstantArray>(SrcInit)) {
861 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
862 Elements.push_back(I->getOperand(i));
864 assert(isa<ConstantAggregateZero>(SrcInit));
865 ArrayType *SrcAT = cast<ArrayType>(SrcInit->getType());
866 Type *EltTy = SrcAT->getElementType();
867 Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy));
869 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
870 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
874 // linkGlobalInits - Update the initializers in the Dest module now that all
875 // globals that may be referenced are in Dest.
876 void ModuleLinker::linkGlobalInits() {
877 // Loop over all of the globals in the src module, mapping them over as we go
878 for (Module::const_global_iterator I = SrcM->global_begin(),
879 E = SrcM->global_end(); I != E; ++I) {
881 // Only process initialized GV's or ones not already in dest.
882 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
884 // Grab destination global variable.
885 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
886 // Figure out what the initializer looks like in the dest module.
887 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
892 // linkFunctionBody - Copy the source function over into the dest function and
893 // fix up references to values. At this point we know that Dest is an external
894 // function, and that Src is not.
895 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
896 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
898 // Go through and convert function arguments over, remembering the mapping.
899 Function::arg_iterator DI = Dst->arg_begin();
900 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
902 DI->setName(I->getName()); // Copy the name over.
904 // Add a mapping to our mapping.
908 if (Mode == Linker::DestroySource) {
909 // Splice the body of the source function into the dest function.
910 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
912 // At this point, all of the instructions and values of the function are now
913 // copied over. The only problem is that they are still referencing values in
914 // the Source function as operands. Loop through all of the operands of the
915 // functions and patch them up to point to the local versions.
916 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
917 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
918 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
921 // Clone the body of the function into the dest function.
922 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
923 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
926 // There is no need to map the arguments anymore.
927 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
934 void ModuleLinker::linkAliasBodies() {
935 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
937 if (DoNotLinkFromSource.count(I))
939 if (Constant *Aliasee = I->getAliasee()) {
940 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
941 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
946 /// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
948 void ModuleLinker::linkNamedMDNodes() {
949 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
950 E = SrcM->named_metadata_end(); I != E; ++I) {
951 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
952 // Add Src elements into Dest node.
953 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
954 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
959 bool ModuleLinker::run() {
960 assert(DstM && "Null Destination module");
961 assert(SrcM && "Null Source Module");
963 // Inherit the target data from the source module if the destination module
964 // doesn't have one already.
965 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
966 DstM->setDataLayout(SrcM->getDataLayout());
968 // Copy the target triple from the source to dest if the dest's is empty.
969 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
970 DstM->setTargetTriple(SrcM->getTargetTriple());
972 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
973 SrcM->getDataLayout() != DstM->getDataLayout())
974 errs() << "WARNING: Linking two modules of different data layouts!\n";
975 if (!SrcM->getTargetTriple().empty() &&
976 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
977 errs() << "WARNING: Linking two modules of different target triples: ";
978 if (!SrcM->getModuleIdentifier().empty())
979 errs() << SrcM->getModuleIdentifier() << ": ";
980 errs() << "'" << SrcM->getTargetTriple() << "' and '"
981 << DstM->getTargetTriple() << "'\n";
984 // Append the module inline asm string.
985 if (!SrcM->getModuleInlineAsm().empty()) {
986 if (DstM->getModuleInlineAsm().empty())
987 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
989 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
990 SrcM->getModuleInlineAsm());
993 // Update the destination module's dependent libraries list with the libraries
994 // from the source module. There's no opportunity for duplicates here as the
995 // Module ensures that duplicate insertions are discarded.
996 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
998 DstM->addLibrary(*SI);
1000 // If the source library's module id is in the dependent library list of the
1001 // destination library, remove it since that module is now linked in.
1002 StringRef ModuleId = SrcM->getModuleIdentifier();
1003 if (!ModuleId.empty())
1004 DstM->removeLibrary(sys::path::stem(ModuleId));
1006 // Loop over all of the linked values to compute type mappings.
1007 computeTypeMapping();
1009 // Insert all of the globals in src into the DstM module... without linking
1010 // initializers (which could refer to functions not yet mapped over).
1011 for (Module::global_iterator I = SrcM->global_begin(),
1012 E = SrcM->global_end(); I != E; ++I)
1013 if (linkGlobalProto(I))
1016 // Link the functions together between the two modules, without doing function
1017 // bodies... this just adds external function prototypes to the DstM
1018 // function... We do this so that when we begin processing function bodies,
1019 // all of the global values that may be referenced are available in our
1021 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1022 if (linkFunctionProto(I))
1025 // If there were any aliases, link them now.
1026 for (Module::alias_iterator I = SrcM->alias_begin(),
1027 E = SrcM->alias_end(); I != E; ++I)
1028 if (linkAliasProto(I))
1031 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1032 linkAppendingVarInit(AppendingVars[i]);
1034 // Update the initializers in the DstM module now that all globals that may
1035 // be referenced are in DstM.
1038 // Link in the function bodies that are defined in the source module into
1040 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1042 // Skip if not linking from source.
1043 if (DoNotLinkFromSource.count(SF)) continue;
1045 // Skip if no body (function is external) or materialize.
1046 if (SF->isDeclaration()) {
1047 if (!SF->isMaterializable())
1049 if (SF->Materialize(&ErrorMsg))
1053 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1056 // Resolve all uses of aliases with aliasees.
1059 // Remap all of the named mdnoes in Src into the DstM module. We do this
1060 // after linking GlobalValues so that MDNodes that reference GlobalValues
1061 // are properly remapped.
1064 // Process vector of lazily linked in functions.
1065 bool LinkedInAnyFunctions;
1067 LinkedInAnyFunctions = false;
1069 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1070 E = LazilyLinkFunctions.end(); I != E; ++I) {
1075 Function *DF = cast<Function>(ValueMap[SF]);
1077 if (!DF->use_empty()) {
1079 // Materialize if necessary.
1080 if (SF->isDeclaration()) {
1081 if (!SF->isMaterializable())
1083 if (SF->Materialize(&ErrorMsg))
1087 // Link in function body.
1088 linkFunctionBody(DF, SF);
1090 // "Remove" from vector by setting the element to 0.
1093 // Set flag to indicate we may have more functions to lazily link in
1094 // since we linked in a function.
1095 LinkedInAnyFunctions = true;
1098 } while (LinkedInAnyFunctions);
1100 // Remove any prototypes of functions that were not actually linked in.
1101 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1102 E = LazilyLinkFunctions.end(); I != E; ++I) {
1107 Function *DF = cast<Function>(ValueMap[SF]);
1108 if (DF->use_empty())
1109 DF->eraseFromParent();
1112 // Now that all of the types from the source are used, resolve any structs
1113 // copied over to the dest that didn't exist there.
1114 TypeMap.linkDefinedTypeBodies();
1119 //===----------------------------------------------------------------------===//
1120 // LinkModules entrypoint.
1121 //===----------------------------------------------------------------------===//
1123 // LinkModules - This function links two modules together, with the resulting
1124 // left module modified to be the composite of the two input modules. If an
1125 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1126 // the problem. Upon failure, the Dest module could be in a modified state, and
1127 // shouldn't be relied on to be consistent.
1128 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1129 std::string *ErrorMsg) {
1130 ModuleLinker TheLinker(Dest, Src, Mode);
1131 if (TheLinker.run()) {
1132 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;