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 assert(SpeculativeTypes.empty());
99 // Check to see if these types are recursively isomorphic and establish a
100 // mapping between them if so.
101 if (!areTypesIsomorphic(DstTy, SrcTy)) {
102 // Oops, they aren't isomorphic. Just discard this request by rolling out
103 // any speculative mappings we've established.
104 for (Type *Ty : SpeculativeTypes)
105 MappedTypes.erase(Ty);
107 SpeculativeTypes.clear();
110 /// Recursively walk this pair of types, returning true if they are isomorphic,
111 /// false if they are not.
112 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
113 // Two types with differing kinds are clearly not isomorphic.
114 if (DstTy->getTypeID() != SrcTy->getTypeID())
117 // If we have an entry in the MappedTypes table, then we have our answer.
118 Type *&Entry = MappedTypes[SrcTy];
120 return Entry == DstTy;
122 // Two identical types are clearly isomorphic. Remember this
123 // non-speculatively.
124 if (DstTy == SrcTy) {
129 // Okay, we have two types with identical kinds that we haven't seen before.
131 // If this is an opaque struct type, special case it.
132 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
133 // Mapping an opaque type to any struct, just keep the dest struct.
134 if (SSTy->isOpaque()) {
136 SpeculativeTypes.push_back(SrcTy);
140 // Mapping a non-opaque source type to an opaque dest. If this is the first
141 // type that we're mapping onto this destination type then we succeed. Keep
142 // the dest, but fill it in later. This doesn't need to be speculative. If
143 // this is the second (different) type that we're trying to map onto the
144 // same opaque type then we fail.
145 if (cast<StructType>(DstTy)->isOpaque()) {
146 // We can only map one source type onto the opaque destination type.
147 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
149 SrcDefinitionsToResolve.push_back(SSTy);
155 // If the number of subtypes disagree between the two types, then we fail.
156 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
159 // Fail if any of the extra properties (e.g. array size) of the type disagree.
160 if (isa<IntegerType>(DstTy))
161 return false; // bitwidth disagrees.
162 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
163 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
166 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
167 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
169 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
170 StructType *SSTy = cast<StructType>(SrcTy);
171 if (DSTy->isLiteral() != SSTy->isLiteral() ||
172 DSTy->isPacked() != SSTy->isPacked())
174 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
175 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
177 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
178 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
182 // Otherwise, we speculate that these two types will line up and recursively
183 // check the subelements.
185 SpeculativeTypes.push_back(SrcTy);
187 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
188 if (!areTypesIsomorphic(DstTy->getContainedType(I),
189 SrcTy->getContainedType(I)))
192 // If everything seems to have lined up, then everything is great.
196 void TypeMapTy::linkDefinedTypeBodies() {
197 SmallVector<Type*, 16> Elements;
198 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
199 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
200 assert(DstSTy->isOpaque());
202 // Map the body of the source type over to a new body for the dest type.
203 Elements.resize(SrcSTy->getNumElements());
204 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
205 Elements[I] = get(SrcSTy->getElementType(I));
207 DstSTy->setBody(Elements, SrcSTy->isPacked());
209 SrcDefinitionsToResolve.clear();
210 DstResolvedOpaqueTypes.clear();
213 Type *TypeMapTy::get(Type *Ty) {
214 // If we already have an entry for this type, return it.
215 Type **Entry = &MappedTypes[Ty];
219 // If this is not a named struct type, then just map all of the elements and
220 // then rebuild the type from inside out.
221 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
222 // If there are no element types to map, then the type is itself. This is
223 // true for the anonymous {} struct, things like 'float', integers, etc.
224 if (Ty->getNumContainedTypes() == 0)
227 // Remap all of the elements, keeping track of whether any of them change.
228 bool AnyChange = false;
229 SmallVector<Type*, 4> ElementTypes;
230 ElementTypes.resize(Ty->getNumContainedTypes());
231 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
232 ElementTypes[I] = get(Ty->getContainedType(I));
233 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
236 // If we found our type while recursively processing stuff, just use it.
237 Entry = &MappedTypes[Ty];
241 // If all of the element types mapped directly over, then the type is usable
246 // Otherwise, rebuild a modified type.
247 switch (Ty->getTypeID()) {
249 llvm_unreachable("unknown derived type to remap");
250 case Type::ArrayTyID:
251 return *Entry = ArrayType::get(ElementTypes[0],
252 cast<ArrayType>(Ty)->getNumElements());
253 case Type::VectorTyID:
254 return *Entry = VectorType::get(ElementTypes[0],
255 cast<VectorType>(Ty)->getNumElements());
256 case Type::PointerTyID:
257 return *Entry = PointerType::get(
258 ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace());
259 case Type::FunctionTyID:
260 return *Entry = FunctionType::get(ElementTypes[0],
261 makeArrayRef(ElementTypes).slice(1),
262 cast<FunctionType>(Ty)->isVarArg());
263 case Type::StructTyID:
264 // Note that this is only reached for anonymous structs.
265 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
266 cast<StructType>(Ty)->isPacked());
270 // Otherwise, this is an unmapped named struct. If the struct can be directly
271 // mapped over, just use it as-is. This happens in a case when the linked-in
272 // module has something like:
273 // %T = type {%T*, i32}
274 // @GV = global %T* null
275 // where T does not exist at all in the destination module.
277 // The other case we watch for is when the type is not in the destination
278 // module, but that it has to be rebuilt because it refers to something that
279 // is already mapped. For example, if the destination module has:
281 // and the source module has something like
282 // %A' = type { i32 }
283 // %B = type { %A'* }
284 // @GV = global %B* null
285 // then we want to create a new type: "%B = type { %A*}" and have it take the
286 // pristine "%B" name from the source module.
288 // To determine which case this is, we have to recursively walk the type graph
289 // speculating that we'll be able to reuse it unmodified. Only if this is
290 // safe would we map the entire thing over. Because this is an optimization,
291 // and is not required for the prettiness of the linked module, we just skip
292 // it and always rebuild a type here.
293 StructType *STy = cast<StructType>(Ty);
295 // If the type is opaque, we can just use it directly.
296 if (STy->isOpaque()) {
297 // A named structure type from src module is used. Add it to the Set of
298 // identified structs in the destination module.
299 DstStructTypesSet.insert(STy);
303 // Otherwise we create a new type.
304 StructType *DTy = StructType::create(STy->getContext());
305 // A new identified structure type was created. Add it to the set of
306 // identified structs in the destination module.
307 DstStructTypesSet.insert(DTy);
310 SmallVector<Type*, 4> ElementTypes;
311 ElementTypes.resize(STy->getNumElements());
312 for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I)
313 ElementTypes[I] = get(STy->getElementType(I));
314 DTy->setBody(ElementTypes, STy->isPacked());
317 if (STy->hasName()) {
318 SmallString<16> TmpName = STy->getName();
320 DTy->setName(TmpName);
326 //===----------------------------------------------------------------------===//
327 // ModuleLinker implementation.
328 //===----------------------------------------------------------------------===//
333 /// Creates prototypes for functions that are lazily linked on the fly. This
334 /// speeds up linking for modules with many/ lazily linked functions of which
336 class ValueMaterializerTy : public ValueMaterializer {
339 std::vector<Function *> &LazilyLinkFunctions;
342 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
343 std::vector<Function *> &LazilyLinkFunctions)
344 : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
345 LazilyLinkFunctions(LazilyLinkFunctions) {}
347 Value *materializeValueFor(Value *V) override;
350 class LinkDiagnosticInfo : public DiagnosticInfo {
354 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
355 void print(DiagnosticPrinter &DP) const override;
357 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
359 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
360 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
362 /// This is an implementation class for the LinkModules function, which is the
363 /// entrypoint for this file.
368 ValueMaterializerTy ValMaterializer;
370 /// Mapping of values from what they used to be in Src, to what they are now
371 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
372 /// due to the use of Value handles which the Linker doesn't actually need,
373 /// but this allows us to reuse the ValueMapper code.
374 ValueToValueMapTy ValueMap;
376 struct AppendingVarInfo {
377 GlobalVariable *NewGV; // New aggregate global in dest module.
378 const Constant *DstInit; // Old initializer from dest module.
379 const Constant *SrcInit; // Old initializer from src module.
382 std::vector<AppendingVarInfo> AppendingVars;
384 // Set of items not to link in from source.
385 SmallPtrSet<const Value *, 16> DoNotLinkFromSource;
387 // Vector of functions to lazily link in.
388 std::vector<Function *> LazilyLinkFunctions;
390 Linker::DiagnosticHandlerFunction DiagnosticHandler;
393 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
394 Linker::DiagnosticHandlerFunction DiagnosticHandler)
395 : DstM(dstM), SrcM(srcM), TypeMap(Set),
396 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
397 DiagnosticHandler(DiagnosticHandler) {}
402 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
403 const GlobalValue &Src);
405 /// Helper method for setting a message and returning an error code.
406 bool emitError(const Twine &Message) {
407 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
411 void emitWarning(const Twine &Message) {
412 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
415 bool getComdatLeader(Module *M, StringRef ComdatName,
416 const GlobalVariable *&GVar);
417 bool computeResultingSelectionKind(StringRef ComdatName,
418 Comdat::SelectionKind Src,
419 Comdat::SelectionKind Dst,
420 Comdat::SelectionKind &Result,
422 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
424 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
427 /// Given a global in the source module, return the global in the
428 /// destination module that is being linked to, if any.
429 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
430 // If the source has no name it can't link. If it has local linkage,
431 // there is no name match-up going on.
432 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
435 // Otherwise see if we have a match in the destination module's symtab.
436 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
440 // If we found a global with the same name in the dest module, but it has
441 // internal linkage, we are really not doing any linkage here.
442 if (DGV->hasLocalLinkage())
445 // Otherwise, we do in fact link to the destination global.
449 void computeTypeMapping();
451 void upgradeMismatchedGlobalArray(StringRef Name);
452 void upgradeMismatchedGlobals();
454 bool linkAppendingVarProto(GlobalVariable *DstGV,
455 const GlobalVariable *SrcGV);
457 bool linkGlobalValueProto(GlobalValue *GV);
458 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
459 GlobalValue *DGV, bool LinkFromSrc);
460 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
462 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
465 bool linkModuleFlagsMetadata();
467 void linkAppendingVarInit(const AppendingVarInfo &AVI);
468 void linkGlobalInits();
469 void linkFunctionBody(Function *Dst, Function *Src);
470 void linkAliasBodies();
471 void linkNamedMDNodes();
475 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
476 /// table. This is good for all clients except for us. Go through the trouble
477 /// to force this back.
478 static void forceRenaming(GlobalValue *GV, StringRef Name) {
479 // If the global doesn't force its name or if it already has the right name,
480 // there is nothing for us to do.
481 if (GV->hasLocalLinkage() || GV->getName() == Name)
484 Module *M = GV->getParent();
486 // If there is a conflict, rename the conflict.
487 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
488 GV->takeName(ConflictGV);
489 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
490 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
492 GV->setName(Name); // Force the name back
496 /// copy additional attributes (those not needed to construct a GlobalValue)
497 /// from the SrcGV to the DestGV.
498 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
499 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
500 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
503 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
505 DestGV->copyAttributesFrom(SrcGV);
508 DestGO->setAlignment(Alignment);
510 forceRenaming(DestGV, SrcGV->getName());
513 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
514 GlobalValue::VisibilityTypes b) {
515 if (a == GlobalValue::HiddenVisibility)
517 if (b == GlobalValue::HiddenVisibility)
519 if (a == GlobalValue::ProtectedVisibility)
521 if (b == GlobalValue::ProtectedVisibility)
526 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
527 Function *SF = dyn_cast<Function>(V);
531 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
532 SF->getLinkage(), SF->getName(), DstM);
533 copyGVAttributes(DF, SF);
535 if (Comdat *SC = SF->getComdat()) {
536 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
540 LazilyLinkFunctions.push_back(SF);
544 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
545 const GlobalVariable *&GVar) {
546 const GlobalValue *GVal = M->getNamedValue(ComdatName);
547 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
548 GVal = GA->getBaseObject();
550 // We cannot resolve the size of the aliasee yet.
551 return emitError("Linking COMDATs named '" + ComdatName +
552 "': COMDAT key involves incomputable alias size.");
555 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
558 "Linking COMDATs named '" + ComdatName +
559 "': GlobalVariable required for data dependent selection!");
564 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
565 Comdat::SelectionKind Src,
566 Comdat::SelectionKind Dst,
567 Comdat::SelectionKind &Result,
569 // The ability to mix Comdat::SelectionKind::Any with
570 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
571 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
572 Dst == Comdat::SelectionKind::Largest;
573 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
574 Src == Comdat::SelectionKind::Largest;
575 if (DstAnyOrLargest && SrcAnyOrLargest) {
576 if (Dst == Comdat::SelectionKind::Largest ||
577 Src == Comdat::SelectionKind::Largest)
578 Result = Comdat::SelectionKind::Largest;
580 Result = Comdat::SelectionKind::Any;
581 } else if (Src == Dst) {
584 return emitError("Linking COMDATs named '" + ComdatName +
585 "': invalid selection kinds!");
589 case Comdat::SelectionKind::Any:
593 case Comdat::SelectionKind::NoDuplicates:
594 return emitError("Linking COMDATs named '" + ComdatName +
595 "': noduplicates has been violated!");
596 case Comdat::SelectionKind::ExactMatch:
597 case Comdat::SelectionKind::Largest:
598 case Comdat::SelectionKind::SameSize: {
599 const GlobalVariable *DstGV;
600 const GlobalVariable *SrcGV;
601 if (getComdatLeader(DstM, ComdatName, DstGV) ||
602 getComdatLeader(SrcM, ComdatName, SrcGV))
605 const DataLayout *DstDL = DstM->getDataLayout();
606 const DataLayout *SrcDL = SrcM->getDataLayout();
607 if (!DstDL || !SrcDL) {
609 "Linking COMDATs named '" + ComdatName +
610 "': can't do size dependent selection without DataLayout!");
613 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
615 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
616 if (Result == Comdat::SelectionKind::ExactMatch) {
617 if (SrcGV->getInitializer() != DstGV->getInitializer())
618 return emitError("Linking COMDATs named '" + ComdatName +
619 "': ExactMatch violated!");
621 } else if (Result == Comdat::SelectionKind::Largest) {
622 LinkFromSrc = SrcSize > DstSize;
623 } else if (Result == Comdat::SelectionKind::SameSize) {
624 if (SrcSize != DstSize)
625 return emitError("Linking COMDATs named '" + ComdatName +
626 "': SameSize violated!");
629 llvm_unreachable("unknown selection kind");
638 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
639 Comdat::SelectionKind &Result,
641 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
642 StringRef ComdatName = SrcC->getName();
643 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
644 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
646 if (DstCI == ComdatSymTab.end()) {
647 // Use the comdat if it is only available in one of the modules.
653 const Comdat *DstC = &DstCI->second;
654 Comdat::SelectionKind DSK = DstC->getSelectionKind();
655 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
659 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
660 const GlobalValue &Dest,
661 const GlobalValue &Src) {
662 // We always have to add Src if it has appending linkage.
663 if (Src.hasAppendingLinkage()) {
668 bool SrcIsDeclaration = Src.isDeclarationForLinker();
669 bool DestIsDeclaration = Dest.isDeclarationForLinker();
671 if (SrcIsDeclaration) {
672 // If Src is external or if both Src & Dest are external.. Just link the
673 // external globals, we aren't adding anything.
674 if (Src.hasDLLImportStorageClass()) {
675 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
676 LinkFromSrc = DestIsDeclaration;
679 // If the Dest is weak, use the source linkage.
680 LinkFromSrc = Dest.hasExternalWeakLinkage();
684 if (DestIsDeclaration) {
685 // If Dest is external but Src is not:
690 if (Src.hasCommonLinkage()) {
691 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
696 if (!Dest.hasCommonLinkage()) {
701 // FIXME: Make datalayout mandatory and just use getDataLayout().
702 DataLayout DL(Dest.getParent());
704 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
705 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
706 LinkFromSrc = SrcSize > DestSize;
710 if (Src.isWeakForLinker()) {
711 assert(!Dest.hasExternalWeakLinkage());
712 assert(!Dest.hasAvailableExternallyLinkage());
714 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
723 if (Dest.isWeakForLinker()) {
724 assert(Src.hasExternalLinkage());
729 assert(!Src.hasExternalWeakLinkage());
730 assert(!Dest.hasExternalWeakLinkage());
731 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
732 "Unexpected linkage type!");
733 return emitError("Linking globals named '" + Src.getName() +
734 "': symbol multiply defined!");
737 /// Loop over all of the linked values to compute type mappings. For example,
738 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
739 /// types 'Foo' but one got renamed when the module was loaded into the same
741 void ModuleLinker::computeTypeMapping() {
742 for (GlobalValue &SGV : SrcM->globals()) {
743 GlobalValue *DGV = getLinkedToGlobal(&SGV);
747 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
748 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
752 // Unify the element type of appending arrays.
753 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
754 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
755 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
758 for (GlobalValue &SGV : *SrcM) {
759 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
760 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
763 for (GlobalValue &SGV : SrcM->aliases()) {
764 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
765 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
768 // Incorporate types by name, scanning all the types in the source module.
769 // At this point, the destination module may have a type "%foo = { i32 }" for
770 // example. When the source module got loaded into the same LLVMContext, if
771 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
772 TypeFinder SrcStructTypes;
773 SrcStructTypes.run(*SrcM, true);
774 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
775 SrcStructTypes.end());
777 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
778 StructType *ST = SrcStructTypes[i];
779 if (!ST->hasName()) continue;
781 // Check to see if there is a dot in the name followed by a digit.
782 size_t DotPos = ST->getName().rfind('.');
783 if (DotPos == 0 || DotPos == StringRef::npos ||
784 ST->getName().back() == '.' ||
785 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
788 // Check to see if the destination module has a struct with the prefix name.
789 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
790 // Don't use it if this actually came from the source module. They're in
791 // the same LLVMContext after all. Also don't use it unless the type is
792 // actually used in the destination module. This can happen in situations
797 // %Z = type { %A } %B = type { %C.1 }
798 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
799 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
800 // %C = type { i8* } %B.3 = type { %C.1 }
802 // When we link Module B with Module A, the '%B' in Module B is
803 // used. However, that would then use '%C.1'. But when we process '%C.1',
804 // we prefer to take the '%C' version. So we are then left with both
805 // '%C.1' and '%C' being used for the same types. This leads to some
806 // variables using one type and some using the other.
807 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
808 TypeMap.addTypeMapping(DST, ST);
811 // Now that we have discovered all of the type equivalences, get a body for
812 // any 'opaque' types in the dest module that are now resolved.
813 TypeMap.linkDefinedTypeBodies();
816 static void upgradeGlobalArray(GlobalVariable *GV) {
817 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
818 StructType *OldTy = cast<StructType>(ATy->getElementType());
819 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
821 // Get the upgraded 3 element type.
822 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
823 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
825 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
827 // Build new constants with a null third field filled in.
828 Constant *OldInitC = GV->getInitializer();
829 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
830 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
831 // Invalid initializer; give up.
833 std::vector<Constant *> Initializers;
834 if (OldInit && OldInit->getNumOperands()) {
835 Value *Null = Constant::getNullValue(VoidPtrTy);
836 for (Use &U : OldInit->operands()) {
837 ConstantStruct *Init = cast<ConstantStruct>(U.get());
838 Initializers.push_back(ConstantStruct::get(
839 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
842 assert(Initializers.size() == ATy->getNumElements() &&
843 "Failed to copy all array elements");
845 // Replace the old GV with a new one.
846 ATy = ArrayType::get(NewTy, Initializers.size());
847 Constant *NewInit = ConstantArray::get(ATy, Initializers);
848 GlobalVariable *NewGV = new GlobalVariable(
849 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
850 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
851 GV->isExternallyInitialized());
852 NewGV->copyAttributesFrom(GV);
854 assert(GV->use_empty() && "program cannot use initializer list");
855 GV->eraseFromParent();
858 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
859 // Look for the global arrays.
860 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
863 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
867 // Check if the types already match.
868 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
870 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
874 // Grab the element types. We can only upgrade an array of a two-field
875 // struct. Only bother if the other one has three-fields.
876 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
877 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
878 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
879 upgradeGlobalArray(DstGV);
882 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
883 upgradeGlobalArray(SrcGV);
885 // We can't upgrade any other differences.
888 void ModuleLinker::upgradeMismatchedGlobals() {
889 upgradeMismatchedGlobalArray("llvm.global_ctors");
890 upgradeMismatchedGlobalArray("llvm.global_dtors");
893 /// If there were any appending global variables, link them together now.
894 /// Return true on error.
895 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
896 const GlobalVariable *SrcGV) {
898 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
899 return emitError("Linking globals named '" + SrcGV->getName() +
900 "': can only link appending global with another appending global!");
902 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
904 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
905 Type *EltTy = DstTy->getElementType();
907 // Check to see that they two arrays agree on type.
908 if (EltTy != SrcTy->getElementType())
909 return emitError("Appending variables with different element types!");
910 if (DstGV->isConstant() != SrcGV->isConstant())
911 return emitError("Appending variables linked with different const'ness!");
913 if (DstGV->getAlignment() != SrcGV->getAlignment())
915 "Appending variables with different alignment need to be linked!");
917 if (DstGV->getVisibility() != SrcGV->getVisibility())
919 "Appending variables with different visibility need to be linked!");
921 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
923 "Appending variables with different unnamed_addr need to be linked!");
925 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
927 "Appending variables with different section name need to be linked!");
929 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
930 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
932 // Create the new global variable.
934 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
935 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
936 DstGV->getThreadLocalMode(),
937 DstGV->getType()->getAddressSpace());
939 // Propagate alignment, visibility and section info.
940 copyGVAttributes(NG, DstGV);
942 AppendingVarInfo AVI;
944 AVI.DstInit = DstGV->getInitializer();
945 AVI.SrcInit = SrcGV->getInitializer();
946 AppendingVars.push_back(AVI);
948 // Replace any uses of the two global variables with uses of the new
950 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
952 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
953 DstGV->eraseFromParent();
955 // Track the source variable so we don't try to link it.
956 DoNotLinkFromSource.insert(SrcGV);
961 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
962 GlobalValue *DGV = getLinkedToGlobal(SGV);
964 // Handle the ultra special appending linkage case first.
965 if (DGV && DGV->hasAppendingLinkage())
966 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
967 cast<GlobalVariable>(SGV));
969 bool LinkFromSrc = true;
971 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
972 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
974 if (const Comdat *SC = SGV->getComdat()) {
975 Comdat::SelectionKind SK;
976 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
977 C = DstM->getOrInsertComdat(SC->getName());
978 C->setSelectionKind(SK);
980 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
985 // Track the source global so that we don't attempt to copy it over when
986 // processing global initializers.
987 DoNotLinkFromSource.insert(SGV);
990 // Make sure to remember this mapping.
992 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
996 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
997 ? DGV->getVisibility()
999 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1002 if (!LinkFromSrc && !DGV)
1006 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1007 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1010 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1011 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1013 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1018 copyGVAttributes(NewGV, SGV);
1020 NewGV->setUnnamedAddr(HasUnnamedAddr);
1021 NewGV->setVisibility(Visibility);
1023 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1025 NewGO->setComdat(C);
1028 // Make sure to remember this mapping.
1031 DGV->replaceAllUsesWith(
1032 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1033 DGV->eraseFromParent();
1035 ValueMap[SGV] = NewGV;
1042 /// Loop through the global variables in the src module and merge them into the
1044 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1047 unsigned Alignment = 0;
1048 bool ClearConstant = false;
1051 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1052 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1054 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1055 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1056 ClearConstant = true;
1060 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1062 NewGVar->setAlignment(Alignment);
1063 if (NewGVar->isDeclaration() && ClearConstant)
1064 NewGVar->setConstant(false);
1069 // No linking to be performed or linking from the source: simply create an
1070 // identical version of the symbol over in the dest module... the
1071 // initializer will be filled in later by LinkGlobalInits.
1072 GlobalVariable *NewDGV = new GlobalVariable(
1073 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1074 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1075 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1076 SGVar->getType()->getAddressSpace());
1079 NewDGV->setAlignment(Alignment);
1084 /// Link the function in the source module into the destination module if
1085 /// needed, setting up mapping information.
1086 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1092 // If the function is to be lazily linked, don't create it just yet.
1093 // The ValueMaterializerTy will deal with creating it if it's used.
1094 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1095 SF->hasAvailableExternallyLinkage())) {
1096 DoNotLinkFromSource.insert(SF);
1100 // If there is no linkage to be performed or we are linking from the source,
1102 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1103 SF->getName(), DstM);
1106 /// Set up prototypes for any aliases that come over from the source module.
1107 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1113 // If there is no linkage to be performed or we're linking from the source,
1115 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1116 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1117 SGA->getLinkage(), SGA->getName(), DstM);
1120 static void getArrayElements(const Constant *C,
1121 SmallVectorImpl<Constant *> &Dest) {
1122 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1124 for (unsigned i = 0; i != NumElements; ++i)
1125 Dest.push_back(C->getAggregateElement(i));
1128 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1129 // Merge the initializer.
1130 SmallVector<Constant *, 16> DstElements;
1131 getArrayElements(AVI.DstInit, DstElements);
1133 SmallVector<Constant *, 16> SrcElements;
1134 getArrayElements(AVI.SrcInit, SrcElements);
1136 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1138 StringRef Name = AVI.NewGV->getName();
1139 bool IsNewStructor =
1140 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1141 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1143 for (auto *V : SrcElements) {
1144 if (IsNewStructor) {
1145 Constant *Key = V->getAggregateElement(2);
1146 if (DoNotLinkFromSource.count(Key))
1149 DstElements.push_back(
1150 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1152 if (IsNewStructor) {
1153 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1154 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1157 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1160 /// Update the initializers in the Dest module now that all globals that may be
1161 /// referenced are in Dest.
1162 void ModuleLinker::linkGlobalInits() {
1163 // Loop over all of the globals in the src module, mapping them over as we go
1164 for (Module::const_global_iterator I = SrcM->global_begin(),
1165 E = SrcM->global_end(); I != E; ++I) {
1167 // Only process initialized GV's or ones not already in dest.
1168 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1170 // Grab destination global variable.
1171 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1172 // Figure out what the initializer looks like in the dest module.
1173 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1174 RF_None, &TypeMap, &ValMaterializer));
1178 /// Copy the source function over into the dest function and fix up references
1179 /// to values. At this point we know that Dest is an external function, and
1180 /// that Src is not.
1181 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1182 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1184 // Go through and convert function arguments over, remembering the mapping.
1185 Function::arg_iterator DI = Dst->arg_begin();
1186 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1187 I != E; ++I, ++DI) {
1188 DI->setName(I->getName()); // Copy the name over.
1190 // Add a mapping to our mapping.
1194 // Splice the body of the source function into the dest function.
1195 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1197 // At this point, all of the instructions and values of the function are now
1198 // copied over. The only problem is that they are still referencing values in
1199 // the Source function as operands. Loop through all of the operands of the
1200 // functions and patch them up to point to the local versions.
1201 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1202 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1203 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1206 // There is no need to map the arguments anymore.
1207 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1213 /// Insert all of the aliases in Src into the Dest module.
1214 void ModuleLinker::linkAliasBodies() {
1215 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1217 if (DoNotLinkFromSource.count(I))
1219 if (Constant *Aliasee = I->getAliasee()) {
1220 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1222 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1223 DA->setAliasee(Val);
1228 /// Insert all of the named MDNodes in Src into the Dest module.
1229 void ModuleLinker::linkNamedMDNodes() {
1230 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1231 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1232 E = SrcM->named_metadata_end(); I != E; ++I) {
1233 // Don't link module flags here. Do them separately.
1234 if (&*I == SrcModFlags) continue;
1235 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1236 // Add Src elements into Dest node.
1237 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1238 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1239 RF_None, &TypeMap, &ValMaterializer));
1243 /// Merge the linker flags in Src into the Dest module.
1244 bool ModuleLinker::linkModuleFlagsMetadata() {
1245 // If the source module has no module flags, we are done.
1246 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1247 if (!SrcModFlags) return false;
1249 // If the destination module doesn't have module flags yet, then just copy
1250 // over the source module's flags.
1251 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1252 if (DstModFlags->getNumOperands() == 0) {
1253 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1254 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1259 // First build a map of the existing module flags and requirements.
1260 DenseMap<MDString*, MDNode*> Flags;
1261 SmallSetVector<MDNode*, 16> Requirements;
1262 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1263 MDNode *Op = DstModFlags->getOperand(I);
1264 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1265 MDString *ID = cast<MDString>(Op->getOperand(1));
1267 if (Behavior->getZExtValue() == Module::Require) {
1268 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1274 // Merge in the flags from the source module, and also collect its set of
1276 bool HasErr = false;
1277 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1278 MDNode *SrcOp = SrcModFlags->getOperand(I);
1279 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1280 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1281 MDNode *DstOp = Flags.lookup(ID);
1282 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1284 // If this is a requirement, add it and continue.
1285 if (SrcBehaviorValue == Module::Require) {
1286 // If the destination module does not already have this requirement, add
1288 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1289 DstModFlags->addOperand(SrcOp);
1294 // If there is no existing flag with this ID, just add it.
1297 DstModFlags->addOperand(SrcOp);
1301 // Otherwise, perform a merge.
1302 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1303 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1305 // If either flag has override behavior, handle it first.
1306 if (DstBehaviorValue == Module::Override) {
1307 // Diagnose inconsistent flags which both have override behavior.
1308 if (SrcBehaviorValue == Module::Override &&
1309 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1310 HasErr |= emitError("linking module flags '" + ID->getString() +
1311 "': IDs have conflicting override values");
1314 } else if (SrcBehaviorValue == Module::Override) {
1315 // Update the destination flag to that of the source.
1316 DstOp->replaceOperandWith(0, SrcBehavior);
1317 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1321 // Diagnose inconsistent merge behavior types.
1322 if (SrcBehaviorValue != DstBehaviorValue) {
1323 HasErr |= emitError("linking module flags '" + ID->getString() +
1324 "': IDs have conflicting behaviors");
1328 // Perform the merge for standard behavior types.
1329 switch (SrcBehaviorValue) {
1330 case Module::Require:
1331 case Module::Override: llvm_unreachable("not possible");
1332 case Module::Error: {
1333 // Emit an error if the values differ.
1334 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1335 HasErr |= emitError("linking module flags '" + ID->getString() +
1336 "': IDs have conflicting values");
1340 case Module::Warning: {
1341 // Emit a warning if the values differ.
1342 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1343 emitWarning("linking module flags '" + ID->getString() +
1344 "': IDs have conflicting values");
1348 case Module::Append: {
1349 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1350 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1351 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1352 Value **VP, **Values = VP = new Value*[NumOps];
1353 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1354 *VP = DstValue->getOperand(i);
1355 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1356 *VP = SrcValue->getOperand(i);
1357 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1358 ArrayRef<Value*>(Values,
1363 case Module::AppendUnique: {
1364 SmallSetVector<Value*, 16> Elts;
1365 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1366 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1367 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1368 Elts.insert(DstValue->getOperand(i));
1369 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1370 Elts.insert(SrcValue->getOperand(i));
1371 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1372 ArrayRef<Value*>(Elts.begin(),
1379 // Check all of the requirements.
1380 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1381 MDNode *Requirement = Requirements[I];
1382 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1383 Value *ReqValue = Requirement->getOperand(1);
1385 MDNode *Op = Flags[Flag];
1386 if (!Op || Op->getOperand(2) != ReqValue) {
1387 HasErr |= emitError("linking module flags '" + Flag->getString() +
1388 "': does not have the required value");
1396 bool ModuleLinker::run() {
1397 assert(DstM && "Null destination module");
1398 assert(SrcM && "Null source module");
1400 // Inherit the target data from the source module if the destination module
1401 // doesn't have one already.
1402 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1403 DstM->setDataLayout(SrcM->getDataLayout());
1405 // Copy the target triple from the source to dest if the dest's is empty.
1406 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1407 DstM->setTargetTriple(SrcM->getTargetTriple());
1409 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1410 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1411 emitWarning("Linking two modules of different data layouts: '" +
1412 SrcM->getModuleIdentifier() + "' is '" +
1413 SrcM->getDataLayoutStr() + "' whereas '" +
1414 DstM->getModuleIdentifier() + "' is '" +
1415 DstM->getDataLayoutStr() + "'\n");
1417 if (!SrcM->getTargetTriple().empty() &&
1418 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1419 emitWarning("Linking two modules of different target triples: " +
1420 SrcM->getModuleIdentifier() + "' is '" +
1421 SrcM->getTargetTriple() + "' whereas '" +
1422 DstM->getModuleIdentifier() + "' is '" +
1423 DstM->getTargetTriple() + "'\n");
1426 // Append the module inline asm string.
1427 if (!SrcM->getModuleInlineAsm().empty()) {
1428 if (DstM->getModuleInlineAsm().empty())
1429 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1431 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1432 SrcM->getModuleInlineAsm());
1435 // Loop over all of the linked values to compute type mappings.
1436 computeTypeMapping();
1438 ComdatsChosen.clear();
1439 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1440 const Comdat &C = SMEC.getValue();
1441 if (ComdatsChosen.count(&C))
1443 Comdat::SelectionKind SK;
1445 if (getComdatResult(&C, SK, LinkFromSrc))
1447 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1450 // Upgrade mismatched global arrays.
1451 upgradeMismatchedGlobals();
1453 // Insert all of the globals in src into the DstM module... without linking
1454 // initializers (which could refer to functions not yet mapped over).
1455 for (Module::global_iterator I = SrcM->global_begin(),
1456 E = SrcM->global_end(); I != E; ++I)
1457 if (linkGlobalValueProto(I))
1460 // Link the functions together between the two modules, without doing function
1461 // bodies... this just adds external function prototypes to the DstM
1462 // function... We do this so that when we begin processing function bodies,
1463 // all of the global values that may be referenced are available in our
1465 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1466 if (linkGlobalValueProto(I))
1469 // If there were any aliases, link them now.
1470 for (Module::alias_iterator I = SrcM->alias_begin(),
1471 E = SrcM->alias_end(); I != E; ++I)
1472 if (linkGlobalValueProto(I))
1475 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1476 linkAppendingVarInit(AppendingVars[i]);
1478 // Link in the function bodies that are defined in the source module into
1480 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1481 // Skip if not linking from source.
1482 if (DoNotLinkFromSource.count(SF)) continue;
1484 Function *DF = cast<Function>(ValueMap[SF]);
1485 if (SF->hasPrefixData()) {
1486 // Link in the prefix data.
1487 DF->setPrefixData(MapValue(
1488 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1491 // Materialize if needed.
1492 if (std::error_code EC = SF->materialize())
1493 return emitError(EC.message());
1495 // Skip if no body (function is external).
1496 if (SF->isDeclaration())
1499 linkFunctionBody(DF, SF);
1500 SF->Dematerialize();
1503 // Resolve all uses of aliases with aliasees.
1506 // Remap all of the named MDNodes in Src into the DstM module. We do this
1507 // after linking GlobalValues so that MDNodes that reference GlobalValues
1508 // are properly remapped.
1511 // Merge the module flags into the DstM module.
1512 if (linkModuleFlagsMetadata())
1515 // Update the initializers in the DstM module now that all globals that may
1516 // be referenced are in DstM.
1519 // Process vector of lazily linked in functions.
1520 bool LinkedInAnyFunctions;
1522 LinkedInAnyFunctions = false;
1524 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1525 E = LazilyLinkFunctions.end(); I != E; ++I) {
1530 Function *DF = cast<Function>(ValueMap[SF]);
1531 if (SF->hasPrefixData()) {
1532 // Link in the prefix data.
1533 DF->setPrefixData(MapValue(SF->getPrefixData(),
1540 // Materialize if needed.
1541 if (std::error_code EC = SF->materialize())
1542 return emitError(EC.message());
1544 // Skip if no body (function is external).
1545 if (SF->isDeclaration())
1548 // Erase from vector *before* the function body is linked - linkFunctionBody could
1550 LazilyLinkFunctions.erase(I);
1552 // Link in function body.
1553 linkFunctionBody(DF, SF);
1554 SF->Dematerialize();
1556 // Set flag to indicate we may have more functions to lazily link in
1557 // since we linked in a function.
1558 LinkedInAnyFunctions = true;
1561 } while (LinkedInAnyFunctions);
1566 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1567 this->Composite = M;
1568 this->DiagnosticHandler = DiagnosticHandler;
1570 TypeFinder StructTypes;
1571 StructTypes.run(*M, true);
1572 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1575 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1576 init(M, DiagnosticHandler);
1579 Linker::Linker(Module *M) {
1580 init(M, [this](const DiagnosticInfo &DI) {
1581 Composite->getContext().diagnose(DI);
1588 void Linker::deleteModule() {
1590 Composite = nullptr;
1593 bool Linker::linkInModule(Module *Src) {
1594 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1596 return TheLinker.run();
1599 //===----------------------------------------------------------------------===//
1600 // LinkModules entrypoint.
1601 //===----------------------------------------------------------------------===//
1603 /// This function links two modules together, with the resulting Dest module
1604 /// modified to be the composite of the two input modules. If an error occurs,
1605 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1606 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1607 /// relied on to be consistent.
1608 bool Linker::LinkModules(Module *Dest, Module *Src,
1609 DiagnosticHandlerFunction DiagnosticHandler) {
1610 Linker L(Dest, DiagnosticHandler);
1611 return L.linkInModule(Src);
1614 bool Linker::LinkModules(Module *Dest, Module *Src) {
1616 return L.linkInModule(Src);
1619 //===----------------------------------------------------------------------===//
1621 //===----------------------------------------------------------------------===//
1623 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1624 LLVMLinkerMode Mode, char **OutMessages) {
1625 Module *D = unwrap(Dest);
1626 std::string Message;
1627 raw_string_ostream Stream(Message);
1628 DiagnosticPrinterRawOStream DP(Stream);
1630 LLVMBool Result = Linker::LinkModules(
1631 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1633 if (OutMessages && Result)
1634 *OutMessages = strdup(Message.c_str());