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/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/TypeFinder.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
34 //===----------------------------------------------------------------------===//
35 // TypeMap implementation.
36 //===----------------------------------------------------------------------===//
39 typedef SmallPtrSet<StructType *, 32> TypeSet;
41 class TypeMapTy : public ValueMapTypeRemapper {
42 /// This is a mapping from a source type to a destination type to use.
43 DenseMap<Type*, Type*> MappedTypes;
45 /// When checking to see if two subgraphs are isomorphic, we speculatively
46 /// add types to MappedTypes, but keep track of them here in case we need to
48 SmallVector<Type*, 16> SpeculativeTypes;
50 /// This is a list of non-opaque structs in the source module that are mapped
51 /// to an opaque struct in the destination module.
52 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
54 /// This is the set of opaque types in the destination modules who are
55 /// getting a body from the source module.
56 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
59 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
61 TypeSet &DstStructTypesSet;
62 /// Indicate that the specified type in the destination module is conceptually
63 /// equivalent to the specified type in the source module.
64 void addTypeMapping(Type *DstTy, Type *SrcTy);
66 /// Produce a body for an opaque type in the dest module from a type
67 /// definition in the source module.
68 void linkDefinedTypeBodies();
70 /// Return the mapped type to use for the specified input type from the
72 Type *get(Type *SrcTy);
74 FunctionType *get(FunctionType *T) {
75 return cast<FunctionType>(get((Type *)T));
78 /// Dump out the type map for debugging purposes.
80 for (auto &Pair : MappedTypes) {
81 dbgs() << "TypeMap: ";
82 Pair.first->print(dbgs());
84 Pair.second->print(dbgs());
90 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 // Check to see if these types are recursively isomorphic and establish a
98 // mapping between them if so.
99 if (!areTypesIsomorphic(DstTy, SrcTy)) {
100 // Oops, they aren't isomorphic. Just discard this request by rolling out
101 // any speculative mappings we've established.
102 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
103 MappedTypes.erase(SpeculativeTypes[i]);
105 SpeculativeTypes.clear();
108 /// Recursively walk this pair of types, returning true if they are isomorphic,
109 /// false if they are not.
110 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
111 // Two types with differing kinds are clearly not isomorphic.
112 if (DstTy->getTypeID() != SrcTy->getTypeID())
115 // If we have an entry in the MappedTypes table, then we have our answer.
116 Type *&Entry = MappedTypes[SrcTy];
118 return Entry == DstTy;
120 // Two identical types are clearly isomorphic. Remember this
121 // non-speculatively.
122 if (DstTy == SrcTy) {
127 // Okay, we have two types with identical kinds that we haven't seen before.
129 // If this is an opaque struct type, special case it.
130 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
131 // Mapping an opaque type to any struct, just keep the dest struct.
132 if (SSTy->isOpaque()) {
134 SpeculativeTypes.push_back(SrcTy);
138 // Mapping a non-opaque source type to an opaque dest. If this is the first
139 // type that we're mapping onto this destination type then we succeed. Keep
140 // the dest, but fill it in later. This doesn't need to be speculative. If
141 // this is the second (different) type that we're trying to map onto the
142 // same opaque type then we fail.
143 if (cast<StructType>(DstTy)->isOpaque()) {
144 // We can only map one source type onto the opaque destination type.
145 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
147 SrcDefinitionsToResolve.push_back(SSTy);
153 // If the number of subtypes disagree between the two types, then we fail.
154 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
157 // Fail if any of the extra properties (e.g. array size) of the type disagree.
158 if (isa<IntegerType>(DstTy))
159 return false; // bitwidth disagrees.
160 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
161 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
164 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
165 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
167 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
168 StructType *SSTy = cast<StructType>(SrcTy);
169 if (DSTy->isLiteral() != SSTy->isLiteral() ||
170 DSTy->isPacked() != SSTy->isPacked())
172 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
173 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
175 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
176 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
180 // Otherwise, we speculate that these two types will line up and recursively
181 // check the subelements.
183 SpeculativeTypes.push_back(SrcTy);
185 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
186 if (!areTypesIsomorphic(DstTy->getContainedType(I),
187 SrcTy->getContainedType(I)))
190 // If everything seems to have lined up, then everything is great.
194 void TypeMapTy::linkDefinedTypeBodies() {
195 SmallVector<Type*, 16> Elements;
196 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
197 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
198 assert(DstSTy->isOpaque());
200 // Map the body of the source type over to a new body for the dest type.
201 Elements.resize(SrcSTy->getNumElements());
202 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
203 Elements[I] = get(SrcSTy->getElementType(I));
205 DstSTy->setBody(Elements, SrcSTy->isPacked());
207 SrcDefinitionsToResolve.clear();
208 DstResolvedOpaqueTypes.clear();
211 Type *TypeMapTy::get(Type *Ty) {
212 // If we already have an entry for this type, return it.
213 Type **Entry = &MappedTypes[Ty];
217 // If this is not a named struct type, then just map all of the elements and
218 // then rebuild the type from inside out.
219 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
220 // If there are no element types to map, then the type is itself. This is
221 // true for the anonymous {} struct, things like 'float', integers, etc.
222 if (Ty->getNumContainedTypes() == 0)
225 // Remap all of the elements, keeping track of whether any of them change.
226 bool AnyChange = false;
227 SmallVector<Type*, 4> ElementTypes;
228 ElementTypes.resize(Ty->getNumContainedTypes());
229 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
230 ElementTypes[I] = get(Ty->getContainedType(I));
231 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
234 // If we found our type while recursively processing stuff, just use it.
235 Entry = &MappedTypes[Ty];
239 // If all of the element types mapped directly over, then the type is usable
244 // Otherwise, rebuild a modified type.
245 switch (Ty->getTypeID()) {
247 llvm_unreachable("unknown derived type to remap");
248 case Type::ArrayTyID:
249 return *Entry = ArrayType::get(ElementTypes[0],
250 cast<ArrayType>(Ty)->getNumElements());
251 case Type::VectorTyID:
252 return *Entry = VectorType::get(ElementTypes[0],
253 cast<VectorType>(Ty)->getNumElements());
254 case Type::PointerTyID:
255 return *Entry = PointerType::get(
256 ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
257 case Type::FunctionTyID:
258 return *Entry = FunctionType::get(ElementTypes[0],
259 makeArrayRef(ElementTypes).slice(1),
260 cast<FunctionType>(Ty)->isVarArg());
261 case Type::StructTyID:
262 // Note that this is only reached for anonymous structs.
263 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
264 cast<StructType>(Ty)->isPacked());
268 // Otherwise, this is an unmapped named struct. If the struct can be directly
269 // mapped over, just use it as-is. This happens in a case when the linked-in
270 // module has something like:
271 // %T = type {%T*, i32}
272 // @GV = global %T* null
273 // where T does not exist at all in the destination module.
275 // The other case we watch for is when the type is not in the destination
276 // module, but that it has to be rebuilt because it refers to something that
277 // is already mapped. For example, if the destination module has:
279 // and the source module has something like
280 // %A' = type { i32 }
281 // %B = type { %A'* }
282 // @GV = global %B* null
283 // then we want to create a new type: "%B = type { %A*}" and have it take the
284 // pristine "%B" name from the source module.
286 // To determine which case this is, we have to recursively walk the type graph
287 // speculating that we'll be able to reuse it unmodified. Only if this is
288 // safe would we map the entire thing over. Because this is an optimization,
289 // and is not required for the prettiness of the linked module, we just skip
290 // it and always rebuild a type here.
291 StructType *STy = cast<StructType>(Ty);
293 // If the type is opaque, we can just use it directly.
294 if (STy->isOpaque()) {
295 // A named structure type from src module is used. Add it to the Set of
296 // identified structs in the destination module.
297 DstStructTypesSet.insert(STy);
301 // Otherwise we create a new type.
302 StructType *DTy = StructType::create(STy->getContext());
303 // A new identified structure type was created. Add it to the set of
304 // identified structs in the destination module.
305 DstStructTypesSet.insert(DTy);
308 SmallVector<Type*, 4> ElementTypes;
309 ElementTypes.resize(STy->getNumElements());
310 for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
311 ElementTypes[I] = get(STy->getElementType(I));
312 DTy->setBody(ElementTypes, STy->isPacked());
315 if (STy->hasName()) {
316 SmallString<16> TmpName = STy->getName();
318 DTy->setName(TmpName);
324 //===----------------------------------------------------------------------===//
325 // ModuleLinker implementation.
326 //===----------------------------------------------------------------------===//
331 /// Creates prototypes for functions that are lazily linked on the fly. This
332 /// speeds up linking for modules with many/ lazily linked functions of which
334 class ValueMaterializerTy : public ValueMaterializer {
337 std::vector<Function *> &LazilyLinkFunctions;
340 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
341 std::vector<Function *> &LazilyLinkFunctions)
342 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
343 LazilyLinkFunctions(LazilyLinkFunctions) {}
345 Value *materializeValueFor(Value *V) override;
348 class LinkDiagnosticInfo : public DiagnosticInfo {
352 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
353 void print(DiagnosticPrinter &DP) const override;
355 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
357 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
358 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
360 /// This is an implementation class for the LinkModules function, which is the
361 /// entrypoint for this file.
366 ValueMaterializerTy ValMaterializer;
368 /// Mapping of values from what they used to be in Src, to what they are now
369 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
370 /// due to the use of Value handles which the Linker doesn't actually need,
371 /// but this allows us to reuse the ValueMapper code.
372 ValueToValueMapTy ValueMap;
374 struct AppendingVarInfo {
375 GlobalVariable *NewGV; // New aggregate global in dest module.
376 const Constant *DstInit; // Old initializer from dest module.
377 const Constant *SrcInit; // Old initializer from src module.
380 std::vector<AppendingVarInfo> AppendingVars;
382 // Set of items not to link in from source.
383 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
385 // Vector of functions to lazily link in.
386 std::vector<Function *> LazilyLinkFunctions;
388 Linker::DiagnosticHandlerFunction DiagnosticHandler;
391 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
392 Linker::DiagnosticHandlerFunction DiagnosticHandler)
393 : DstM(dstM), SrcM(srcM), TypeMap(Set),
394 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
395 DiagnosticHandler(DiagnosticHandler) {}
400 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
401 const GlobalValue &Src);
403 /// Helper method for setting a message and returning an error code.
404 bool emitError(const Twine &Message) {
405 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
409 void emitWarning(const Twine &Message) {
410 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
413 bool getComdatLeader(Module *M, StringRef ComdatName,
414 const GlobalVariable *&GVar);
415 bool computeResultingSelectionKind(StringRef ComdatName,
416 Comdat::SelectionKind Src,
417 Comdat::SelectionKind Dst,
418 Comdat::SelectionKind &Result,
420 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
422 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
425 /// Given a global in the source module, return the global in the
426 /// destination module that is being linked to, if any.
427 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
428 // If the source has no name it can't link. If it has local linkage,
429 // there is no name match-up going on.
430 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
433 // Otherwise see if we have a match in the destination module's symtab.
434 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
438 // If we found a global with the same name in the dest module, but it has
439 // internal linkage, we are really not doing any linkage here.
440 if (DGV->hasLocalLinkage())
443 // Otherwise, we do in fact link to the destination global.
447 void computeTypeMapping();
449 void upgradeMismatchedGlobalArray(StringRef Name);
450 void upgradeMismatchedGlobals();
452 bool linkAppendingVarProto(GlobalVariable *DstGV,
453 const GlobalVariable *SrcGV);
455 bool linkGlobalValueProto(GlobalValue *GV);
456 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
457 GlobalValue *DGV, bool LinkFromSrc);
458 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
460 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
463 bool linkModuleFlagsMetadata();
465 void linkAppendingVarInit(const AppendingVarInfo &AVI);
466 void linkGlobalInits();
467 void linkFunctionBody(Function *Dst, Function *Src);
468 void linkAliasBodies();
469 void linkNamedMDNodes();
473 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
474 /// table. This is good for all clients except for us. Go through the trouble
475 /// to force this back.
476 static void forceRenaming(GlobalValue *GV, StringRef Name) {
477 // If the global doesn't force its name or if it already has the right name,
478 // there is nothing for us to do.
479 if (GV->hasLocalLinkage() || GV->getName() == Name)
482 Module *M = GV->getParent();
484 // If there is a conflict, rename the conflict.
485 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
486 GV->takeName(ConflictGV);
487 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
488 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
490 GV->setName(Name); // Force the name back
494 /// copy additional attributes (those not needed to construct a GlobalValue)
495 /// from the SrcGV to the DestGV.
496 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
497 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
498 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
501 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
503 DestGV->copyAttributesFrom(SrcGV);
506 DestGO->setAlignment(Alignment);
508 forceRenaming(DestGV, SrcGV->getName());
511 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
512 GlobalValue::VisibilityTypes b) {
513 if (a == GlobalValue::HiddenVisibility)
515 if (b == GlobalValue::HiddenVisibility)
517 if (a == GlobalValue::ProtectedVisibility)
519 if (b == GlobalValue::ProtectedVisibility)
524 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
525 Function *SF = dyn_cast<Function>(V);
529 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
530 SF->getLinkage(), SF->getName(), DstM);
531 copyGVAttributes(DF, SF);
533 if (Comdat *SC = SF->getComdat()) {
534 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
538 LazilyLinkFunctions.push_back(SF);
542 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
543 const GlobalVariable *&GVar) {
544 const GlobalValue *GVal = M->getNamedValue(ComdatName);
545 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
546 GVal = GA->getBaseObject();
548 // We cannot resolve the size of the aliasee yet.
549 return emitError("Linking COMDATs named '" + ComdatName +
550 "': COMDAT key involves incomputable alias size.");
553 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
556 "Linking COMDATs named '" + ComdatName +
557 "': GlobalVariable required for data dependent selection!");
562 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
563 Comdat::SelectionKind Src,
564 Comdat::SelectionKind Dst,
565 Comdat::SelectionKind &Result,
567 // The ability to mix Comdat::SelectionKind::Any with
568 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
569 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
570 Dst == Comdat::SelectionKind::Largest;
571 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
572 Src == Comdat::SelectionKind::Largest;
573 if (DstAnyOrLargest && SrcAnyOrLargest) {
574 if (Dst == Comdat::SelectionKind::Largest ||
575 Src == Comdat::SelectionKind::Largest)
576 Result = Comdat::SelectionKind::Largest;
578 Result = Comdat::SelectionKind::Any;
579 } else if (Src == Dst) {
582 return emitError("Linking COMDATs named '" + ComdatName +
583 "': invalid selection kinds!");
587 case Comdat::SelectionKind::Any:
591 case Comdat::SelectionKind::NoDuplicates:
592 return emitError("Linking COMDATs named '" + ComdatName +
593 "': noduplicates has been violated!");
594 case Comdat::SelectionKind::ExactMatch:
595 case Comdat::SelectionKind::Largest:
596 case Comdat::SelectionKind::SameSize: {
597 const GlobalVariable *DstGV;
598 const GlobalVariable *SrcGV;
599 if (getComdatLeader(DstM, ComdatName, DstGV) ||
600 getComdatLeader(SrcM, ComdatName, SrcGV))
603 const DataLayout *DstDL = DstM->getDataLayout();
604 const DataLayout *SrcDL = SrcM->getDataLayout();
605 if (!DstDL || !SrcDL) {
607 "Linking COMDATs named '" + ComdatName +
608 "': can't do size dependent selection without DataLayout!");
611 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
613 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
614 if (Result == Comdat::SelectionKind::ExactMatch) {
615 if (SrcGV->getInitializer() != DstGV->getInitializer())
616 return emitError("Linking COMDATs named '" + ComdatName +
617 "': ExactMatch violated!");
619 } else if (Result == Comdat::SelectionKind::Largest) {
620 LinkFromSrc = SrcSize > DstSize;
621 } else if (Result == Comdat::SelectionKind::SameSize) {
622 if (SrcSize != DstSize)
623 return emitError("Linking COMDATs named '" + ComdatName +
624 "': SameSize violated!");
627 llvm_unreachable("unknown selection kind");
636 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
637 Comdat::SelectionKind &Result,
639 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
640 StringRef ComdatName = SrcC->getName();
641 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
642 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
644 if (DstCI == ComdatSymTab.end()) {
645 // Use the comdat if it is only available in one of the modules.
651 const Comdat *DstC = &DstCI->second;
652 Comdat::SelectionKind DSK = DstC->getSelectionKind();
653 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
657 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
658 const GlobalValue &Dest,
659 const GlobalValue &Src) {
660 // We always have to add Src if it has appending linkage.
661 if (Src.hasAppendingLinkage()) {
666 bool SrcIsDeclaration = Src.isDeclarationForLinker();
667 bool DestIsDeclaration = Dest.isDeclarationForLinker();
669 if (SrcIsDeclaration) {
670 // If Src is external or if both Src & Dest are external.. Just link the
671 // external globals, we aren't adding anything.
672 if (Src.hasDLLImportStorageClass()) {
673 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
674 LinkFromSrc = DestIsDeclaration;
677 // If the Dest is weak, use the source linkage.
678 LinkFromSrc = Dest.hasExternalWeakLinkage();
682 if (DestIsDeclaration) {
683 // If Dest is external but Src is not:
688 if (Src.hasCommonLinkage()) {
689 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
694 if (!Dest.hasCommonLinkage()) {
699 // FIXME: Make datalayout mandatory and just use getDataLayout().
700 DataLayout DL(Dest.getParent());
702 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
703 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
704 LinkFromSrc = SrcSize > DestSize;
708 if (Src.isWeakForLinker()) {
709 assert(!Dest.hasExternalWeakLinkage());
710 assert(!Dest.hasAvailableExternallyLinkage());
712 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
721 if (Dest.isWeakForLinker()) {
722 assert(Src.hasExternalLinkage());
727 assert(!Src.hasExternalWeakLinkage());
728 assert(!Dest.hasExternalWeakLinkage());
729 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
730 "Unexpected linkage type!");
731 return emitError("Linking globals named '" + Src.getName() +
732 "': symbol multiply defined!");
735 /// Loop over all of the linked values to compute type mappings. For example,
736 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
737 /// types 'Foo' but one got renamed when the module was loaded into the same
739 void ModuleLinker::computeTypeMapping() {
740 for (GlobalValue &SGV : SrcM->globals()) {
741 GlobalValue *DGV = getLinkedToGlobal(&SGV);
745 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
746 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
750 // Unify the element type of appending arrays.
751 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
752 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
753 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
756 for (GlobalValue &SGV : *SrcM) {
757 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
758 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
761 for (GlobalValue &SGV : SrcM->aliases()) {
762 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
763 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
766 // Incorporate types by name, scanning all the types in the source module.
767 // At this point, the destination module may have a type "%foo = { i32 }" for
768 // example. When the source module got loaded into the same LLVMContext, if
769 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
770 TypeFinder SrcStructTypes;
771 SrcStructTypes.run(*SrcM, true);
772 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
773 SrcStructTypes.end());
775 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
776 StructType *ST = SrcStructTypes[i];
777 if (!ST->hasName()) continue;
779 // Check to see if there is a dot in the name followed by a digit.
780 size_t DotPos = ST->getName().rfind('.');
781 if (DotPos == 0 || DotPos == StringRef::npos ||
782 ST->getName().back() == '.' ||
783 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
786 // Check to see if the destination module has a struct with the prefix name.
787 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
788 // Don't use it if this actually came from the source module. They're in
789 // the same LLVMContext after all. Also don't use it unless the type is
790 // actually used in the destination module. This can happen in situations
795 // %Z = type { %A } %B = type { %C.1 }
796 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
797 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
798 // %C = type { i8* } %B.3 = type { %C.1 }
800 // When we link Module B with Module A, the '%B' in Module B is
801 // used. However, that would then use '%C.1'. But when we process '%C.1',
802 // we prefer to take the '%C' version. So we are then left with both
803 // '%C.1' and '%C' being used for the same types. This leads to some
804 // variables using one type and some using the other.
805 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
806 TypeMap.addTypeMapping(DST, ST);
809 // Now that we have discovered all of the type equivalences, get a body for
810 // any 'opaque' types in the dest module that are now resolved.
811 TypeMap.linkDefinedTypeBodies();
814 static void upgradeGlobalArray(GlobalVariable *GV) {
815 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
816 StructType *OldTy = cast<StructType>(ATy->getElementType());
817 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
819 // Get the upgraded 3 element type.
820 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
821 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
823 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
825 // Build new constants with a null third field filled in.
826 Constant *OldInitC = GV->getInitializer();
827 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
828 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
829 // Invalid initializer; give up.
831 std::vector<Constant *> Initializers;
832 if (OldInit && OldInit->getNumOperands()) {
833 Value *Null = Constant::getNullValue(VoidPtrTy);
834 for (Use &U : OldInit->operands()) {
835 ConstantStruct *Init = cast<ConstantStruct>(U.get());
836 Initializers.push_back(ConstantStruct::get(
837 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
840 assert(Initializers.size() == ATy->getNumElements() &&
841 "Failed to copy all array elements");
843 // Replace the old GV with a new one.
844 ATy = ArrayType::get(NewTy, Initializers.size());
845 Constant *NewInit = ConstantArray::get(ATy, Initializers);
846 GlobalVariable *NewGV = new GlobalVariable(
847 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
848 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
849 GV->isExternallyInitialized());
850 NewGV->copyAttributesFrom(GV);
852 assert(GV->use_empty() && "program cannot use initializer list");
853 GV->eraseFromParent();
856 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
857 // Look for the global arrays.
858 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
861 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
865 // Check if the types already match.
866 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
868 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
872 // Grab the element types. We can only upgrade an array of a two-field
873 // struct. Only bother if the other one has three-fields.
874 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
875 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
876 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
877 upgradeGlobalArray(DstGV);
880 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
881 upgradeGlobalArray(SrcGV);
883 // We can't upgrade any other differences.
886 void ModuleLinker::upgradeMismatchedGlobals() {
887 upgradeMismatchedGlobalArray("llvm.global_ctors");
888 upgradeMismatchedGlobalArray("llvm.global_dtors");
891 /// If there were any appending global variables, link them together now.
892 /// Return true on error.
893 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
894 const GlobalVariable *SrcGV) {
896 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
897 return emitError("Linking globals named '" + SrcGV->getName() +
898 "': can only link appending global with another appending global!");
900 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
902 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
903 Type *EltTy = DstTy->getElementType();
905 // Check to see that they two arrays agree on type.
906 if (EltTy != SrcTy->getElementType())
907 return emitError("Appending variables with different element types!");
908 if (DstGV->isConstant() != SrcGV->isConstant())
909 return emitError("Appending variables linked with different const'ness!");
911 if (DstGV->getAlignment() != SrcGV->getAlignment())
913 "Appending variables with different alignment need to be linked!");
915 if (DstGV->getVisibility() != SrcGV->getVisibility())
917 "Appending variables with different visibility need to be linked!");
919 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
921 "Appending variables with different unnamed_addr need to be linked!");
923 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
925 "Appending variables with different section name need to be linked!");
927 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
928 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
930 // Create the new global variable.
932 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
933 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
934 DstGV->getThreadLocalMode(),
935 DstGV->getType()->getAddressSpace());
937 // Propagate alignment, visibility and section info.
938 copyGVAttributes(NG, DstGV);
940 AppendingVarInfo AVI;
942 AVI.DstInit = DstGV->getInitializer();
943 AVI.SrcInit = SrcGV->getInitializer();
944 AppendingVars.push_back(AVI);
946 // Replace any uses of the two global variables with uses of the new
948 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
950 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
951 DstGV->eraseFromParent();
953 // Track the source variable so we don't try to link it.
954 DoNotLinkFromSource.insert(SrcGV);
959 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
960 GlobalValue *DGV = getLinkedToGlobal(SGV);
962 // Handle the ultra special appending linkage case first.
963 if (DGV && DGV->hasAppendingLinkage())
964 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
965 cast<GlobalVariable>(SGV));
967 bool LinkFromSrc = true;
969 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
970 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
972 if (const Comdat *SC = SGV->getComdat()) {
973 Comdat::SelectionKind SK;
974 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
975 C = DstM->getOrInsertComdat(SC->getName());
976 C->setSelectionKind(SK);
978 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
983 // Track the source global so that we don't attempt to copy it over when
984 // processing global initializers.
985 DoNotLinkFromSource.insert(SGV);
988 // Make sure to remember this mapping.
990 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
994 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
995 ? DGV->getVisibility()
997 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1000 if (!LinkFromSrc && !DGV)
1004 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1005 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1008 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1009 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1011 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1016 copyGVAttributes(NewGV, SGV);
1018 NewGV->setUnnamedAddr(HasUnnamedAddr);
1019 NewGV->setVisibility(Visibility);
1021 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1023 NewGO->setComdat(C);
1026 // Make sure to remember this mapping.
1029 DGV->replaceAllUsesWith(
1030 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1031 DGV->eraseFromParent();
1033 ValueMap[SGV] = NewGV;
1040 /// Loop through the global variables in the src module and merge them into the
1042 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1045 unsigned Alignment = 0;
1046 bool ClearConstant = false;
1049 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1050 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1052 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1053 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1054 ClearConstant = true;
1058 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1060 NewGVar->setAlignment(Alignment);
1061 if (NewGVar->isDeclaration() && ClearConstant)
1062 NewGVar->setConstant(false);
1067 // No linking to be performed or linking from the source: simply create an
1068 // identical version of the symbol over in the dest module... the
1069 // initializer will be filled in later by LinkGlobalInits.
1070 GlobalVariable *NewDGV = new GlobalVariable(
1071 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1072 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1073 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1074 SGVar->getType()->getAddressSpace());
1077 NewDGV->setAlignment(Alignment);
1082 /// Link the function in the source module into the destination module if
1083 /// needed, setting up mapping information.
1084 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1090 // If the function is to be lazily linked, don't create it just yet.
1091 // The ValueMaterializerTy will deal with creating it if it's used.
1092 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1093 SF->hasAvailableExternallyLinkage())) {
1094 DoNotLinkFromSource.insert(SF);
1098 // If there is no linkage to be performed or we are linking from the source,
1100 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1101 SF->getName(), DstM);
1104 /// Set up prototypes for any aliases that come over from the source module.
1105 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1111 // If there is no linkage to be performed or we're linking from the source,
1113 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1114 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1115 SGA->getLinkage(), SGA->getName(), DstM);
1118 static void getArrayElements(const Constant *C,
1119 SmallVectorImpl<Constant *> &Dest) {
1120 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1122 for (unsigned i = 0; i != NumElements; ++i)
1123 Dest.push_back(C->getAggregateElement(i));
1126 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1127 // Merge the initializer.
1128 SmallVector<Constant *, 16> DstElements;
1129 getArrayElements(AVI.DstInit, DstElements);
1131 SmallVector<Constant *, 16> SrcElements;
1132 getArrayElements(AVI.SrcInit, SrcElements);
1134 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1136 StringRef Name = AVI.NewGV->getName();
1137 bool IsNewStructor =
1138 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1139 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1141 for (auto *V : SrcElements) {
1142 if (IsNewStructor) {
1143 Constant *Key = V->getAggregateElement(2);
1144 if (DoNotLinkFromSource.count(Key))
1147 DstElements.push_back(
1148 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1150 if (IsNewStructor) {
1151 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1152 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1155 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1158 /// Update the initializers in the Dest module now that all globals that may be
1159 /// referenced are in Dest.
1160 void ModuleLinker::linkGlobalInits() {
1161 // Loop over all of the globals in the src module, mapping them over as we go
1162 for (Module::const_global_iterator I = SrcM->global_begin(),
1163 E = SrcM->global_end(); I != E; ++I) {
1165 // Only process initialized GV's or ones not already in dest.
1166 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1168 // Grab destination global variable.
1169 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1170 // Figure out what the initializer looks like in the dest module.
1171 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1172 RF_None, &TypeMap, &ValMaterializer));
1176 /// Copy the source function over into the dest function and fix up references
1177 /// to values. At this point we know that Dest is an external function, and
1178 /// that Src is not.
1179 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1180 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1182 // Go through and convert function arguments over, remembering the mapping.
1183 Function::arg_iterator DI = Dst->arg_begin();
1184 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1185 I != E; ++I, ++DI) {
1186 DI->setName(I->getName()); // Copy the name over.
1188 // Add a mapping to our mapping.
1192 // Splice the body of the source function into the dest function.
1193 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1195 // At this point, all of the instructions and values of the function are now
1196 // copied over. The only problem is that they are still referencing values in
1197 // the Source function as operands. Loop through all of the operands of the
1198 // functions and patch them up to point to the local versions.
1199 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1200 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1201 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1204 // There is no need to map the arguments anymore.
1205 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1211 /// Insert all of the aliases in Src into the Dest module.
1212 void ModuleLinker::linkAliasBodies() {
1213 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1215 if (DoNotLinkFromSource.count(I))
1217 if (Constant *Aliasee = I->getAliasee()) {
1218 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1220 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1221 DA->setAliasee(Val);
1226 /// Insert all of the named MDNodes in Src into the Dest module.
1227 void ModuleLinker::linkNamedMDNodes() {
1228 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1229 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1230 E = SrcM->named_metadata_end(); I != E; ++I) {
1231 // Don't link module flags here. Do them separately.
1232 if (&*I == SrcModFlags) continue;
1233 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1234 // Add Src elements into Dest node.
1235 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1236 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1237 RF_None, &TypeMap, &ValMaterializer));
1241 /// Merge the linker flags in Src into the Dest module.
1242 bool ModuleLinker::linkModuleFlagsMetadata() {
1243 // If the source module has no module flags, we are done.
1244 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1245 if (!SrcModFlags) return false;
1247 // If the destination module doesn't have module flags yet, then just copy
1248 // over the source module's flags.
1249 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1250 if (DstModFlags->getNumOperands() == 0) {
1251 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1252 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1257 // First build a map of the existing module flags and requirements.
1258 DenseMap<MDString*, MDNode*> Flags;
1259 SmallSetVector<MDNode*, 16> Requirements;
1260 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1261 MDNode *Op = DstModFlags->getOperand(I);
1262 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1263 MDString *ID = cast<MDString>(Op->getOperand(1));
1265 if (Behavior->getZExtValue() == Module::Require) {
1266 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1272 // Merge in the flags from the source module, and also collect its set of
1274 bool HasErr = false;
1275 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1276 MDNode *SrcOp = SrcModFlags->getOperand(I);
1277 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1278 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1279 MDNode *DstOp = Flags.lookup(ID);
1280 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1282 // If this is a requirement, add it and continue.
1283 if (SrcBehaviorValue == Module::Require) {
1284 // If the destination module does not already have this requirement, add
1286 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1287 DstModFlags->addOperand(SrcOp);
1292 // If there is no existing flag with this ID, just add it.
1295 DstModFlags->addOperand(SrcOp);
1299 // Otherwise, perform a merge.
1300 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1301 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1303 // If either flag has override behavior, handle it first.
1304 if (DstBehaviorValue == Module::Override) {
1305 // Diagnose inconsistent flags which both have override behavior.
1306 if (SrcBehaviorValue == Module::Override &&
1307 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1308 HasErr |= emitError("linking module flags '" + ID->getString() +
1309 "': IDs have conflicting override values");
1312 } else if (SrcBehaviorValue == Module::Override) {
1313 // Update the destination flag to that of the source.
1314 DstOp->replaceOperandWith(0, SrcBehavior);
1315 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1319 // Diagnose inconsistent merge behavior types.
1320 if (SrcBehaviorValue != DstBehaviorValue) {
1321 HasErr |= emitError("linking module flags '" + ID->getString() +
1322 "': IDs have conflicting behaviors");
1326 // Perform the merge for standard behavior types.
1327 switch (SrcBehaviorValue) {
1328 case Module::Require:
1329 case Module::Override: llvm_unreachable("not possible");
1330 case Module::Error: {
1331 // Emit an error if the values differ.
1332 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1333 HasErr |= emitError("linking module flags '" + ID->getString() +
1334 "': IDs have conflicting values");
1338 case Module::Warning: {
1339 // Emit a warning if the values differ.
1340 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1341 emitWarning("linking module flags '" + ID->getString() +
1342 "': IDs have conflicting values");
1346 case Module::Append: {
1347 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1348 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1349 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1350 Value **VP, **Values = VP = new Value*[NumOps];
1351 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1352 *VP = DstValue->getOperand(i);
1353 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1354 *VP = SrcValue->getOperand(i);
1355 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1356 ArrayRef<Value*>(Values,
1361 case Module::AppendUnique: {
1362 SmallSetVector<Value*, 16> Elts;
1363 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1364 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1365 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1366 Elts.insert(DstValue->getOperand(i));
1367 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1368 Elts.insert(SrcValue->getOperand(i));
1369 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1370 ArrayRef<Value*>(Elts.begin(),
1377 // Check all of the requirements.
1378 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1379 MDNode *Requirement = Requirements[I];
1380 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1381 Value *ReqValue = Requirement->getOperand(1);
1383 MDNode *Op = Flags[Flag];
1384 if (!Op || Op->getOperand(2) != ReqValue) {
1385 HasErr |= emitError("linking module flags '" + Flag->getString() +
1386 "': does not have the required value");
1394 bool ModuleLinker::run() {
1395 assert(DstM && "Null destination module");
1396 assert(SrcM && "Null source module");
1398 // Inherit the target data from the source module if the destination module
1399 // doesn't have one already.
1400 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1401 DstM->setDataLayout(SrcM->getDataLayout());
1403 // Copy the target triple from the source to dest if the dest's is empty.
1404 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1405 DstM->setTargetTriple(SrcM->getTargetTriple());
1407 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1408 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1409 emitWarning("Linking two modules of different data layouts: '" +
1410 SrcM->getModuleIdentifier() + "' is '" +
1411 SrcM->getDataLayoutStr() + "' whereas '" +
1412 DstM->getModuleIdentifier() + "' is '" +
1413 DstM->getDataLayoutStr() + "'\n");
1415 if (!SrcM->getTargetTriple().empty() &&
1416 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1417 emitWarning("Linking two modules of different target triples: " +
1418 SrcM->getModuleIdentifier() + "' is '" +
1419 SrcM->getTargetTriple() + "' whereas '" +
1420 DstM->getModuleIdentifier() + "' is '" +
1421 DstM->getTargetTriple() + "'\n");
1424 // Append the module inline asm string.
1425 if (!SrcM->getModuleInlineAsm().empty()) {
1426 if (DstM->getModuleInlineAsm().empty())
1427 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1429 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1430 SrcM->getModuleInlineAsm());
1433 // Loop over all of the linked values to compute type mappings.
1434 computeTypeMapping();
1436 ComdatsChosen.clear();
1437 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1438 const Comdat &C = SMEC.getValue();
1439 if (ComdatsChosen.count(&C))
1441 Comdat::SelectionKind SK;
1443 if (getComdatResult(&C, SK, LinkFromSrc))
1445 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1448 // Upgrade mismatched global arrays.
1449 upgradeMismatchedGlobals();
1451 // Insert all of the globals in src into the DstM module... without linking
1452 // initializers (which could refer to functions not yet mapped over).
1453 for (Module::global_iterator I = SrcM->global_begin(),
1454 E = SrcM->global_end(); I != E; ++I)
1455 if (linkGlobalValueProto(I))
1458 // Link the functions together between the two modules, without doing function
1459 // bodies... this just adds external function prototypes to the DstM
1460 // function... We do this so that when we begin processing function bodies,
1461 // all of the global values that may be referenced are available in our
1463 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1464 if (linkGlobalValueProto(I))
1467 // If there were any aliases, link them now.
1468 for (Module::alias_iterator I = SrcM->alias_begin(),
1469 E = SrcM->alias_end(); I != E; ++I)
1470 if (linkGlobalValueProto(I))
1473 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1474 linkAppendingVarInit(AppendingVars[i]);
1476 // Link in the function bodies that are defined in the source module into
1478 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1479 // Skip if not linking from source.
1480 if (DoNotLinkFromSource.count(SF)) continue;
1482 Function *DF = cast<Function>(ValueMap[SF]);
1483 if (SF->hasPrefixData()) {
1484 // Link in the prefix data.
1485 DF->setPrefixData(MapValue(
1486 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1489 // Materialize if needed.
1490 if (std::error_code EC = SF->materialize())
1491 return emitError(EC.message());
1493 // Skip if no body (function is external).
1494 if (SF->isDeclaration())
1497 linkFunctionBody(DF, SF);
1498 SF->Dematerialize();
1501 // Resolve all uses of aliases with aliasees.
1504 // Remap all of the named MDNodes in Src into the DstM module. We do this
1505 // after linking GlobalValues so that MDNodes that reference GlobalValues
1506 // are properly remapped.
1509 // Merge the module flags into the DstM module.
1510 if (linkModuleFlagsMetadata())
1513 // Update the initializers in the DstM module now that all globals that may
1514 // be referenced are in DstM.
1517 // Process vector of lazily linked in functions.
1518 bool LinkedInAnyFunctions;
1520 LinkedInAnyFunctions = false;
1522 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1523 E = LazilyLinkFunctions.end(); I != E; ++I) {
1528 Function *DF = cast<Function>(ValueMap[SF]);
1529 if (SF->hasPrefixData()) {
1530 // Link in the prefix data.
1531 DF->setPrefixData(MapValue(SF->getPrefixData(),
1538 // Materialize if needed.
1539 if (std::error_code EC = SF->materialize())
1540 return emitError(EC.message());
1542 // Skip if no body (function is external).
1543 if (SF->isDeclaration())
1546 // Erase from vector *before* the function body is linked - linkFunctionBody could
1548 LazilyLinkFunctions.erase(I);
1550 // Link in function body.
1551 linkFunctionBody(DF, SF);
1552 SF->Dematerialize();
1554 // Set flag to indicate we may have more functions to lazily link in
1555 // since we linked in a function.
1556 LinkedInAnyFunctions = true;
1559 } while (LinkedInAnyFunctions);
1564 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1565 this->Composite = M;
1566 this->DiagnosticHandler = DiagnosticHandler;
1568 TypeFinder StructTypes;
1569 StructTypes.run(*M, true);
1570 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1573 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1574 init(M, DiagnosticHandler);
1577 Linker::Linker(Module *M) {
1578 init(M, [this](const DiagnosticInfo &DI) {
1579 Composite->getContext().diagnose(DI);
1586 void Linker::deleteModule() {
1588 Composite = nullptr;
1591 bool Linker::linkInModule(Module *Src) {
1592 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1594 return TheLinker.run();
1597 //===----------------------------------------------------------------------===//
1598 // LinkModules entrypoint.
1599 //===----------------------------------------------------------------------===//
1601 /// This function links two modules together, with the resulting Dest module
1602 /// modified to be the composite of the two input modules. If an error occurs,
1603 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1604 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1605 /// relied on to be consistent.
1606 bool Linker::LinkModules(Module *Dest, Module *Src,
1607 DiagnosticHandlerFunction DiagnosticHandler) {
1608 Linker L(Dest, DiagnosticHandler);
1609 return L.linkInModule(Src);
1612 bool Linker::LinkModules(Module *Dest, Module *Src) {
1614 return L.linkInModule(Src);
1617 //===----------------------------------------------------------------------===//
1619 //===----------------------------------------------------------------------===//
1621 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1622 LLVMLinkerMode Mode, char **OutMessages) {
1623 Module *D = unwrap(Dest);
1624 std::string Message;
1625 raw_string_ostream Stream(Message);
1626 DiagnosticPrinterRawOStream DP(Stream);
1628 LLVMBool Result = Linker::LinkModules(
1629 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1631 if (OutMessages && Result)
1632 *OutMessages = strdup(Message.c_str());