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/Module.h"
21 #include "llvm/IR/TypeFinder.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
31 //===----------------------------------------------------------------------===//
32 // TypeMap implementation.
33 //===----------------------------------------------------------------------===//
36 typedef SmallPtrSet<StructType*, 32> TypeSet;
38 class TypeMapTy : public ValueMapTypeRemapper {
39 /// MappedTypes - This is a mapping from a source type to a destination type
41 DenseMap<Type*, Type*> MappedTypes;
43 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
44 /// we speculatively add types to MappedTypes, but keep track of them here in
45 /// case we need to roll back.
46 SmallVector<Type*, 16> SpeculativeTypes;
48 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
49 /// source module that are mapped to an opaque struct in the destination
51 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
53 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
54 /// destination modules who are getting a body from the source module.
55 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
58 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
60 TypeSet &DstStructTypesSet;
61 /// addTypeMapping - Indicate that the specified type in the destination
62 /// module is conceptually equivalent to the specified type in the source
64 void addTypeMapping(Type *DstTy, Type *SrcTy);
66 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
67 /// module from a type definition in the source module.
68 void linkDefinedTypeBodies();
70 /// get - 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 - 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 /// remapType - 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 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
120 /// if they are isomorphic, 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)))
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 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
205 /// module from a type definition in the source module.
206 void TypeMapTy::linkDefinedTypeBodies() {
207 SmallVector<Type*, 16> Elements;
208 SmallString<16> TmpName;
210 // Note that processing entries in this loop (calling 'get') can add new
211 // entries to the SrcDefinitionsToResolve vector.
212 while (!SrcDefinitionsToResolve.empty()) {
213 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
214 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
216 // TypeMap is a many-to-one mapping, if there were multiple types that
217 // provide a body for DstSTy then previous iterations of this loop may have
218 // already handled it. Just ignore this case.
219 if (!DstSTy->isOpaque()) continue;
220 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
222 // Map the body of the source type over to a new body for the dest type.
223 Elements.resize(SrcSTy->getNumElements());
224 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
225 Elements[i] = getImpl(SrcSTy->getElementType(i));
227 DstSTy->setBody(Elements, SrcSTy->isPacked());
229 // If DstSTy has no name or has a longer name than STy, then viciously steal
231 if (!SrcSTy->hasName()) continue;
232 StringRef SrcName = SrcSTy->getName();
234 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
235 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
237 DstSTy->setName(TmpName.str());
242 DstResolvedOpaqueTypes.clear();
245 /// get - Return the mapped type to use for the specified input type from the
247 Type *TypeMapTy::get(Type *Ty) {
248 Type *Result = getImpl(Ty);
250 // If this caused a reference to any struct type, resolve it before returning.
251 if (!SrcDefinitionsToResolve.empty())
252 linkDefinedTypeBodies();
256 /// getImpl - This is the recursive version of get().
257 Type *TypeMapTy::getImpl(Type *Ty) {
258 // If we already have an entry for this type, return it.
259 Type **Entry = &MappedTypes[Ty];
260 if (*Entry) return *Entry;
262 // If this is not a named struct type, then just map all of the elements and
263 // then rebuild the type from inside out.
264 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
265 // If there are no element types to map, then the type is itself. This is
266 // true for the anonymous {} struct, things like 'float', integers, etc.
267 if (Ty->getNumContainedTypes() == 0)
270 // Remap all of the elements, keeping track of whether any of them change.
271 bool AnyChange = false;
272 SmallVector<Type*, 4> ElementTypes;
273 ElementTypes.resize(Ty->getNumContainedTypes());
274 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
275 ElementTypes[i] = getImpl(Ty->getContainedType(i));
276 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
279 // If we found our type while recursively processing stuff, just use it.
280 Entry = &MappedTypes[Ty];
281 if (*Entry) return *Entry;
283 // If all of the element types mapped directly over, then the type is usable
288 // Otherwise, rebuild a modified type.
289 switch (Ty->getTypeID()) {
290 default: llvm_unreachable("unknown derived type to remap");
291 case Type::ArrayTyID:
292 return *Entry = ArrayType::get(ElementTypes[0],
293 cast<ArrayType>(Ty)->getNumElements());
294 case Type::VectorTyID:
295 return *Entry = VectorType::get(ElementTypes[0],
296 cast<VectorType>(Ty)->getNumElements());
297 case Type::PointerTyID:
298 return *Entry = PointerType::get(ElementTypes[0],
299 cast<PointerType>(Ty)->getAddressSpace());
300 case Type::FunctionTyID:
301 return *Entry = FunctionType::get(ElementTypes[0],
302 makeArrayRef(ElementTypes).slice(1),
303 cast<FunctionType>(Ty)->isVarArg());
304 case Type::StructTyID:
305 // Note that this is only reached for anonymous structs.
306 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
307 cast<StructType>(Ty)->isPacked());
311 // Otherwise, this is an unmapped named struct. If the struct can be directly
312 // mapped over, just use it as-is. This happens in a case when the linked-in
313 // module has something like:
314 // %T = type {%T*, i32}
315 // @GV = global %T* null
316 // where T does not exist at all in the destination module.
318 // The other case we watch for is when the type is not in the destination
319 // module, but that it has to be rebuilt because it refers to something that
320 // is already mapped. For example, if the destination module has:
322 // and the source module has something like
323 // %A' = type { i32 }
324 // %B = type { %A'* }
325 // @GV = global %B* null
326 // then we want to create a new type: "%B = type { %A*}" and have it take the
327 // pristine "%B" name from the source module.
329 // To determine which case this is, we have to recursively walk the type graph
330 // speculating that we'll be able to reuse it unmodified. Only if this is
331 // safe would we map the entire thing over. Because this is an optimization,
332 // and is not required for the prettiness of the linked module, we just skip
333 // it and always rebuild a type here.
334 StructType *STy = cast<StructType>(Ty);
336 // If the type is opaque, we can just use it directly.
337 if (STy->isOpaque()) {
338 // A named structure type from src module is used. Add it to the Set of
339 // identified structs in the destination module.
340 DstStructTypesSet.insert(STy);
344 // Otherwise we create a new type and resolve its body later. This will be
345 // resolved by the top level of get().
346 SrcDefinitionsToResolve.push_back(STy);
347 StructType *DTy = StructType::create(STy->getContext());
348 // A new identified structure type was created. Add it to the set of
349 // identified structs in the destination module.
350 DstStructTypesSet.insert(DTy);
351 DstResolvedOpaqueTypes.insert(DTy);
355 //===----------------------------------------------------------------------===//
356 // ModuleLinker implementation.
357 //===----------------------------------------------------------------------===//
362 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
363 /// linked on the fly. This speeds up linking for modules with many
364 /// lazily linked functions of which few get used.
365 class ValueMaterializerTy : public ValueMaterializer {
368 std::vector<Function*> &LazilyLinkFunctions;
370 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
371 std::vector<Function*> &LazilyLinkFunctions) :
372 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
373 LazilyLinkFunctions(LazilyLinkFunctions) {
376 Value *materializeValueFor(Value *V) override;
379 /// ModuleLinker - This is an implementation class for the LinkModules
380 /// function, which is the entrypoint for this file.
385 ValueMaterializerTy ValMaterializer;
387 /// ValueMap - Mapping of values from what they used to be in Src, to what
388 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
389 /// some overhead due to the use of Value handles which the Linker doesn't
390 /// actually need, but this allows us to reuse the ValueMapper code.
391 ValueToValueMapTy ValueMap;
393 struct AppendingVarInfo {
394 GlobalVariable *NewGV; // New aggregate global in dest module.
395 Constant *DstInit; // Old initializer from dest module.
396 Constant *SrcInit; // Old initializer from src module.
399 std::vector<AppendingVarInfo> AppendingVars;
401 unsigned Mode; // Mode to treat source module.
403 // Set of items not to link in from source.
404 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
406 // Vector of functions to lazily link in.
407 std::vector<Function*> LazilyLinkFunctions;
409 bool SuppressWarnings;
412 std::string ErrorMsg;
414 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
415 bool SuppressWarnings=false)
416 : DstM(dstM), SrcM(srcM), TypeMap(Set),
417 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
418 SuppressWarnings(SuppressWarnings) {}
423 /// emitError - Helper method for setting a message and returning an error
425 bool emitError(const Twine &Message) {
426 ErrorMsg = Message.str();
430 bool getComdatLeader(Module *M, StringRef ComdatName,
431 const GlobalVariable *&GVar);
432 bool computeResultingSelectionKind(StringRef ComdatName,
433 Comdat::SelectionKind Src,
434 Comdat::SelectionKind Dst,
435 Comdat::SelectionKind &Result,
437 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
439 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
442 /// getLinkageResult - This analyzes the two global values and determines
443 /// what the result will look like in the destination module.
444 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
445 GlobalValue::LinkageTypes <,
446 GlobalValue::VisibilityTypes &Vis,
449 /// getLinkedToGlobal - Given a global in the source module, return the
450 /// global in the destination module that is being linked to, if any.
451 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
452 // If the source has no name it can't link. If it has local linkage,
453 // there is no name match-up going on.
454 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
457 // Otherwise see if we have a match in the destination module's symtab.
458 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
459 if (!DGV) return nullptr;
461 // If we found a global with the same name in the dest module, but it has
462 // internal linkage, we are really not doing any linkage here.
463 if (DGV->hasLocalLinkage())
466 // Otherwise, we do in fact link to the destination global.
470 void computeTypeMapping();
472 void upgradeMismatchedGlobalArray(StringRef Name);
473 void upgradeMismatchedGlobals();
475 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
476 bool linkGlobalProto(GlobalVariable *SrcGV);
477 bool linkFunctionProto(Function *SrcF);
478 bool linkAliasProto(GlobalAlias *SrcA);
479 bool linkModuleFlagsMetadata();
481 void linkAppendingVarInit(const AppendingVarInfo &AVI);
482 void linkGlobalInits();
483 void linkFunctionBody(Function *Dst, Function *Src);
484 void linkAliasBodies();
485 void linkNamedMDNodes();
489 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
490 /// in the symbol table. This is good for all clients except for us. Go
491 /// through the trouble to force this back.
492 static void forceRenaming(GlobalValue *GV, StringRef Name) {
493 // If the global doesn't force its name or if it already has the right name,
494 // there is nothing for us to do.
495 if (GV->hasLocalLinkage() || GV->getName() == Name)
498 Module *M = GV->getParent();
500 // If there is a conflict, rename the conflict.
501 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
502 GV->takeName(ConflictGV);
503 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
504 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
506 GV->setName(Name); // Force the name back
510 /// copyGVAttributes - copy additional attributes (those not needed to construct
511 /// a GlobalValue) from the SrcGV to the DestGV.
512 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
513 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
514 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
517 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
519 DestGV->copyAttributesFrom(SrcGV);
522 DestGO->setAlignment(Alignment);
524 forceRenaming(DestGV, SrcGV->getName());
527 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
528 GlobalValue::VisibilityTypes b) {
529 if (a == GlobalValue::HiddenVisibility)
531 if (b == GlobalValue::HiddenVisibility)
533 if (a == GlobalValue::ProtectedVisibility)
535 if (b == GlobalValue::ProtectedVisibility)
540 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
541 Function *SF = dyn_cast<Function>(V);
545 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
546 SF->getLinkage(), SF->getName(), DstM);
547 copyGVAttributes(DF, SF);
549 if (Comdat *SC = SF->getComdat()) {
550 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
554 LazilyLinkFunctions.push_back(SF);
558 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
559 const GlobalVariable *&GVar) {
560 const GlobalValue *GVal = M->getNamedValue(ComdatName);
561 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
562 GVal = GA->getBaseObject();
564 // We cannot resolve the size of the aliasee yet.
565 return emitError("Linking COMDATs named '" + ComdatName +
566 "': COMDAT key involves incomputable alias size.");
569 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
572 "Linking COMDATs named '" + ComdatName +
573 "': GlobalVariable required for data dependent selection!");
578 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
579 Comdat::SelectionKind Src,
580 Comdat::SelectionKind Dst,
581 Comdat::SelectionKind &Result,
583 // The ability to mix Comdat::SelectionKind::Any with
584 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
585 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
586 Dst == Comdat::SelectionKind::Largest;
587 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
588 Src == Comdat::SelectionKind::Largest;
589 if (DstAnyOrLargest && SrcAnyOrLargest) {
590 if (Dst == Comdat::SelectionKind::Largest ||
591 Src == Comdat::SelectionKind::Largest)
592 Result = Comdat::SelectionKind::Largest;
594 Result = Comdat::SelectionKind::Any;
595 } else if (Src == Dst) {
598 return emitError("Linking COMDATs named '" + ComdatName +
599 "': invalid selection kinds!");
603 case Comdat::SelectionKind::Any:
607 case Comdat::SelectionKind::NoDuplicates:
608 return emitError("Linking COMDATs named '" + ComdatName +
609 "': noduplicates has been violated!");
610 case Comdat::SelectionKind::ExactMatch:
611 case Comdat::SelectionKind::Largest:
612 case Comdat::SelectionKind::SameSize: {
613 const GlobalVariable *DstGV;
614 const GlobalVariable *SrcGV;
615 if (getComdatLeader(DstM, ComdatName, DstGV) ||
616 getComdatLeader(SrcM, ComdatName, SrcGV))
619 const DataLayout *DstDL = DstM->getDataLayout();
620 const DataLayout *SrcDL = SrcM->getDataLayout();
621 if (!DstDL || !SrcDL) {
623 "Linking COMDATs named '" + ComdatName +
624 "': can't do size dependent selection without DataLayout!");
627 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
629 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
630 if (Result == Comdat::SelectionKind::ExactMatch) {
631 if (SrcGV->getInitializer() != DstGV->getInitializer())
632 return emitError("Linking COMDATs named '" + ComdatName +
633 "': ExactMatch violated!");
635 } else if (Result == Comdat::SelectionKind::Largest) {
636 LinkFromSrc = SrcSize > DstSize;
637 } else if (Result == Comdat::SelectionKind::SameSize) {
638 if (SrcSize != DstSize)
639 return emitError("Linking COMDATs named '" + ComdatName +
640 "': SameSize violated!");
643 llvm_unreachable("unknown selection kind");
652 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
653 Comdat::SelectionKind &Result,
655 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
656 StringRef ComdatName = SrcC->getName();
657 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
658 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
660 if (DstCI == ComdatSymTab.end()) {
661 // Use the comdat if it is only available in one of the modules.
667 const Comdat *DstC = &DstCI->second;
668 Comdat::SelectionKind DSK = DstC->getSelectionKind();
669 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
673 // FIXME: Duplicated from the gold plugin. This should be refactored somewhere.
674 static bool isDeclaration(const GlobalValue &V) {
675 if (V.hasAvailableExternallyLinkage())
678 if (V.isMaterializable())
681 return V.isDeclaration();
684 /// This analyzes the two global values and determines what the result will look
685 /// like in the destination module. In particular, it computes the resultant
686 /// linkage type and visibility, computes whether the global in the source
687 /// should be copied over to the destination (replacing the existing one), and
688 /// computes whether this linkage is an error or not.
689 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
690 GlobalValue::LinkageTypes <,
691 GlobalValue::VisibilityTypes &Vis,
693 assert(Dest && "Must have two globals being queried");
694 assert(!Src->hasLocalLinkage() &&
695 "If Src has internal linkage, Dest shouldn't be set!");
697 bool SrcIsDeclaration = isDeclaration(*Src);
698 bool DestIsDeclaration = isDeclaration(*Dest);
700 if (SrcIsDeclaration) {
701 // If Src is external or if both Src & Dest are external.. Just link the
702 // external globals, we aren't adding anything.
703 if (Src->hasDLLImportStorageClass()) {
704 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
705 if (DestIsDeclaration) {
707 LT = Src->getLinkage();
709 } else if (Dest->hasExternalWeakLinkage()) {
710 // If the Dest is weak, use the source linkage.
712 LT = Src->getLinkage();
715 LT = Dest->getLinkage();
717 } else if (DestIsDeclaration) {
718 // If Dest is external but Src is not:
720 LT = Src->getLinkage();
721 } else if (Src->isWeakForLinker()) {
722 assert(!Dest->hasExternalWeakLinkage());
723 assert(!Dest->hasAvailableExternallyLinkage());
724 if ((Dest->hasLinkOnceLinkage() && Src->hasWeakLinkage()) ||
725 ((Dest->hasLinkOnceLinkage() || Dest->hasWeakLinkage()) &&
726 Src->hasCommonLinkage())) {
728 LT = Src->getLinkage();
731 LT = Dest->getLinkage();
733 } else if (Dest->isWeakForLinker()) {
734 assert(!Src->hasExternalWeakLinkage());
736 LT = GlobalValue::ExternalLinkage;
738 assert(!Src->hasExternalWeakLinkage());
739 assert(!Dest->hasExternalWeakLinkage());
740 assert(Dest->hasExternalLinkage() && Src->hasExternalLinkage() &&
741 "Unexpected linkage type!");
742 return emitError("Linking globals named '" + Src->getName() +
743 "': symbol multiply defined!");
746 // Compute the visibility. We follow the rules in the System V Application
748 assert(!GlobalValue::isLocalLinkage(LT) &&
749 "Symbols with local linkage should not be merged");
750 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
751 Dest->getVisibility() : Src->getVisibility();
755 /// computeTypeMapping - Loop over all of the linked values to compute type
756 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
757 /// we have two struct types 'Foo' but one got renamed when the module was
758 /// loaded into the same LLVMContext.
759 void ModuleLinker::computeTypeMapping() {
760 // Incorporate globals.
761 for (Module::global_iterator I = SrcM->global_begin(),
762 E = SrcM->global_end(); I != E; ++I) {
763 GlobalValue *DGV = getLinkedToGlobal(I);
766 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
767 TypeMap.addTypeMapping(DGV->getType(), I->getType());
771 // Unify the element type of appending arrays.
772 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
773 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
774 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
777 // Incorporate functions.
778 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
779 if (GlobalValue *DGV = getLinkedToGlobal(I))
780 TypeMap.addTypeMapping(DGV->getType(), I->getType());
783 // Incorporate types by name, scanning all the types in the source module.
784 // At this point, the destination module may have a type "%foo = { i32 }" for
785 // example. When the source module got loaded into the same LLVMContext, if
786 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
787 TypeFinder SrcStructTypes;
788 SrcStructTypes.run(*SrcM, true);
789 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
790 SrcStructTypes.end());
792 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
793 StructType *ST = SrcStructTypes[i];
794 if (!ST->hasName()) continue;
796 // Check to see if there is a dot in the name followed by a digit.
797 size_t DotPos = ST->getName().rfind('.');
798 if (DotPos == 0 || DotPos == StringRef::npos ||
799 ST->getName().back() == '.' ||
800 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
803 // Check to see if the destination module has a struct with the prefix name.
804 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
805 // Don't use it if this actually came from the source module. They're in
806 // the same LLVMContext after all. Also don't use it unless the type is
807 // actually used in the destination module. This can happen in situations
812 // %Z = type { %A } %B = type { %C.1 }
813 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
814 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
815 // %C = type { i8* } %B.3 = type { %C.1 }
817 // When we link Module B with Module A, the '%B' in Module B is
818 // used. However, that would then use '%C.1'. But when we process '%C.1',
819 // we prefer to take the '%C' version. So we are then left with both
820 // '%C.1' and '%C' being used for the same types. This leads to some
821 // variables using one type and some using the other.
822 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
823 TypeMap.addTypeMapping(DST, ST);
826 // Don't bother incorporating aliases, they aren't generally typed well.
828 // Now that we have discovered all of the type equivalences, get a body for
829 // any 'opaque' types in the dest module that are now resolved.
830 TypeMap.linkDefinedTypeBodies();
833 static void upgradeGlobalArray(GlobalVariable *GV) {
834 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
835 StructType *OldTy = cast<StructType>(ATy->getElementType());
836 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
838 // Get the upgraded 3 element type.
839 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
840 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
842 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
844 // Build new constants with a null third field filled in.
845 Constant *OldInitC = GV->getInitializer();
846 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
847 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
848 // Invalid initializer; give up.
850 std::vector<Constant *> Initializers;
851 if (OldInit && OldInit->getNumOperands()) {
852 Value *Null = Constant::getNullValue(VoidPtrTy);
853 for (Use &U : OldInit->operands()) {
854 ConstantStruct *Init = cast<ConstantStruct>(U.get());
855 Initializers.push_back(ConstantStruct::get(
856 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
859 assert(Initializers.size() == ATy->getNumElements() &&
860 "Failed to copy all array elements");
862 // Replace the old GV with a new one.
863 ATy = ArrayType::get(NewTy, Initializers.size());
864 Constant *NewInit = ConstantArray::get(ATy, Initializers);
865 GlobalVariable *NewGV = new GlobalVariable(
866 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
867 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
868 GV->isExternallyInitialized());
869 NewGV->copyAttributesFrom(GV);
871 assert(GV->use_empty() && "program cannot use initializer list");
872 GV->eraseFromParent();
875 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
876 // Look for the global arrays.
877 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
880 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
884 // Check if the types already match.
885 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
887 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
891 // Grab the element types. We can only upgrade an array of a two-field
892 // struct. Only bother if the other one has three-fields.
893 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
894 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
895 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
896 upgradeGlobalArray(DstGV);
899 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
900 upgradeGlobalArray(SrcGV);
902 // We can't upgrade any other differences.
905 void ModuleLinker::upgradeMismatchedGlobals() {
906 upgradeMismatchedGlobalArray("llvm.global_ctors");
907 upgradeMismatchedGlobalArray("llvm.global_dtors");
910 /// linkAppendingVarProto - If there were any appending global variables, link
911 /// them together now. Return true on error.
912 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
913 GlobalVariable *SrcGV) {
915 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
916 return emitError("Linking globals named '" + SrcGV->getName() +
917 "': can only link appending global with another appending global!");
919 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
921 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
922 Type *EltTy = DstTy->getElementType();
924 // Check to see that they two arrays agree on type.
925 if (EltTy != SrcTy->getElementType())
926 return emitError("Appending variables with different element types!");
927 if (DstGV->isConstant() != SrcGV->isConstant())
928 return emitError("Appending variables linked with different const'ness!");
930 if (DstGV->getAlignment() != SrcGV->getAlignment())
932 "Appending variables with different alignment need to be linked!");
934 if (DstGV->getVisibility() != SrcGV->getVisibility())
936 "Appending variables with different visibility need to be linked!");
938 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
940 "Appending variables with different unnamed_addr need to be linked!");
942 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
944 "Appending variables with different section name need to be linked!");
946 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
947 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
949 // Create the new global variable.
951 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
952 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
953 DstGV->getThreadLocalMode(),
954 DstGV->getType()->getAddressSpace());
956 // Propagate alignment, visibility and section info.
957 copyGVAttributes(NG, DstGV);
959 AppendingVarInfo AVI;
961 AVI.DstInit = DstGV->getInitializer();
962 AVI.SrcInit = SrcGV->getInitializer();
963 AppendingVars.push_back(AVI);
965 // Replace any uses of the two global variables with uses of the new
967 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
969 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
970 DstGV->eraseFromParent();
972 // Track the source variable so we don't try to link it.
973 DoNotLinkFromSource.insert(SrcGV);
978 /// linkGlobalProto - Loop through the global variables in the src module and
979 /// merge them into the dest module.
980 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
981 GlobalValue *DGV = getLinkedToGlobal(SGV);
982 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
983 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
985 bool LinkFromSrc = false;
986 Comdat *DC = nullptr;
987 if (const Comdat *SC = SGV->getComdat()) {
988 Comdat::SelectionKind SK;
989 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
990 DC = DstM->getOrInsertComdat(SC->getName());
991 DC->setSelectionKind(SK);
996 // Concatenation of appending linkage variables is magic and handled later.
997 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
998 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
1000 // Determine whether linkage of these two globals follows the source
1001 // module's definition or the destination module's definition.
1002 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1003 GlobalValue::VisibilityTypes NV;
1004 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1007 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1009 // If we're not linking from the source, then keep the definition that we
1012 // Special case for const propagation.
1013 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
1014 if (DGVar->isDeclaration() && SGV->isConstant() &&
1015 !DGVar->isConstant())
1016 DGVar->setConstant(true);
1018 // Set calculated linkage, visibility and unnamed_addr.
1019 DGV->setLinkage(NewLinkage);
1020 DGV->setVisibility(*NewVisibility);
1021 DGV->setUnnamedAddr(HasUnnamedAddr);
1026 // Make sure to remember this mapping.
1027 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
1029 // Track the source global so that we don't attempt to copy it over when
1030 // processing global initializers.
1031 DoNotLinkFromSource.insert(SGV);
1037 // If the Comdat this variable was inside of wasn't selected, skip it.
1038 if (DC && !DGV && !LinkFromSrc) {
1039 DoNotLinkFromSource.insert(SGV);
1043 // No linking to be performed or linking from the source: simply create an
1044 // identical version of the symbol over in the dest module... the
1045 // initializer will be filled in later by LinkGlobalInits.
1046 GlobalVariable *NewDGV =
1047 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
1048 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
1049 SGV->getName(), /*insertbefore*/nullptr,
1050 SGV->getThreadLocalMode(),
1051 SGV->getType()->getAddressSpace());
1052 // Propagate alignment, visibility and section info.
1053 copyGVAttributes(NewDGV, SGV);
1055 NewDGV->setVisibility(*NewVisibility);
1056 NewDGV->setUnnamedAddr(HasUnnamedAddr);
1059 NewDGV->setComdat(DC);
1062 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1063 DGV->eraseFromParent();
1066 // Make sure to remember this mapping.
1067 ValueMap[SGV] = NewDGV;
1071 /// linkFunctionProto - Link the function in the source module into the
1072 /// destination module if needed, setting up mapping information.
1073 bool ModuleLinker::linkFunctionProto(Function *SF) {
1074 GlobalValue *DGV = getLinkedToGlobal(SF);
1075 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1076 bool HasUnnamedAddr = SF->hasUnnamedAddr();
1078 bool LinkFromSrc = false;
1079 Comdat *DC = nullptr;
1080 if (const Comdat *SC = SF->getComdat()) {
1081 Comdat::SelectionKind SK;
1082 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1083 DC = DstM->getOrInsertComdat(SC->getName());
1084 DC->setSelectionKind(SK);
1089 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1090 GlobalValue::VisibilityTypes NV;
1091 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
1094 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1097 // Set calculated linkage
1098 DGV->setLinkage(NewLinkage);
1099 DGV->setVisibility(*NewVisibility);
1100 DGV->setUnnamedAddr(HasUnnamedAddr);
1105 // Make sure to remember this mapping.
1106 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
1108 // Track the function from the source module so we don't attempt to remap
1110 DoNotLinkFromSource.insert(SF);
1116 // If the function is to be lazily linked, don't create it just yet.
1117 // The ValueMaterializerTy will deal with creating it if it's used.
1118 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1119 SF->hasAvailableExternallyLinkage())) {
1120 DoNotLinkFromSource.insert(SF);
1124 // If the Comdat this function was inside of wasn't selected, skip it.
1125 if (DC && !DGV && !LinkFromSrc) {
1126 DoNotLinkFromSource.insert(SF);
1130 // If there is no linkage to be performed or we are linking from the source,
1132 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1133 SF->getLinkage(), SF->getName(), DstM);
1134 copyGVAttributes(NewDF, SF);
1136 NewDF->setVisibility(*NewVisibility);
1137 NewDF->setUnnamedAddr(HasUnnamedAddr);
1140 NewDF->setComdat(DC);
1143 // Any uses of DF need to change to NewDF, with cast.
1144 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1145 DGV->eraseFromParent();
1148 ValueMap[SF] = NewDF;
1152 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
1154 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1155 GlobalValue *DGV = getLinkedToGlobal(SGA);
1156 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1157 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
1159 bool LinkFromSrc = false;
1160 Comdat *DC = nullptr;
1161 if (const Comdat *SC = SGA->getComdat()) {
1162 Comdat::SelectionKind SK;
1163 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1164 DC = DstM->getOrInsertComdat(SC->getName());
1165 DC->setSelectionKind(SK);
1170 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1171 GlobalValue::VisibilityTypes NV;
1172 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1175 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1178 // Set calculated linkage.
1179 DGV->setLinkage(NewLinkage);
1180 DGV->setVisibility(*NewVisibility);
1181 DGV->setUnnamedAddr(HasUnnamedAddr);
1186 // Make sure to remember this mapping.
1187 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
1189 // Track the alias from the source module so we don't attempt to remap it.
1190 DoNotLinkFromSource.insert(SGA);
1196 // If the Comdat this alias was inside of wasn't selected, skip it.
1197 if (DC && !DGV && !LinkFromSrc) {
1198 DoNotLinkFromSource.insert(SGA);
1202 // If there is no linkage to be performed or we're linking from the source,
1204 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1206 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1207 SGA->getLinkage(), SGA->getName(), DstM);
1208 copyGVAttributes(NewDA, SGA);
1210 NewDA->setVisibility(*NewVisibility);
1211 NewDA->setUnnamedAddr(HasUnnamedAddr);
1214 // Any uses of DGV need to change to NewDA, with cast.
1215 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1216 DGV->eraseFromParent();
1219 ValueMap[SGA] = NewDA;
1223 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
1224 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1226 for (unsigned i = 0; i != NumElements; ++i)
1227 Dest.push_back(C->getAggregateElement(i));
1230 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1231 // Merge the initializer.
1232 SmallVector<Constant *, 16> DstElements;
1233 getArrayElements(AVI.DstInit, DstElements);
1235 SmallVector<Constant *, 16> SrcElements;
1236 getArrayElements(AVI.SrcInit, SrcElements);
1238 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1240 StringRef Name = AVI.NewGV->getName();
1241 bool IsNewStructor =
1242 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1243 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1245 for (auto *V : SrcElements) {
1246 if (IsNewStructor) {
1247 Constant *Key = V->getAggregateElement(2);
1248 if (DoNotLinkFromSource.count(Key))
1251 DstElements.push_back(
1252 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1254 if (IsNewStructor) {
1255 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1256 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1259 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1262 /// linkGlobalInits - Update the initializers in the Dest module now that all
1263 /// globals that may be referenced are in Dest.
1264 void ModuleLinker::linkGlobalInits() {
1265 // Loop over all of the globals in the src module, mapping them over as we go
1266 for (Module::const_global_iterator I = SrcM->global_begin(),
1267 E = SrcM->global_end(); I != E; ++I) {
1269 // Only process initialized GV's or ones not already in dest.
1270 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1272 // Grab destination global variable.
1273 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1274 // Figure out what the initializer looks like in the dest module.
1275 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1276 RF_None, &TypeMap, &ValMaterializer));
1280 /// linkFunctionBody - Copy the source function over into the dest function and
1281 /// fix up references to values. At this point we know that Dest is an external
1282 /// function, and that Src is not.
1283 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1284 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1286 // Go through and convert function arguments over, remembering the mapping.
1287 Function::arg_iterator DI = Dst->arg_begin();
1288 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1289 I != E; ++I, ++DI) {
1290 DI->setName(I->getName()); // Copy the name over.
1292 // Add a mapping to our mapping.
1296 if (Mode == Linker::DestroySource) {
1297 // Splice the body of the source function into the dest function.
1298 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1300 // At this point, all of the instructions and values of the function are now
1301 // copied over. The only problem is that they are still referencing values in
1302 // the Source function as operands. Loop through all of the operands of the
1303 // functions and patch them up to point to the local versions.
1304 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1305 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1306 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1307 &TypeMap, &ValMaterializer);
1310 // Clone the body of the function into the dest function.
1311 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1312 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1313 &TypeMap, &ValMaterializer);
1316 // There is no need to map the arguments anymore.
1317 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1323 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1324 void ModuleLinker::linkAliasBodies() {
1325 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1327 if (DoNotLinkFromSource.count(I))
1329 if (Constant *Aliasee = I->getAliasee()) {
1330 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1332 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1333 DA->setAliasee(Val);
1338 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1340 void ModuleLinker::linkNamedMDNodes() {
1341 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1342 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1343 E = SrcM->named_metadata_end(); I != E; ++I) {
1344 // Don't link module flags here. Do them separately.
1345 if (&*I == SrcModFlags) continue;
1346 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1347 // Add Src elements into Dest node.
1348 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1349 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1350 RF_None, &TypeMap, &ValMaterializer));
1354 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1356 bool ModuleLinker::linkModuleFlagsMetadata() {
1357 // If the source module has no module flags, we are done.
1358 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1359 if (!SrcModFlags) return false;
1361 // If the destination module doesn't have module flags yet, then just copy
1362 // over the source module's flags.
1363 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1364 if (DstModFlags->getNumOperands() == 0) {
1365 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1366 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1371 // First build a map of the existing module flags and requirements.
1372 DenseMap<MDString*, MDNode*> Flags;
1373 SmallSetVector<MDNode*, 16> Requirements;
1374 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1375 MDNode *Op = DstModFlags->getOperand(I);
1376 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1377 MDString *ID = cast<MDString>(Op->getOperand(1));
1379 if (Behavior->getZExtValue() == Module::Require) {
1380 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1386 // Merge in the flags from the source module, and also collect its set of
1388 bool HasErr = false;
1389 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1390 MDNode *SrcOp = SrcModFlags->getOperand(I);
1391 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1392 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1393 MDNode *DstOp = Flags.lookup(ID);
1394 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1396 // If this is a requirement, add it and continue.
1397 if (SrcBehaviorValue == Module::Require) {
1398 // If the destination module does not already have this requirement, add
1400 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1401 DstModFlags->addOperand(SrcOp);
1406 // If there is no existing flag with this ID, just add it.
1409 DstModFlags->addOperand(SrcOp);
1413 // Otherwise, perform a merge.
1414 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1415 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1417 // If either flag has override behavior, handle it first.
1418 if (DstBehaviorValue == Module::Override) {
1419 // Diagnose inconsistent flags which both have override behavior.
1420 if (SrcBehaviorValue == Module::Override &&
1421 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1422 HasErr |= emitError("linking module flags '" + ID->getString() +
1423 "': IDs have conflicting override values");
1426 } else if (SrcBehaviorValue == Module::Override) {
1427 // Update the destination flag to that of the source.
1428 DstOp->replaceOperandWith(0, SrcBehavior);
1429 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1433 // Diagnose inconsistent merge behavior types.
1434 if (SrcBehaviorValue != DstBehaviorValue) {
1435 HasErr |= emitError("linking module flags '" + ID->getString() +
1436 "': IDs have conflicting behaviors");
1440 // Perform the merge for standard behavior types.
1441 switch (SrcBehaviorValue) {
1442 case Module::Require:
1443 case Module::Override: llvm_unreachable("not possible");
1444 case Module::Error: {
1445 // Emit an error if the values differ.
1446 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1447 HasErr |= emitError("linking module flags '" + ID->getString() +
1448 "': IDs have conflicting values");
1452 case Module::Warning: {
1453 // Emit a warning if the values differ.
1454 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1455 if (!SuppressWarnings) {
1456 errs() << "WARNING: linking module flags '" << ID->getString()
1457 << "': IDs have conflicting values";
1462 case Module::Append: {
1463 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1464 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1465 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1466 Value **VP, **Values = VP = new Value*[NumOps];
1467 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1468 *VP = DstValue->getOperand(i);
1469 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1470 *VP = SrcValue->getOperand(i);
1471 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1472 ArrayRef<Value*>(Values,
1477 case Module::AppendUnique: {
1478 SmallSetVector<Value*, 16> Elts;
1479 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1480 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1481 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1482 Elts.insert(DstValue->getOperand(i));
1483 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1484 Elts.insert(SrcValue->getOperand(i));
1485 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1486 ArrayRef<Value*>(Elts.begin(),
1493 // Check all of the requirements.
1494 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1495 MDNode *Requirement = Requirements[I];
1496 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1497 Value *ReqValue = Requirement->getOperand(1);
1499 MDNode *Op = Flags[Flag];
1500 if (!Op || Op->getOperand(2) != ReqValue) {
1501 HasErr |= emitError("linking module flags '" + Flag->getString() +
1502 "': does not have the required value");
1510 bool ModuleLinker::run() {
1511 assert(DstM && "Null destination module");
1512 assert(SrcM && "Null source module");
1514 // Inherit the target data from the source module if the destination module
1515 // doesn't have one already.
1516 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1517 DstM->setDataLayout(SrcM->getDataLayout());
1519 // Copy the target triple from the source to dest if the dest's is empty.
1520 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1521 DstM->setTargetTriple(SrcM->getTargetTriple());
1523 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1524 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1525 if (!SuppressWarnings) {
1526 errs() << "WARNING: Linking two modules of different data layouts: '"
1527 << SrcM->getModuleIdentifier() << "' is '"
1528 << SrcM->getDataLayoutStr() << "' whereas '"
1529 << DstM->getModuleIdentifier() << "' is '"
1530 << DstM->getDataLayoutStr() << "'\n";
1533 if (!SrcM->getTargetTriple().empty() &&
1534 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1535 if (!SuppressWarnings) {
1536 errs() << "WARNING: Linking two modules of different target triples: "
1537 << SrcM->getModuleIdentifier() << "' is '"
1538 << SrcM->getTargetTriple() << "' whereas '"
1539 << DstM->getModuleIdentifier() << "' is '"
1540 << DstM->getTargetTriple() << "'\n";
1544 // Append the module inline asm string.
1545 if (!SrcM->getModuleInlineAsm().empty()) {
1546 if (DstM->getModuleInlineAsm().empty())
1547 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1549 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1550 SrcM->getModuleInlineAsm());
1553 // Loop over all of the linked values to compute type mappings.
1554 computeTypeMapping();
1556 ComdatsChosen.clear();
1557 for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1558 const Comdat &C = SMEC.getValue();
1559 if (ComdatsChosen.count(&C))
1561 Comdat::SelectionKind SK;
1563 if (getComdatResult(&C, SK, LinkFromSrc))
1565 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1568 // Upgrade mismatched global arrays.
1569 upgradeMismatchedGlobals();
1571 // Insert all of the globals in src into the DstM module... without linking
1572 // initializers (which could refer to functions not yet mapped over).
1573 for (Module::global_iterator I = SrcM->global_begin(),
1574 E = SrcM->global_end(); I != E; ++I)
1575 if (linkGlobalProto(I))
1578 // Link the functions together between the two modules, without doing function
1579 // bodies... this just adds external function prototypes to the DstM
1580 // function... We do this so that when we begin processing function bodies,
1581 // all of the global values that may be referenced are available in our
1583 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1584 if (linkFunctionProto(I))
1587 // If there were any aliases, link them now.
1588 for (Module::alias_iterator I = SrcM->alias_begin(),
1589 E = SrcM->alias_end(); I != E; ++I)
1590 if (linkAliasProto(I))
1593 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1594 linkAppendingVarInit(AppendingVars[i]);
1596 // Link in the function bodies that are defined in the source module into
1598 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1599 // Skip if not linking from source.
1600 if (DoNotLinkFromSource.count(SF)) continue;
1602 Function *DF = cast<Function>(ValueMap[SF]);
1603 if (SF->hasPrefixData()) {
1604 // Link in the prefix data.
1605 DF->setPrefixData(MapValue(
1606 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1609 // Skip if no body (function is external) or materialize.
1610 if (SF->isDeclaration()) {
1611 if (!SF->isMaterializable())
1613 if (SF->Materialize(&ErrorMsg))
1617 linkFunctionBody(DF, SF);
1618 SF->Dematerialize();
1621 // Resolve all uses of aliases with aliasees.
1624 // Remap all of the named MDNodes in Src into the DstM module. We do this
1625 // after linking GlobalValues so that MDNodes that reference GlobalValues
1626 // are properly remapped.
1629 // Merge the module flags into the DstM module.
1630 if (linkModuleFlagsMetadata())
1633 // Update the initializers in the DstM module now that all globals that may
1634 // be referenced are in DstM.
1637 // Process vector of lazily linked in functions.
1638 bool LinkedInAnyFunctions;
1640 LinkedInAnyFunctions = false;
1642 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1643 E = LazilyLinkFunctions.end(); I != E; ++I) {
1648 Function *DF = cast<Function>(ValueMap[SF]);
1649 if (SF->hasPrefixData()) {
1650 // Link in the prefix data.
1651 DF->setPrefixData(MapValue(SF->getPrefixData(),
1658 // Materialize if necessary.
1659 if (SF->isDeclaration()) {
1660 if (!SF->isMaterializable())
1662 if (SF->Materialize(&ErrorMsg))
1666 // Erase from vector *before* the function body is linked - linkFunctionBody could
1668 LazilyLinkFunctions.erase(I);
1670 // Link in function body.
1671 linkFunctionBody(DF, SF);
1672 SF->Dematerialize();
1674 // Set flag to indicate we may have more functions to lazily link in
1675 // since we linked in a function.
1676 LinkedInAnyFunctions = true;
1679 } while (LinkedInAnyFunctions);
1681 // Now that all of the types from the source are used, resolve any structs
1682 // copied over to the dest that didn't exist there.
1683 TypeMap.linkDefinedTypeBodies();
1688 Linker::Linker(Module *M, bool SuppressWarnings)
1689 : Composite(M), SuppressWarnings(SuppressWarnings) {
1690 TypeFinder StructTypes;
1691 StructTypes.run(*M, true);
1692 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1698 void Linker::deleteModule() {
1700 Composite = nullptr;
1703 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1704 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1706 if (TheLinker.run()) {
1708 *ErrorMsg = TheLinker.ErrorMsg;
1714 //===----------------------------------------------------------------------===//
1715 // LinkModules entrypoint.
1716 //===----------------------------------------------------------------------===//
1718 /// LinkModules - This function links two modules together, with the resulting
1719 /// Dest module modified to be the composite of the two input modules. If an
1720 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1721 /// the problem. Upon failure, the Dest module could be in a modified state,
1722 /// and shouldn't be relied on to be consistent.
1723 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1724 std::string *ErrorMsg) {
1726 return L.linkInModule(Src, Mode, ErrorMsg);
1729 //===----------------------------------------------------------------------===//
1731 //===----------------------------------------------------------------------===//
1733 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1734 LLVMLinkerMode Mode, char **OutMessages) {
1735 std::string Messages;
1736 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1737 Mode, OutMessages? &Messages : nullptr);
1739 *OutMessages = strdup(Messages.c_str());