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) {return cast<FunctionType>(get((Type*)T));}
76 /// Dump out the type map for debugging purposes.
78 for (DenseMap<Type*, Type*>::const_iterator
79 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
80 dbgs() << "TypeMap: ";
81 I->first->print(dbgs());
83 I->second->print(dbgs());
89 Type *getImpl(Type *T);
90 /// Implement the ValueMapTypeRemapper interface.
91 Type *remapType(Type *SrcTy) override {
95 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
99 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
100 Type *&Entry = MappedTypes[SrcTy];
103 if (DstTy == SrcTy) {
108 // Check to see if these types are recursively isomorphic and establish a
109 // mapping between them if so.
110 if (!areTypesIsomorphic(DstTy, SrcTy)) {
111 // Oops, they aren't isomorphic. Just discard this request by rolling out
112 // any speculative mappings we've established.
113 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
114 MappedTypes.erase(SpeculativeTypes[i]);
116 SpeculativeTypes.clear();
119 /// Recursively walk this pair of types, returning true if they are isomorphic,
120 /// false if they are not.
121 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
122 // Two types with differing kinds are clearly not isomorphic.
123 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
125 // If we have an entry in the MappedTypes table, then we have our answer.
126 Type *&Entry = MappedTypes[SrcTy];
128 return Entry == DstTy;
130 // Two identical types are clearly isomorphic. Remember this
131 // non-speculatively.
132 if (DstTy == SrcTy) {
137 // Okay, we have two types with identical kinds that we haven't seen before.
139 // If this is an opaque struct type, special case it.
140 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
141 // Mapping an opaque type to any struct, just keep the dest struct.
142 if (SSTy->isOpaque()) {
144 SpeculativeTypes.push_back(SrcTy);
148 // Mapping a non-opaque source type to an opaque dest. If this is the first
149 // type that we're mapping onto this destination type then we succeed. Keep
150 // the dest, but fill it in later. This doesn't need to be speculative. If
151 // this is the second (different) type that we're trying to map onto the
152 // same opaque type then we fail.
153 if (cast<StructType>(DstTy)->isOpaque()) {
154 // We can only map one source type onto the opaque destination type.
155 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
157 SrcDefinitionsToResolve.push_back(SSTy);
163 // If the number of subtypes disagree between the two types, then we fail.
164 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
167 // Fail if any of the extra properties (e.g. array size) of the type disagree.
168 if (isa<IntegerType>(DstTy))
169 return false; // bitwidth disagrees.
170 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
171 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
174 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
175 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
177 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
178 StructType *SSTy = cast<StructType>(SrcTy);
179 if (DSTy->isLiteral() != SSTy->isLiteral() ||
180 DSTy->isPacked() != SSTy->isPacked())
182 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
183 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
185 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
186 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
190 // Otherwise, we speculate that these two types will line up and recursively
191 // check the subelements.
193 SpeculativeTypes.push_back(SrcTy);
195 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
196 if (!areTypesIsomorphic(DstTy->getContainedType(i),
197 SrcTy->getContainedType(i)))
200 // If everything seems to have lined up, then everything is great.
204 void TypeMapTy::linkDefinedTypeBodies() {
205 SmallVector<Type*, 16> Elements;
206 SmallString<16> TmpName;
208 // Note that processing entries in this loop (calling 'get') can add new
209 // entries to the SrcDefinitionsToResolve vector.
210 while (!SrcDefinitionsToResolve.empty()) {
211 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
212 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
214 // TypeMap is a many-to-one mapping, if there were multiple types that
215 // provide a body for DstSTy then previous iterations of this loop may have
216 // already handled it. Just ignore this case.
217 if (!DstSTy->isOpaque()) continue;
218 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
220 // Map the body of the source type over to a new body for the dest type.
221 Elements.resize(SrcSTy->getNumElements());
222 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
223 Elements[i] = getImpl(SrcSTy->getElementType(i));
225 DstSTy->setBody(Elements, SrcSTy->isPacked());
227 // If DstSTy has no name or has a longer name than STy, then viciously steal
229 if (!SrcSTy->hasName()) continue;
230 StringRef SrcName = SrcSTy->getName();
232 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
233 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
235 DstSTy->setName(TmpName.str());
240 DstResolvedOpaqueTypes.clear();
243 Type *TypeMapTy::get(Type *Ty) {
244 Type *Result = getImpl(Ty);
246 // If this caused a reference to any struct type, resolve it before returning.
247 if (!SrcDefinitionsToResolve.empty())
248 linkDefinedTypeBodies();
252 /// This is the recursive version of get().
253 Type *TypeMapTy::getImpl(Type *Ty) {
254 // If we already have an entry for this type, return it.
255 Type **Entry = &MappedTypes[Ty];
256 if (*Entry) return *Entry;
258 // If this is not a named struct type, then just map all of the elements and
259 // then rebuild the type from inside out.
260 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
261 // If there are no element types to map, then the type is itself. This is
262 // true for the anonymous {} struct, things like 'float', integers, etc.
263 if (Ty->getNumContainedTypes() == 0)
266 // Remap all of the elements, keeping track of whether any of them change.
267 bool AnyChange = false;
268 SmallVector<Type*, 4> ElementTypes;
269 ElementTypes.resize(Ty->getNumContainedTypes());
270 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
271 ElementTypes[i] = getImpl(Ty->getContainedType(i));
272 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
275 // If we found our type while recursively processing stuff, just use it.
276 Entry = &MappedTypes[Ty];
277 if (*Entry) return *Entry;
279 // If all of the element types mapped directly over, then the type is usable
284 // Otherwise, rebuild a modified type.
285 switch (Ty->getTypeID()) {
286 default: llvm_unreachable("unknown derived type to remap");
287 case Type::ArrayTyID:
288 return *Entry = ArrayType::get(ElementTypes[0],
289 cast<ArrayType>(Ty)->getNumElements());
290 case Type::VectorTyID:
291 return *Entry = VectorType::get(ElementTypes[0],
292 cast<VectorType>(Ty)->getNumElements());
293 case Type::PointerTyID:
294 return *Entry = PointerType::get(ElementTypes[0],
295 cast<PointerType>(Ty)->getAddressSpace());
296 case Type::FunctionTyID:
297 return *Entry = FunctionType::get(ElementTypes[0],
298 makeArrayRef(ElementTypes).slice(1),
299 cast<FunctionType>(Ty)->isVarArg());
300 case Type::StructTyID:
301 // Note that this is only reached for anonymous structs.
302 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
303 cast<StructType>(Ty)->isPacked());
307 // Otherwise, this is an unmapped named struct. If the struct can be directly
308 // mapped over, just use it as-is. This happens in a case when the linked-in
309 // module has something like:
310 // %T = type {%T*, i32}
311 // @GV = global %T* null
312 // where T does not exist at all in the destination module.
314 // The other case we watch for is when the type is not in the destination
315 // module, but that it has to be rebuilt because it refers to something that
316 // is already mapped. For example, if the destination module has:
318 // and the source module has something like
319 // %A' = type { i32 }
320 // %B = type { %A'* }
321 // @GV = global %B* null
322 // then we want to create a new type: "%B = type { %A*}" and have it take the
323 // pristine "%B" name from the source module.
325 // To determine which case this is, we have to recursively walk the type graph
326 // speculating that we'll be able to reuse it unmodified. Only if this is
327 // safe would we map the entire thing over. Because this is an optimization,
328 // and is not required for the prettiness of the linked module, we just skip
329 // it and always rebuild a type here.
330 StructType *STy = cast<StructType>(Ty);
332 // If the type is opaque, we can just use it directly.
333 if (STy->isOpaque()) {
334 // A named structure type from src module is used. Add it to the Set of
335 // identified structs in the destination module.
336 DstStructTypesSet.insert(STy);
340 // Otherwise we create a new type and resolve its body later. This will be
341 // resolved by the top level of get().
342 SrcDefinitionsToResolve.push_back(STy);
343 StructType *DTy = StructType::create(STy->getContext());
344 // A new identified structure type was created. Add it to the set of
345 // identified structs in the destination module.
346 DstStructTypesSet.insert(DTy);
347 DstResolvedOpaqueTypes.insert(DTy);
351 //===----------------------------------------------------------------------===//
352 // ModuleLinker implementation.
353 //===----------------------------------------------------------------------===//
358 /// Creates prototypes for functions that are lazily linked on the fly. This
359 /// speeds up linking for modules with many/ lazily linked functions of which
361 class ValueMaterializerTy : public ValueMaterializer {
364 std::vector<Function*> &LazilyLinkFunctions;
366 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
367 std::vector<Function*> &LazilyLinkFunctions) :
368 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
369 LazilyLinkFunctions(LazilyLinkFunctions) {
372 Value *materializeValueFor(Value *V) override;
376 class LinkDiagnosticInfo : public DiagnosticInfo {
380 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
381 void print(DiagnosticPrinter &DP) const override;
383 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
385 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
386 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
389 /// This is an implementation class for the LinkModules function, which is the
390 /// entrypoint for this file.
395 ValueMaterializerTy ValMaterializer;
397 /// Mapping of values from what they used to be in Src, to what they are now
398 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
399 /// due to the use of Value handles which the Linker doesn't actually need,
400 /// but this allows us to reuse the ValueMapper code.
401 ValueToValueMapTy ValueMap;
403 struct AppendingVarInfo {
404 GlobalVariable *NewGV; // New aggregate global in dest module.
405 const Constant *DstInit; // Old initializer from dest module.
406 const Constant *SrcInit; // Old initializer from src module.
409 std::vector<AppendingVarInfo> AppendingVars;
411 // Set of items not to link in from source.
412 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
414 // Vector of functions to lazily link in.
415 std::vector<Function*> LazilyLinkFunctions;
417 Linker::DiagnosticHandlerFunction DiagnosticHandler;
420 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM,
421 Linker::DiagnosticHandlerFunction DiagnosticHandler)
422 : DstM(dstM), SrcM(srcM), TypeMap(Set),
423 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
424 DiagnosticHandler(DiagnosticHandler) {}
429 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
430 const GlobalValue &Src);
432 /// Helper method for setting a message and returning an error code.
433 bool emitError(const Twine &Message) {
434 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
438 void emitWarning(const Twine &Message) {
439 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
442 bool getComdatLeader(Module *M, StringRef ComdatName,
443 const GlobalVariable *&GVar);
444 bool computeResultingSelectionKind(StringRef ComdatName,
445 Comdat::SelectionKind Src,
446 Comdat::SelectionKind Dst,
447 Comdat::SelectionKind &Result,
449 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
451 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
454 /// Given a global in the source module, return the global in the
455 /// destination module that is being linked to, if any.
456 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
457 // If the source has no name it can't link. If it has local linkage,
458 // there is no name match-up going on.
459 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
462 // Otherwise see if we have a match in the destination module's symtab.
463 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
464 if (!DGV) return nullptr;
466 // If we found a global with the same name in the dest module, but it has
467 // internal linkage, we are really not doing any linkage here.
468 if (DGV->hasLocalLinkage())
471 // Otherwise, we do in fact link to the destination global.
475 void computeTypeMapping();
477 void upgradeMismatchedGlobalArray(StringRef Name);
478 void upgradeMismatchedGlobals();
480 bool linkAppendingVarProto(GlobalVariable *DstGV,
481 const GlobalVariable *SrcGV);
483 bool linkGlobalValueProto(GlobalValue *GV);
484 GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar,
485 GlobalValue *DGV, bool LinkFromSrc);
486 GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV,
488 GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV,
491 bool linkModuleFlagsMetadata();
493 void linkAppendingVarInit(const AppendingVarInfo &AVI);
494 void linkGlobalInits();
495 void linkFunctionBody(Function *Dst, Function *Src);
496 void linkAliasBodies();
497 void linkNamedMDNodes();
501 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
502 /// table. This is good for all clients except for us. Go through the trouble
503 /// to force this back.
504 static void forceRenaming(GlobalValue *GV, StringRef Name) {
505 // If the global doesn't force its name or if it already has the right name,
506 // there is nothing for us to do.
507 if (GV->hasLocalLinkage() || GV->getName() == Name)
510 Module *M = GV->getParent();
512 // If there is a conflict, rename the conflict.
513 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
514 GV->takeName(ConflictGV);
515 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
516 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
518 GV->setName(Name); // Force the name back
522 /// copy additional attributes (those not needed to construct a GlobalValue)
523 /// from the SrcGV to the DestGV.
524 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
525 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
526 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
529 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
531 DestGV->copyAttributesFrom(SrcGV);
534 DestGO->setAlignment(Alignment);
536 forceRenaming(DestGV, SrcGV->getName());
539 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
540 GlobalValue::VisibilityTypes b) {
541 if (a == GlobalValue::HiddenVisibility)
543 if (b == GlobalValue::HiddenVisibility)
545 if (a == GlobalValue::ProtectedVisibility)
547 if (b == GlobalValue::ProtectedVisibility)
552 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
553 Function *SF = dyn_cast<Function>(V);
557 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
558 SF->getLinkage(), SF->getName(), DstM);
559 copyGVAttributes(DF, SF);
561 if (Comdat *SC = SF->getComdat()) {
562 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
566 LazilyLinkFunctions.push_back(SF);
570 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
571 const GlobalVariable *&GVar) {
572 const GlobalValue *GVal = M->getNamedValue(ComdatName);
573 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
574 GVal = GA->getBaseObject();
576 // We cannot resolve the size of the aliasee yet.
577 return emitError("Linking COMDATs named '" + ComdatName +
578 "': COMDAT key involves incomputable alias size.");
581 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
584 "Linking COMDATs named '" + ComdatName +
585 "': GlobalVariable required for data dependent selection!");
590 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
591 Comdat::SelectionKind Src,
592 Comdat::SelectionKind Dst,
593 Comdat::SelectionKind &Result,
595 // The ability to mix Comdat::SelectionKind::Any with
596 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
597 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
598 Dst == Comdat::SelectionKind::Largest;
599 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
600 Src == Comdat::SelectionKind::Largest;
601 if (DstAnyOrLargest && SrcAnyOrLargest) {
602 if (Dst == Comdat::SelectionKind::Largest ||
603 Src == Comdat::SelectionKind::Largest)
604 Result = Comdat::SelectionKind::Largest;
606 Result = Comdat::SelectionKind::Any;
607 } else if (Src == Dst) {
610 return emitError("Linking COMDATs named '" + ComdatName +
611 "': invalid selection kinds!");
615 case Comdat::SelectionKind::Any:
619 case Comdat::SelectionKind::NoDuplicates:
620 return emitError("Linking COMDATs named '" + ComdatName +
621 "': noduplicates has been violated!");
622 case Comdat::SelectionKind::ExactMatch:
623 case Comdat::SelectionKind::Largest:
624 case Comdat::SelectionKind::SameSize: {
625 const GlobalVariable *DstGV;
626 const GlobalVariable *SrcGV;
627 if (getComdatLeader(DstM, ComdatName, DstGV) ||
628 getComdatLeader(SrcM, ComdatName, SrcGV))
631 const DataLayout *DstDL = DstM->getDataLayout();
632 const DataLayout *SrcDL = SrcM->getDataLayout();
633 if (!DstDL || !SrcDL) {
635 "Linking COMDATs named '" + ComdatName +
636 "': can't do size dependent selection without DataLayout!");
639 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
641 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
642 if (Result == Comdat::SelectionKind::ExactMatch) {
643 if (SrcGV->getInitializer() != DstGV->getInitializer())
644 return emitError("Linking COMDATs named '" + ComdatName +
645 "': ExactMatch violated!");
647 } else if (Result == Comdat::SelectionKind::Largest) {
648 LinkFromSrc = SrcSize > DstSize;
649 } else if (Result == Comdat::SelectionKind::SameSize) {
650 if (SrcSize != DstSize)
651 return emitError("Linking COMDATs named '" + ComdatName +
652 "': SameSize violated!");
655 llvm_unreachable("unknown selection kind");
664 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
665 Comdat::SelectionKind &Result,
667 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
668 StringRef ComdatName = SrcC->getName();
669 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
670 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
672 if (DstCI == ComdatSymTab.end()) {
673 // Use the comdat if it is only available in one of the modules.
679 const Comdat *DstC = &DstCI->second;
680 Comdat::SelectionKind DSK = DstC->getSelectionKind();
681 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
685 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
686 const GlobalValue &Dest,
687 const GlobalValue &Src) {
688 // We always have to add Src if it has appending linkage.
689 if (Src.hasAppendingLinkage()) {
694 bool SrcIsDeclaration = Src.isDeclarationForLinker();
695 bool DestIsDeclaration = Dest.isDeclarationForLinker();
697 if (SrcIsDeclaration) {
698 // If Src is external or if both Src & Dest are external.. Just link the
699 // external globals, we aren't adding anything.
700 if (Src.hasDLLImportStorageClass()) {
701 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
702 LinkFromSrc = DestIsDeclaration;
705 // If the Dest is weak, use the source linkage.
706 LinkFromSrc = Dest.hasExternalWeakLinkage();
710 if (DestIsDeclaration) {
711 // If Dest is external but Src is not:
716 if (Src.hasCommonLinkage()) {
717 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
722 if (!Dest.hasCommonLinkage()) {
727 // FIXME: Make datalayout mandatory and just use getDataLayout().
728 DataLayout DL(Dest.getParent());
730 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
731 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
732 LinkFromSrc = SrcSize > DestSize;
736 if (Src.isWeakForLinker()) {
737 assert(!Dest.hasExternalWeakLinkage());
738 assert(!Dest.hasAvailableExternallyLinkage());
740 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
749 if (Dest.isWeakForLinker()) {
750 assert(Src.hasExternalLinkage());
755 assert(!Src.hasExternalWeakLinkage());
756 assert(!Dest.hasExternalWeakLinkage());
757 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
758 "Unexpected linkage type!");
759 return emitError("Linking globals named '" + Src.getName() +
760 "': symbol multiply defined!");
763 /// Loop over all of the linked values to compute type mappings. For example,
764 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
765 /// types 'Foo' but one got renamed when the module was loaded into the same
767 void ModuleLinker::computeTypeMapping() {
768 for (GlobalValue &SGV : SrcM->globals()) {
769 GlobalValue *DGV = getLinkedToGlobal(&SGV);
773 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
774 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
778 // Unify the element type of appending arrays.
779 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
780 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
781 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
784 for (GlobalValue &SGV : *SrcM) {
785 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
786 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
789 for (GlobalValue &SGV : SrcM->aliases()) {
790 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
791 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
794 // Incorporate types by name, scanning all the types in the source module.
795 // At this point, the destination module may have a type "%foo = { i32 }" for
796 // example. When the source module got loaded into the same LLVMContext, if
797 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
798 TypeFinder SrcStructTypes;
799 SrcStructTypes.run(*SrcM, true);
800 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
801 SrcStructTypes.end());
803 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
804 StructType *ST = SrcStructTypes[i];
805 if (!ST->hasName()) continue;
807 // Check to see if there is a dot in the name followed by a digit.
808 size_t DotPos = ST->getName().rfind('.');
809 if (DotPos == 0 || DotPos == StringRef::npos ||
810 ST->getName().back() == '.' ||
811 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
814 // Check to see if the destination module has a struct with the prefix name.
815 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
816 // Don't use it if this actually came from the source module. They're in
817 // the same LLVMContext after all. Also don't use it unless the type is
818 // actually used in the destination module. This can happen in situations
823 // %Z = type { %A } %B = type { %C.1 }
824 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
825 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
826 // %C = type { i8* } %B.3 = type { %C.1 }
828 // When we link Module B with Module A, the '%B' in Module B is
829 // used. However, that would then use '%C.1'. But when we process '%C.1',
830 // we prefer to take the '%C' version. So we are then left with both
831 // '%C.1' and '%C' being used for the same types. This leads to some
832 // variables using one type and some using the other.
833 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
834 TypeMap.addTypeMapping(DST, ST);
837 // Now that we have discovered all of the type equivalences, get a body for
838 // any 'opaque' types in the dest module that are now resolved.
839 TypeMap.linkDefinedTypeBodies();
842 static void upgradeGlobalArray(GlobalVariable *GV) {
843 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
844 StructType *OldTy = cast<StructType>(ATy->getElementType());
845 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
847 // Get the upgraded 3 element type.
848 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
849 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
851 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
853 // Build new constants with a null third field filled in.
854 Constant *OldInitC = GV->getInitializer();
855 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
856 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
857 // Invalid initializer; give up.
859 std::vector<Constant *> Initializers;
860 if (OldInit && OldInit->getNumOperands()) {
861 Value *Null = Constant::getNullValue(VoidPtrTy);
862 for (Use &U : OldInit->operands()) {
863 ConstantStruct *Init = cast<ConstantStruct>(U.get());
864 Initializers.push_back(ConstantStruct::get(
865 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
868 assert(Initializers.size() == ATy->getNumElements() &&
869 "Failed to copy all array elements");
871 // Replace the old GV with a new one.
872 ATy = ArrayType::get(NewTy, Initializers.size());
873 Constant *NewInit = ConstantArray::get(ATy, Initializers);
874 GlobalVariable *NewGV = new GlobalVariable(
875 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
876 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
877 GV->isExternallyInitialized());
878 NewGV->copyAttributesFrom(GV);
880 assert(GV->use_empty() && "program cannot use initializer list");
881 GV->eraseFromParent();
884 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
885 // Look for the global arrays.
886 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
889 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
893 // Check if the types already match.
894 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
896 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
900 // Grab the element types. We can only upgrade an array of a two-field
901 // struct. Only bother if the other one has three-fields.
902 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
903 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
904 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
905 upgradeGlobalArray(DstGV);
908 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
909 upgradeGlobalArray(SrcGV);
911 // We can't upgrade any other differences.
914 void ModuleLinker::upgradeMismatchedGlobals() {
915 upgradeMismatchedGlobalArray("llvm.global_ctors");
916 upgradeMismatchedGlobalArray("llvm.global_dtors");
919 /// If there were any appending global variables, link them together now.
920 /// Return true on error.
921 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
922 const GlobalVariable *SrcGV) {
924 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
925 return emitError("Linking globals named '" + SrcGV->getName() +
926 "': can only link appending global with another appending global!");
928 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
930 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
931 Type *EltTy = DstTy->getElementType();
933 // Check to see that they two arrays agree on type.
934 if (EltTy != SrcTy->getElementType())
935 return emitError("Appending variables with different element types!");
936 if (DstGV->isConstant() != SrcGV->isConstant())
937 return emitError("Appending variables linked with different const'ness!");
939 if (DstGV->getAlignment() != SrcGV->getAlignment())
941 "Appending variables with different alignment need to be linked!");
943 if (DstGV->getVisibility() != SrcGV->getVisibility())
945 "Appending variables with different visibility need to be linked!");
947 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
949 "Appending variables with different unnamed_addr need to be linked!");
951 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
953 "Appending variables with different section name need to be linked!");
955 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
956 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
958 // Create the new global variable.
960 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
961 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
962 DstGV->getThreadLocalMode(),
963 DstGV->getType()->getAddressSpace());
965 // Propagate alignment, visibility and section info.
966 copyGVAttributes(NG, DstGV);
968 AppendingVarInfo AVI;
970 AVI.DstInit = DstGV->getInitializer();
971 AVI.SrcInit = SrcGV->getInitializer();
972 AppendingVars.push_back(AVI);
974 // Replace any uses of the two global variables with uses of the new
976 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
978 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
979 DstGV->eraseFromParent();
981 // Track the source variable so we don't try to link it.
982 DoNotLinkFromSource.insert(SrcGV);
987 bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
988 GlobalValue *DGV = getLinkedToGlobal(SGV);
990 // Handle the ultra special appending linkage case first.
991 if (DGV && DGV->hasAppendingLinkage())
992 return linkAppendingVarProto(cast<GlobalVariable>(DGV),
993 cast<GlobalVariable>(SGV));
995 bool LinkFromSrc = true;
997 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
998 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1000 if (const Comdat *SC = SGV->getComdat()) {
1001 Comdat::SelectionKind SK;
1002 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1003 C = DstM->getOrInsertComdat(SC->getName());
1004 C->setSelectionKind(SK);
1006 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1011 // Track the source global so that we don't attempt to copy it over when
1012 // processing global initializers.
1013 DoNotLinkFromSource.insert(SGV);
1016 // Make sure to remember this mapping.
1018 ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1022 Visibility = isLessConstraining(Visibility, DGV->getVisibility())
1023 ? DGV->getVisibility()
1025 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1028 if (!LinkFromSrc && !DGV)
1032 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
1033 NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc);
1036 } else if (auto *SF = dyn_cast<Function>(SGV)) {
1037 NewGV = linkFunctionProto(SF, DGV, LinkFromSrc);
1039 NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc);
1044 copyGVAttributes(NewGV, SGV);
1046 NewGV->setUnnamedAddr(HasUnnamedAddr);
1047 NewGV->setVisibility(Visibility);
1049 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1051 NewGO->setComdat(C);
1054 // Make sure to remember this mapping.
1057 DGV->replaceAllUsesWith(
1058 ConstantExpr::getBitCast(NewGV, DGV->getType()));
1059 DGV->eraseFromParent();
1061 ValueMap[SGV] = NewGV;
1068 /// Loop through the global variables in the src module and merge them into the
1070 GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar,
1073 unsigned Alignment = 0;
1074 bool ClearConstant = false;
1077 if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage())
1078 Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment());
1080 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1081 if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant()))
1082 ClearConstant = true;
1086 if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) {
1088 NewGVar->setAlignment(Alignment);
1089 if (NewGVar->isDeclaration() && ClearConstant)
1090 NewGVar->setConstant(false);
1095 // No linking to be performed or linking from the source: simply create an
1096 // identical version of the symbol over in the dest module... the
1097 // initializer will be filled in later by LinkGlobalInits.
1098 GlobalVariable *NewDGV = new GlobalVariable(
1099 *DstM, TypeMap.get(SGVar->getType()->getElementType()),
1100 SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr,
1101 SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
1102 SGVar->getType()->getAddressSpace());
1105 NewDGV->setAlignment(Alignment);
1110 /// Link the function in the source module into the destination module if
1111 /// needed, setting up mapping information.
1112 GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF,
1118 // If the function is to be lazily linked, don't create it just yet.
1119 // The ValueMaterializerTy will deal with creating it if it's used.
1120 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1121 SF->hasAvailableExternallyLinkage())) {
1122 DoNotLinkFromSource.insert(SF);
1126 // If there is no linkage to be performed or we are linking from the source,
1128 return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(),
1129 SF->getName(), DstM);
1132 /// Set up prototypes for any aliases that come over from the source module.
1133 GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA,
1139 // If there is no linkage to be performed or we're linking from the source,
1141 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1142 return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1143 SGA->getLinkage(), SGA->getName(), DstM);
1146 static void getArrayElements(const Constant *C,
1147 SmallVectorImpl<Constant *> &Dest) {
1148 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1150 for (unsigned i = 0; i != NumElements; ++i)
1151 Dest.push_back(C->getAggregateElement(i));
1154 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1155 // Merge the initializer.
1156 SmallVector<Constant *, 16> DstElements;
1157 getArrayElements(AVI.DstInit, DstElements);
1159 SmallVector<Constant *, 16> SrcElements;
1160 getArrayElements(AVI.SrcInit, SrcElements);
1162 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1164 StringRef Name = AVI.NewGV->getName();
1165 bool IsNewStructor =
1166 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1167 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1169 for (auto *V : SrcElements) {
1170 if (IsNewStructor) {
1171 Constant *Key = V->getAggregateElement(2);
1172 if (DoNotLinkFromSource.count(Key))
1175 DstElements.push_back(
1176 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1178 if (IsNewStructor) {
1179 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1180 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1183 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1186 /// Update the initializers in the Dest module now that all globals that may be
1187 /// referenced are in Dest.
1188 void ModuleLinker::linkGlobalInits() {
1189 // Loop over all of the globals in the src module, mapping them over as we go
1190 for (Module::const_global_iterator I = SrcM->global_begin(),
1191 E = SrcM->global_end(); I != E; ++I) {
1193 // Only process initialized GV's or ones not already in dest.
1194 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1196 // Grab destination global variable.
1197 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1198 // Figure out what the initializer looks like in the dest module.
1199 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1200 RF_None, &TypeMap, &ValMaterializer));
1204 /// Copy the source function over into the dest function and fix up references
1205 /// to values. At this point we know that Dest is an external function, and
1206 /// that Src is not.
1207 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1208 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1210 // Go through and convert function arguments over, remembering the mapping.
1211 Function::arg_iterator DI = Dst->arg_begin();
1212 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1213 I != E; ++I, ++DI) {
1214 DI->setName(I->getName()); // Copy the name over.
1216 // Add a mapping to our mapping.
1220 // Splice the body of the source function into the dest function.
1221 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1223 // At this point, all of the instructions and values of the function are now
1224 // copied over. The only problem is that they are still referencing values in
1225 // the Source function as operands. Loop through all of the operands of the
1226 // functions and patch them up to point to the local versions.
1227 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1229 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap,
1232 // There is no need to map the arguments anymore.
1233 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1239 /// Insert all of the aliases in Src into the Dest module.
1240 void ModuleLinker::linkAliasBodies() {
1241 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1243 if (DoNotLinkFromSource.count(I))
1245 if (Constant *Aliasee = I->getAliasee()) {
1246 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1248 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1249 DA->setAliasee(Val);
1254 /// Insert all of the named MDNodes in Src into the Dest module.
1255 void ModuleLinker::linkNamedMDNodes() {
1256 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1257 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1258 E = SrcM->named_metadata_end(); I != E; ++I) {
1259 // Don't link module flags here. Do them separately.
1260 if (&*I == SrcModFlags) continue;
1261 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1262 // Add Src elements into Dest node.
1263 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1264 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1265 RF_None, &TypeMap, &ValMaterializer));
1269 /// Merge the linker flags in Src into the Dest module.
1270 bool ModuleLinker::linkModuleFlagsMetadata() {
1271 // If the source module has no module flags, we are done.
1272 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1273 if (!SrcModFlags) return false;
1275 // If the destination module doesn't have module flags yet, then just copy
1276 // over the source module's flags.
1277 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1278 if (DstModFlags->getNumOperands() == 0) {
1279 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1280 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1285 // First build a map of the existing module flags and requirements.
1286 DenseMap<MDString*, MDNode*> Flags;
1287 SmallSetVector<MDNode*, 16> Requirements;
1288 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1289 MDNode *Op = DstModFlags->getOperand(I);
1290 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1291 MDString *ID = cast<MDString>(Op->getOperand(1));
1293 if (Behavior->getZExtValue() == Module::Require) {
1294 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1300 // Merge in the flags from the source module, and also collect its set of
1302 bool HasErr = false;
1303 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1304 MDNode *SrcOp = SrcModFlags->getOperand(I);
1305 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1306 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1307 MDNode *DstOp = Flags.lookup(ID);
1308 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1310 // If this is a requirement, add it and continue.
1311 if (SrcBehaviorValue == Module::Require) {
1312 // If the destination module does not already have this requirement, add
1314 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1315 DstModFlags->addOperand(SrcOp);
1320 // If there is no existing flag with this ID, just add it.
1323 DstModFlags->addOperand(SrcOp);
1327 // Otherwise, perform a merge.
1328 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1329 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1331 // If either flag has override behavior, handle it first.
1332 if (DstBehaviorValue == Module::Override) {
1333 // Diagnose inconsistent flags which both have override behavior.
1334 if (SrcBehaviorValue == Module::Override &&
1335 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1336 HasErr |= emitError("linking module flags '" + ID->getString() +
1337 "': IDs have conflicting override values");
1340 } else if (SrcBehaviorValue == Module::Override) {
1341 // Update the destination flag to that of the source.
1342 DstOp->replaceOperandWith(0, SrcBehavior);
1343 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1347 // Diagnose inconsistent merge behavior types.
1348 if (SrcBehaviorValue != DstBehaviorValue) {
1349 HasErr |= emitError("linking module flags '" + ID->getString() +
1350 "': IDs have conflicting behaviors");
1354 // Perform the merge for standard behavior types.
1355 switch (SrcBehaviorValue) {
1356 case Module::Require:
1357 case Module::Override: llvm_unreachable("not possible");
1358 case Module::Error: {
1359 // Emit an error if the values differ.
1360 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1361 HasErr |= emitError("linking module flags '" + ID->getString() +
1362 "': IDs have conflicting values");
1366 case Module::Warning: {
1367 // Emit a warning if the values differ.
1368 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1369 emitWarning("linking module flags '" + ID->getString() +
1370 "': IDs have conflicting values");
1374 case Module::Append: {
1375 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1376 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1377 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1378 Value **VP, **Values = VP = new Value*[NumOps];
1379 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1380 *VP = DstValue->getOperand(i);
1381 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1382 *VP = SrcValue->getOperand(i);
1383 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1384 ArrayRef<Value*>(Values,
1389 case Module::AppendUnique: {
1390 SmallSetVector<Value*, 16> Elts;
1391 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1392 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1393 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1394 Elts.insert(DstValue->getOperand(i));
1395 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1396 Elts.insert(SrcValue->getOperand(i));
1397 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1398 ArrayRef<Value*>(Elts.begin(),
1405 // Check all of the requirements.
1406 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1407 MDNode *Requirement = Requirements[I];
1408 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1409 Value *ReqValue = Requirement->getOperand(1);
1411 MDNode *Op = Flags[Flag];
1412 if (!Op || Op->getOperand(2) != ReqValue) {
1413 HasErr |= emitError("linking module flags '" + Flag->getString() +
1414 "': does not have the required value");
1422 bool ModuleLinker::run() {
1423 assert(DstM && "Null destination module");
1424 assert(SrcM && "Null source module");
1426 // Inherit the target data from the source module if the destination module
1427 // doesn't have one already.
1428 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1429 DstM->setDataLayout(SrcM->getDataLayout());
1431 // Copy the target triple from the source to dest if the dest's is empty.
1432 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1433 DstM->setTargetTriple(SrcM->getTargetTriple());
1435 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1436 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1437 emitWarning("Linking two modules of different data layouts: '" +
1438 SrcM->getModuleIdentifier() + "' is '" +
1439 SrcM->getDataLayoutStr() + "' whereas '" +
1440 DstM->getModuleIdentifier() + "' is '" +
1441 DstM->getDataLayoutStr() + "'\n");
1443 if (!SrcM->getTargetTriple().empty() &&
1444 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1445 emitWarning("Linking two modules of different target triples: " +
1446 SrcM->getModuleIdentifier() + "' is '" +
1447 SrcM->getTargetTriple() + "' whereas '" +
1448 DstM->getModuleIdentifier() + "' is '" +
1449 DstM->getTargetTriple() + "'\n");
1452 // Append the module inline asm string.
1453 if (!SrcM->getModuleInlineAsm().empty()) {
1454 if (DstM->getModuleInlineAsm().empty())
1455 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1457 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1458 SrcM->getModuleInlineAsm());
1461 // Loop over all of the linked values to compute type mappings.
1462 computeTypeMapping();
1464 ComdatsChosen.clear();
1465 for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1466 const Comdat &C = SMEC.getValue();
1467 if (ComdatsChosen.count(&C))
1469 Comdat::SelectionKind SK;
1471 if (getComdatResult(&C, SK, LinkFromSrc))
1473 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1476 // Upgrade mismatched global arrays.
1477 upgradeMismatchedGlobals();
1479 // Insert all of the globals in src into the DstM module... without linking
1480 // initializers (which could refer to functions not yet mapped over).
1481 for (Module::global_iterator I = SrcM->global_begin(),
1482 E = SrcM->global_end(); I != E; ++I)
1483 if (linkGlobalValueProto(I))
1486 // Link the functions together between the two modules, without doing function
1487 // bodies... this just adds external function prototypes to the DstM
1488 // function... We do this so that when we begin processing function bodies,
1489 // all of the global values that may be referenced are available in our
1491 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1492 if (linkGlobalValueProto(I))
1495 // If there were any aliases, link them now.
1496 for (Module::alias_iterator I = SrcM->alias_begin(),
1497 E = SrcM->alias_end(); I != E; ++I)
1498 if (linkGlobalValueProto(I))
1501 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1502 linkAppendingVarInit(AppendingVars[i]);
1504 // Link in the function bodies that are defined in the source module into
1506 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1507 // Skip if not linking from source.
1508 if (DoNotLinkFromSource.count(SF)) continue;
1510 Function *DF = cast<Function>(ValueMap[SF]);
1511 if (SF->hasPrefixData()) {
1512 // Link in the prefix data.
1513 DF->setPrefixData(MapValue(
1514 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1517 // Materialize if needed.
1518 if (std::error_code EC = SF->materialize())
1519 return emitError(EC.message());
1521 // Skip if no body (function is external).
1522 if (SF->isDeclaration())
1525 linkFunctionBody(DF, SF);
1526 SF->Dematerialize();
1529 // Resolve all uses of aliases with aliasees.
1532 // Remap all of the named MDNodes in Src into the DstM module. We do this
1533 // after linking GlobalValues so that MDNodes that reference GlobalValues
1534 // are properly remapped.
1537 // Merge the module flags into the DstM module.
1538 if (linkModuleFlagsMetadata())
1541 // Update the initializers in the DstM module now that all globals that may
1542 // be referenced are in DstM.
1545 // Process vector of lazily linked in functions.
1546 bool LinkedInAnyFunctions;
1548 LinkedInAnyFunctions = false;
1550 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1551 E = LazilyLinkFunctions.end(); I != E; ++I) {
1556 Function *DF = cast<Function>(ValueMap[SF]);
1557 if (SF->hasPrefixData()) {
1558 // Link in the prefix data.
1559 DF->setPrefixData(MapValue(SF->getPrefixData(),
1566 // Materialize if needed.
1567 if (std::error_code EC = SF->materialize())
1568 return emitError(EC.message());
1570 // Skip if no body (function is external).
1571 if (SF->isDeclaration())
1574 // Erase from vector *before* the function body is linked - linkFunctionBody could
1576 LazilyLinkFunctions.erase(I);
1578 // Link in function body.
1579 linkFunctionBody(DF, SF);
1580 SF->Dematerialize();
1582 // Set flag to indicate we may have more functions to lazily link in
1583 // since we linked in a function.
1584 LinkedInAnyFunctions = true;
1587 } while (LinkedInAnyFunctions);
1589 // Now that all of the types from the source are used, resolve any structs
1590 // copied over to the dest that didn't exist there.
1591 TypeMap.linkDefinedTypeBodies();
1596 void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1597 this->Composite = M;
1598 this->DiagnosticHandler = DiagnosticHandler;
1600 TypeFinder StructTypes;
1601 StructTypes.run(*M, true);
1602 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1605 Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
1606 init(M, DiagnosticHandler);
1609 Linker::Linker(Module *M) {
1610 init(M, [this](const DiagnosticInfo &DI) {
1611 Composite->getContext().diagnose(DI);
1618 void Linker::deleteModule() {
1620 Composite = nullptr;
1623 bool Linker::linkInModule(Module *Src) {
1624 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1626 return TheLinker.run();
1629 //===----------------------------------------------------------------------===//
1630 // LinkModules entrypoint.
1631 //===----------------------------------------------------------------------===//
1633 /// This function links two modules together, with the resulting Dest module
1634 /// modified to be the composite of the two input modules. If an error occurs,
1635 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1636 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1637 /// relied on to be consistent.
1638 bool Linker::LinkModules(Module *Dest, Module *Src,
1639 DiagnosticHandlerFunction DiagnosticHandler) {
1640 Linker L(Dest, DiagnosticHandler);
1641 return L.linkInModule(Src);
1644 bool Linker::LinkModules(Module *Dest, Module *Src) {
1646 return L.linkInModule(Src);
1649 //===----------------------------------------------------------------------===//
1651 //===----------------------------------------------------------------------===//
1653 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1654 LLVMLinkerMode Mode, char **OutMessages) {
1655 Module *D = unwrap(Dest);
1656 std::string Message;
1657 raw_string_ostream Stream(Message);
1658 DiagnosticPrinterRawOStream DP(Stream);
1660 LLVMBool Result = Linker::LinkModules(
1661 D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
1663 if (OutMessages && Result)
1664 *OutMessages = strdup(Message.c_str());