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"
30 //===----------------------------------------------------------------------===//
31 // TypeMap implementation.
32 //===----------------------------------------------------------------------===//
35 typedef SmallPtrSet<StructType*, 32> TypeSet;
37 class TypeMapTy : public ValueMapTypeRemapper {
38 /// MappedTypes - This is a mapping from a source type to a destination type
40 DenseMap<Type*, Type*> MappedTypes;
42 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
43 /// we speculatively add types to MappedTypes, but keep track of them here in
44 /// case we need to roll back.
45 SmallVector<Type*, 16> SpeculativeTypes;
47 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
48 /// source module that are mapped to an opaque struct in the destination
50 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
52 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
53 /// destination modules who are getting a body from the source module.
54 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
57 TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
59 TypeSet &DstStructTypesSet;
60 /// addTypeMapping - Indicate that the specified type in the destination
61 /// module is conceptually equivalent to the specified type in the source
63 void addTypeMapping(Type *DstTy, Type *SrcTy);
65 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
66 /// module from a type definition in the source module.
67 void linkDefinedTypeBodies();
69 /// get - Return the mapped type to use for the specified input type from the
71 Type *get(Type *SrcTy);
73 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
75 /// dump - Dump out the type map for debugging purposes.
77 for (DenseMap<Type*, Type*>::const_iterator
78 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
79 dbgs() << "TypeMap: ";
88 Type *getImpl(Type *T);
89 /// remapType - Implement the ValueMapTypeRemapper interface.
90 Type *remapType(Type *SrcTy) override {
94 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
98 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
99 Type *&Entry = MappedTypes[SrcTy];
102 if (DstTy == SrcTy) {
107 // Check to see if these types are recursively isomorphic and establish a
108 // mapping between them if so.
109 if (!areTypesIsomorphic(DstTy, SrcTy)) {
110 // Oops, they aren't isomorphic. Just discard this request by rolling out
111 // any speculative mappings we've established.
112 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
113 MappedTypes.erase(SpeculativeTypes[i]);
115 SpeculativeTypes.clear();
118 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
119 /// if they are isomorphic, false if they are not.
120 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
121 // Two types with differing kinds are clearly not isomorphic.
122 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
124 // If we have an entry in the MappedTypes table, then we have our answer.
125 Type *&Entry = MappedTypes[SrcTy];
127 return Entry == DstTy;
129 // Two identical types are clearly isomorphic. Remember this
130 // non-speculatively.
131 if (DstTy == SrcTy) {
136 // Okay, we have two types with identical kinds that we haven't seen before.
138 // If this is an opaque struct type, special case it.
139 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
140 // Mapping an opaque type to any struct, just keep the dest struct.
141 if (SSTy->isOpaque()) {
143 SpeculativeTypes.push_back(SrcTy);
147 // Mapping a non-opaque source type to an opaque dest. If this is the first
148 // type that we're mapping onto this destination type then we succeed. Keep
149 // the dest, but fill it in later. This doesn't need to be speculative. If
150 // this is the second (different) type that we're trying to map onto the
151 // same opaque type then we fail.
152 if (cast<StructType>(DstTy)->isOpaque()) {
153 // We can only map one source type onto the opaque destination type.
154 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
156 SrcDefinitionsToResolve.push_back(SSTy);
162 // If the number of subtypes disagree between the two types, then we fail.
163 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
166 // Fail if any of the extra properties (e.g. array size) of the type disagree.
167 if (isa<IntegerType>(DstTy))
168 return false; // bitwidth disagrees.
169 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
170 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
173 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
174 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
176 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
177 StructType *SSTy = cast<StructType>(SrcTy);
178 if (DSTy->isLiteral() != SSTy->isLiteral() ||
179 DSTy->isPacked() != SSTy->isPacked())
181 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
182 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
184 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
185 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
189 // Otherwise, we speculate that these two types will line up and recursively
190 // check the subelements.
192 SpeculativeTypes.push_back(SrcTy);
194 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
195 if (!areTypesIsomorphic(DstTy->getContainedType(i),
196 SrcTy->getContainedType(i)))
199 // If everything seems to have lined up, then everything is great.
203 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
204 /// module from a type definition in the source module.
205 void TypeMapTy::linkDefinedTypeBodies() {
206 SmallVector<Type*, 16> Elements;
207 SmallString<16> TmpName;
209 // Note that processing entries in this loop (calling 'get') can add new
210 // entries to the SrcDefinitionsToResolve vector.
211 while (!SrcDefinitionsToResolve.empty()) {
212 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
213 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
215 // TypeMap is a many-to-one mapping, if there were multiple types that
216 // provide a body for DstSTy then previous iterations of this loop may have
217 // already handled it. Just ignore this case.
218 if (!DstSTy->isOpaque()) continue;
219 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
221 // Map the body of the source type over to a new body for the dest type.
222 Elements.resize(SrcSTy->getNumElements());
223 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
224 Elements[i] = getImpl(SrcSTy->getElementType(i));
226 DstSTy->setBody(Elements, SrcSTy->isPacked());
228 // If DstSTy has no name or has a longer name than STy, then viciously steal
230 if (!SrcSTy->hasName()) continue;
231 StringRef SrcName = SrcSTy->getName();
233 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
234 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
236 DstSTy->setName(TmpName.str());
241 DstResolvedOpaqueTypes.clear();
244 /// get - Return the mapped type to use for the specified input type from the
246 Type *TypeMapTy::get(Type *Ty) {
247 Type *Result = getImpl(Ty);
249 // If this caused a reference to any struct type, resolve it before returning.
250 if (!SrcDefinitionsToResolve.empty())
251 linkDefinedTypeBodies();
255 /// getImpl - This is the recursive version of get().
256 Type *TypeMapTy::getImpl(Type *Ty) {
257 // If we already have an entry for this type, return it.
258 Type **Entry = &MappedTypes[Ty];
259 if (*Entry) return *Entry;
261 // If this is not a named struct type, then just map all of the elements and
262 // then rebuild the type from inside out.
263 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
264 // If there are no element types to map, then the type is itself. This is
265 // true for the anonymous {} struct, things like 'float', integers, etc.
266 if (Ty->getNumContainedTypes() == 0)
269 // Remap all of the elements, keeping track of whether any of them change.
270 bool AnyChange = false;
271 SmallVector<Type*, 4> ElementTypes;
272 ElementTypes.resize(Ty->getNumContainedTypes());
273 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
274 ElementTypes[i] = getImpl(Ty->getContainedType(i));
275 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
278 // If we found our type while recursively processing stuff, just use it.
279 Entry = &MappedTypes[Ty];
280 if (*Entry) return *Entry;
282 // If all of the element types mapped directly over, then the type is usable
287 // Otherwise, rebuild a modified type.
288 switch (Ty->getTypeID()) {
289 default: llvm_unreachable("unknown derived type to remap");
290 case Type::ArrayTyID:
291 return *Entry = ArrayType::get(ElementTypes[0],
292 cast<ArrayType>(Ty)->getNumElements());
293 case Type::VectorTyID:
294 return *Entry = VectorType::get(ElementTypes[0],
295 cast<VectorType>(Ty)->getNumElements());
296 case Type::PointerTyID:
297 return *Entry = PointerType::get(ElementTypes[0],
298 cast<PointerType>(Ty)->getAddressSpace());
299 case Type::FunctionTyID:
300 return *Entry = FunctionType::get(ElementTypes[0],
301 makeArrayRef(ElementTypes).slice(1),
302 cast<FunctionType>(Ty)->isVarArg());
303 case Type::StructTyID:
304 // Note that this is only reached for anonymous structs.
305 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
306 cast<StructType>(Ty)->isPacked());
310 // Otherwise, this is an unmapped named struct. If the struct can be directly
311 // mapped over, just use it as-is. This happens in a case when the linked-in
312 // module has something like:
313 // %T = type {%T*, i32}
314 // @GV = global %T* null
315 // where T does not exist at all in the destination module.
317 // The other case we watch for is when the type is not in the destination
318 // module, but that it has to be rebuilt because it refers to something that
319 // is already mapped. For example, if the destination module has:
321 // and the source module has something like
322 // %A' = type { i32 }
323 // %B = type { %A'* }
324 // @GV = global %B* null
325 // then we want to create a new type: "%B = type { %A*}" and have it take the
326 // pristine "%B" name from the source module.
328 // To determine which case this is, we have to recursively walk the type graph
329 // speculating that we'll be able to reuse it unmodified. Only if this is
330 // safe would we map the entire thing over. Because this is an optimization,
331 // and is not required for the prettiness of the linked module, we just skip
332 // it and always rebuild a type here.
333 StructType *STy = cast<StructType>(Ty);
335 // If the type is opaque, we can just use it directly.
336 if (STy->isOpaque()) {
337 // A named structure type from src module is used. Add it to the Set of
338 // identified structs in the destination module.
339 DstStructTypesSet.insert(STy);
343 // Otherwise we create a new type and resolve its body later. This will be
344 // resolved by the top level of get().
345 SrcDefinitionsToResolve.push_back(STy);
346 StructType *DTy = StructType::create(STy->getContext());
347 // A new identified structure type was created. Add it to the set of
348 // identified structs in the destination module.
349 DstStructTypesSet.insert(DTy);
350 DstResolvedOpaqueTypes.insert(DTy);
354 //===----------------------------------------------------------------------===//
355 // ModuleLinker implementation.
356 //===----------------------------------------------------------------------===//
361 /// ValueMaterializerTy - Creates prototypes for functions that are lazily
362 /// linked on the fly. This speeds up linking for modules with many
363 /// lazily linked functions of which few get used.
364 class ValueMaterializerTy : public ValueMaterializer {
367 std::vector<Function*> &LazilyLinkFunctions;
369 ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
370 std::vector<Function*> &LazilyLinkFunctions) :
371 ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
372 LazilyLinkFunctions(LazilyLinkFunctions) {
375 Value *materializeValueFor(Value *V) override;
378 /// ModuleLinker - This is an implementation class for the LinkModules
379 /// function, which is the entrypoint for this file.
384 ValueMaterializerTy ValMaterializer;
386 /// ValueMap - Mapping of values from what they used to be in Src, to what
387 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
388 /// some overhead due to the use of Value handles which the Linker doesn't
389 /// actually need, but this allows us to reuse the ValueMapper code.
390 ValueToValueMapTy ValueMap;
392 struct AppendingVarInfo {
393 GlobalVariable *NewGV; // New aggregate global in dest module.
394 Constant *DstInit; // Old initializer from dest module.
395 Constant *SrcInit; // Old initializer from src module.
398 std::vector<AppendingVarInfo> AppendingVars;
400 unsigned Mode; // Mode to treat source module.
402 // Set of items not to link in from source.
403 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
405 // Vector of functions to lazily link in.
406 std::vector<Function*> LazilyLinkFunctions;
408 bool SuppressWarnings;
411 std::string ErrorMsg;
413 ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode,
414 bool SuppressWarnings=false)
415 : DstM(dstM), SrcM(srcM), TypeMap(Set),
416 ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode),
417 SuppressWarnings(SuppressWarnings) {}
422 /// emitError - Helper method for setting a message and returning an error
424 bool emitError(const Twine &Message) {
425 ErrorMsg = Message.str();
429 bool getComdatLeader(Module *M, StringRef ComdatName,
430 const GlobalVariable *&GVar);
431 bool computeResultingSelectionKind(StringRef ComdatName,
432 Comdat::SelectionKind Src,
433 Comdat::SelectionKind Dst,
434 Comdat::SelectionKind &Result,
436 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
438 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
441 /// getLinkageResult - This analyzes the two global values and determines
442 /// what the result will look like in the destination module.
443 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
444 GlobalValue::LinkageTypes <,
445 GlobalValue::VisibilityTypes &Vis,
448 /// getLinkedToGlobal - Given a global in the source module, return the
449 /// global in the destination module that is being linked to, if any.
450 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
451 // If the source has no name it can't link. If it has local linkage,
452 // there is no name match-up going on.
453 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
456 // Otherwise see if we have a match in the destination module's symtab.
457 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
458 if (!DGV) return nullptr;
460 // If we found a global with the same name in the dest module, but it has
461 // internal linkage, we are really not doing any linkage here.
462 if (DGV->hasLocalLinkage())
465 // Otherwise, we do in fact link to the destination global.
469 void computeTypeMapping();
471 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
472 bool linkGlobalProto(GlobalVariable *SrcGV);
473 bool linkFunctionProto(Function *SrcF);
474 bool linkAliasProto(GlobalAlias *SrcA);
475 bool linkModuleFlagsMetadata();
477 void linkAppendingVarInit(const AppendingVarInfo &AVI);
478 void linkGlobalInits();
479 void linkFunctionBody(Function *Dst, Function *Src);
480 void linkAliasBodies();
481 void linkNamedMDNodes();
485 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
486 /// in the symbol table. This is good for all clients except for us. Go
487 /// through the trouble to force this back.
488 static void forceRenaming(GlobalValue *GV, StringRef Name) {
489 // If the global doesn't force its name or if it already has the right name,
490 // there is nothing for us to do.
491 if (GV->hasLocalLinkage() || GV->getName() == Name)
494 Module *M = GV->getParent();
496 // If there is a conflict, rename the conflict.
497 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
498 GV->takeName(ConflictGV);
499 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
500 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
502 GV->setName(Name); // Force the name back
506 /// copyGVAttributes - copy additional attributes (those not needed to construct
507 /// a GlobalValue) from the SrcGV to the DestGV.
508 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
509 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
510 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
513 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
515 DestGV->copyAttributesFrom(SrcGV);
518 DestGO->setAlignment(Alignment);
520 forceRenaming(DestGV, SrcGV->getName());
523 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
524 GlobalValue::VisibilityTypes b) {
525 if (a == GlobalValue::HiddenVisibility)
527 if (b == GlobalValue::HiddenVisibility)
529 if (a == GlobalValue::ProtectedVisibility)
531 if (b == GlobalValue::ProtectedVisibility)
536 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
537 Function *SF = dyn_cast<Function>(V);
541 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
542 SF->getLinkage(), SF->getName(), DstM);
543 copyGVAttributes(DF, SF);
545 LazilyLinkFunctions.push_back(SF);
549 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
550 const GlobalVariable *&GVar) {
551 const GlobalValue *GVal = M->getNamedValue(ComdatName);
552 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
553 GVal = GA->getBaseObject();
555 // We cannot resolve the size of the aliasee yet.
556 return emitError("Linking COMDATs named '" + ComdatName +
557 "': COMDAT key involves incomputable alias size.");
560 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
563 "Linking COMDATs named '" + ComdatName +
564 "': GlobalVariable required for data dependent selection!");
569 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
570 Comdat::SelectionKind Src,
571 Comdat::SelectionKind Dst,
572 Comdat::SelectionKind &Result,
574 // The ability to mix Comdat::SelectionKind::Any with
575 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
576 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
577 Dst == Comdat::SelectionKind::Largest;
578 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
579 Src == Comdat::SelectionKind::Largest;
580 if (DstAnyOrLargest && SrcAnyOrLargest) {
581 if (Dst == Comdat::SelectionKind::Largest ||
582 Src == Comdat::SelectionKind::Largest)
583 Result = Comdat::SelectionKind::Largest;
585 Result = Comdat::SelectionKind::Any;
586 } else if (Src == Dst) {
589 return emitError("Linking COMDATs named '" + ComdatName +
590 "': invalid selection kinds!");
594 case Comdat::SelectionKind::Any:
598 case Comdat::SelectionKind::NoDuplicates:
599 return emitError("Linking COMDATs named '" + ComdatName +
600 "': noduplicates has been violated!");
601 case Comdat::SelectionKind::ExactMatch:
602 case Comdat::SelectionKind::Largest:
603 case Comdat::SelectionKind::SameSize: {
604 const GlobalVariable *DstGV;
605 const GlobalVariable *SrcGV;
606 if (getComdatLeader(DstM, ComdatName, DstGV) ||
607 getComdatLeader(SrcM, ComdatName, SrcGV))
610 const DataLayout *DstDL = DstM->getDataLayout();
611 const DataLayout *SrcDL = SrcM->getDataLayout();
612 if (!DstDL || !SrcDL) {
614 "Linking COMDATs named '" + ComdatName +
615 "': can't do size dependent selection without DataLayout!");
618 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
620 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
621 if (Result == Comdat::SelectionKind::ExactMatch) {
622 if (SrcGV->getInitializer() != DstGV->getInitializer())
623 return emitError("Linking COMDATs named '" + ComdatName +
624 "': ExactMatch violated!");
626 } else if (Result == Comdat::SelectionKind::Largest) {
627 LinkFromSrc = SrcSize > DstSize;
628 } else if (Result == Comdat::SelectionKind::SameSize) {
629 if (SrcSize != DstSize)
630 return emitError("Linking COMDATs named '" + ComdatName +
631 "': SameSize violated!");
634 llvm_unreachable("unknown selection kind");
643 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
644 Comdat::SelectionKind &Result,
646 StringRef ComdatName = SrcC->getName();
647 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
648 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
649 if (DstCI != ComdatSymTab.end()) {
650 const Comdat *DstC = &DstCI->second;
651 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
652 Comdat::SelectionKind DSK = DstC->getSelectionKind();
653 if (computeResultingSelectionKind(ComdatName, SSK, DSK, Result, LinkFromSrc))
659 /// getLinkageResult - This analyzes the two global values and determines what
660 /// the result will look like in the destination module. In particular, it
661 /// computes the resultant linkage type and visibility, computes whether the
662 /// global in the source should be copied over to the destination (replacing
663 /// the existing one), and computes whether this linkage is an error or not.
664 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
665 GlobalValue::LinkageTypes <,
666 GlobalValue::VisibilityTypes &Vis,
668 assert(Dest && "Must have two globals being queried");
669 assert(!Src->hasLocalLinkage() &&
670 "If Src has internal linkage, Dest shouldn't be set!");
672 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
673 bool DestIsDeclaration = Dest->isDeclaration();
675 if (SrcIsDeclaration) {
676 // If Src is external or if both Src & Dest are external.. Just link the
677 // external globals, we aren't adding anything.
678 if (Src->hasDLLImportStorageClass()) {
679 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
680 if (DestIsDeclaration) {
682 LT = Src->getLinkage();
684 } else if (Dest->hasExternalWeakLinkage()) {
685 // If the Dest is weak, use the source linkage.
687 LT = Src->getLinkage();
690 LT = Dest->getLinkage();
692 } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
693 // If Dest is external but Src is not:
695 LT = Src->getLinkage();
696 } else if (Src->isWeakForLinker()) {
697 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
699 if (Dest->hasExternalWeakLinkage() ||
700 Dest->hasAvailableExternallyLinkage() ||
701 (Dest->hasLinkOnceLinkage() &&
702 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
704 LT = Src->getLinkage();
707 LT = Dest->getLinkage();
709 } else if (Dest->isWeakForLinker()) {
710 // At this point we know that Src has External* or DLL* linkage.
711 if (Src->hasExternalWeakLinkage()) {
713 LT = Dest->getLinkage();
716 LT = GlobalValue::ExternalLinkage;
719 assert((Dest->hasExternalLinkage() || Dest->hasExternalWeakLinkage()) &&
720 (Src->hasExternalLinkage() || Src->hasExternalWeakLinkage()) &&
721 "Unexpected linkage type!");
722 return emitError("Linking globals named '" + Src->getName() +
723 "': symbol multiply defined!");
726 // Compute the visibility. We follow the rules in the System V Application
728 assert(!GlobalValue::isLocalLinkage(LT) &&
729 "Symbols with local linkage should not be merged");
730 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
731 Dest->getVisibility() : Src->getVisibility();
735 /// computeTypeMapping - Loop over all of the linked values to compute type
736 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
737 /// we have two struct types 'Foo' but one got renamed when the module was
738 /// loaded into the same LLVMContext.
739 void ModuleLinker::computeTypeMapping() {
740 // Incorporate globals.
741 for (Module::global_iterator I = SrcM->global_begin(),
742 E = SrcM->global_end(); I != E; ++I) {
743 GlobalValue *DGV = getLinkedToGlobal(I);
746 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
747 TypeMap.addTypeMapping(DGV->getType(), I->getType());
751 // Unify the element type of appending arrays.
752 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
753 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
754 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
757 // Incorporate functions.
758 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
759 if (GlobalValue *DGV = getLinkedToGlobal(I))
760 TypeMap.addTypeMapping(DGV->getType(), I->getType());
763 // Incorporate types by name, scanning all the types in the source module.
764 // At this point, the destination module may have a type "%foo = { i32 }" for
765 // example. When the source module got loaded into the same LLVMContext, if
766 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
767 TypeFinder SrcStructTypes;
768 SrcStructTypes.run(*SrcM, true);
769 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
770 SrcStructTypes.end());
772 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
773 StructType *ST = SrcStructTypes[i];
774 if (!ST->hasName()) continue;
776 // Check to see if there is a dot in the name followed by a digit.
777 size_t DotPos = ST->getName().rfind('.');
778 if (DotPos == 0 || DotPos == StringRef::npos ||
779 ST->getName().back() == '.' ||
780 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
783 // Check to see if the destination module has a struct with the prefix name.
784 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
785 // Don't use it if this actually came from the source module. They're in
786 // the same LLVMContext after all. Also don't use it unless the type is
787 // actually used in the destination module. This can happen in situations
792 // %Z = type { %A } %B = type { %C.1 }
793 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
794 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
795 // %C = type { i8* } %B.3 = type { %C.1 }
797 // When we link Module B with Module A, the '%B' in Module B is
798 // used. However, that would then use '%C.1'. But when we process '%C.1',
799 // we prefer to take the '%C' version. So we are then left with both
800 // '%C.1' and '%C' being used for the same types. This leads to some
801 // variables using one type and some using the other.
802 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
803 TypeMap.addTypeMapping(DST, ST);
806 // Don't bother incorporating aliases, they aren't generally typed well.
808 // Now that we have discovered all of the type equivalences, get a body for
809 // any 'opaque' types in the dest module that are now resolved.
810 TypeMap.linkDefinedTypeBodies();
813 /// linkAppendingVarProto - If there were any appending global variables, link
814 /// them together now. Return true on error.
815 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
816 GlobalVariable *SrcGV) {
818 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
819 return emitError("Linking globals named '" + SrcGV->getName() +
820 "': can only link appending global with another appending global!");
822 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
824 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
825 Type *EltTy = DstTy->getElementType();
827 // Check to see that they two arrays agree on type.
828 if (EltTy != SrcTy->getElementType())
829 return emitError("Appending variables with different element types!");
830 if (DstGV->isConstant() != SrcGV->isConstant())
831 return emitError("Appending variables linked with different const'ness!");
833 if (DstGV->getAlignment() != SrcGV->getAlignment())
835 "Appending variables with different alignment need to be linked!");
837 if (DstGV->getVisibility() != SrcGV->getVisibility())
839 "Appending variables with different visibility need to be linked!");
841 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
843 "Appending variables with different unnamed_addr need to be linked!");
845 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
847 "Appending variables with different section name need to be linked!");
849 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
850 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
852 // Create the new global variable.
854 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
855 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
856 DstGV->getThreadLocalMode(),
857 DstGV->getType()->getAddressSpace());
859 // Propagate alignment, visibility and section info.
860 copyGVAttributes(NG, DstGV);
862 AppendingVarInfo AVI;
864 AVI.DstInit = DstGV->getInitializer();
865 AVI.SrcInit = SrcGV->getInitializer();
866 AppendingVars.push_back(AVI);
868 // Replace any uses of the two global variables with uses of the new
870 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
872 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
873 DstGV->eraseFromParent();
875 // Track the source variable so we don't try to link it.
876 DoNotLinkFromSource.insert(SrcGV);
881 /// linkGlobalProto - Loop through the global variables in the src module and
882 /// merge them into the dest module.
883 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
884 GlobalValue *DGV = getLinkedToGlobal(SGV);
885 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
886 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
888 bool LinkFromSrc = false;
889 Comdat *DC = nullptr;
890 if (const Comdat *SC = SGV->getComdat()) {
891 Comdat::SelectionKind SK;
892 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
893 DC = DstM->getOrInsertComdat(SC->getName());
894 DC->setSelectionKind(SK);
899 // Concatenation of appending linkage variables is magic and handled later.
900 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
901 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
903 // Determine whether linkage of these two globals follows the source
904 // module's definition or the destination module's definition.
905 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
906 GlobalValue::VisibilityTypes NV;
907 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
910 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
912 // If we're not linking from the source, then keep the definition that we
915 // Special case for const propagation.
916 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
917 if (DGVar->isDeclaration() && SGV->isConstant() &&
918 !DGVar->isConstant())
919 DGVar->setConstant(true);
921 // Set calculated linkage, visibility and unnamed_addr.
922 DGV->setLinkage(NewLinkage);
923 DGV->setVisibility(*NewVisibility);
924 DGV->setUnnamedAddr(HasUnnamedAddr);
929 // Make sure to remember this mapping.
930 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
932 // Track the source global so that we don't attempt to copy it over when
933 // processing global initializers.
934 DoNotLinkFromSource.insert(SGV);
940 // If the Comdat this variable was inside of wasn't selected, skip it.
941 if (DC && !DGV && !LinkFromSrc) {
942 DoNotLinkFromSource.insert(SGV);
946 // No linking to be performed or linking from the source: simply create an
947 // identical version of the symbol over in the dest module... the
948 // initializer will be filled in later by LinkGlobalInits.
949 GlobalVariable *NewDGV =
950 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
951 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
952 SGV->getName(), /*insertbefore*/nullptr,
953 SGV->getThreadLocalMode(),
954 SGV->getType()->getAddressSpace());
955 // Propagate alignment, visibility and section info.
956 copyGVAttributes(NewDGV, SGV);
958 NewDGV->setVisibility(*NewVisibility);
959 NewDGV->setUnnamedAddr(HasUnnamedAddr);
962 NewDGV->setComdat(DC);
965 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
966 DGV->eraseFromParent();
969 // Make sure to remember this mapping.
970 ValueMap[SGV] = NewDGV;
974 /// linkFunctionProto - Link the function in the source module into the
975 /// destination module if needed, setting up mapping information.
976 bool ModuleLinker::linkFunctionProto(Function *SF) {
977 GlobalValue *DGV = getLinkedToGlobal(SF);
978 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
979 bool HasUnnamedAddr = SF->hasUnnamedAddr();
981 bool LinkFromSrc = false;
982 Comdat *DC = nullptr;
983 if (const Comdat *SC = SF->getComdat()) {
984 Comdat::SelectionKind SK;
985 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
986 DC = DstM->getOrInsertComdat(SC->getName());
987 DC->setSelectionKind(SK);
992 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
993 GlobalValue::VisibilityTypes NV;
994 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
997 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1000 // Set calculated linkage
1001 DGV->setLinkage(NewLinkage);
1002 DGV->setVisibility(*NewVisibility);
1003 DGV->setUnnamedAddr(HasUnnamedAddr);
1008 // Make sure to remember this mapping.
1009 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
1011 // Track the function from the source module so we don't attempt to remap
1013 DoNotLinkFromSource.insert(SF);
1019 // If the function is to be lazily linked, don't create it just yet.
1020 // The ValueMaterializerTy will deal with creating it if it's used.
1021 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1022 SF->hasAvailableExternallyLinkage())) {
1023 DoNotLinkFromSource.insert(SF);
1027 // If the Comdat this function was inside of wasn't selected, skip it.
1028 if (DC && !DGV && !LinkFromSrc) {
1029 DoNotLinkFromSource.insert(SF);
1033 // If there is no linkage to be performed or we are linking from the source,
1035 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1036 SF->getLinkage(), SF->getName(), DstM);
1037 copyGVAttributes(NewDF, SF);
1039 NewDF->setVisibility(*NewVisibility);
1040 NewDF->setUnnamedAddr(HasUnnamedAddr);
1043 NewDF->setComdat(DC);
1046 // Any uses of DF need to change to NewDF, with cast.
1047 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1048 DGV->eraseFromParent();
1051 ValueMap[SF] = NewDF;
1055 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
1057 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1058 GlobalValue *DGV = getLinkedToGlobal(SGA);
1059 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1060 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
1062 bool LinkFromSrc = false;
1063 Comdat *DC = nullptr;
1064 if (const Comdat *SC = SGA->getComdat()) {
1065 Comdat::SelectionKind SK;
1066 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1067 DC = DstM->getOrInsertComdat(SC->getName());
1068 DC->setSelectionKind(SK);
1073 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1074 GlobalValue::VisibilityTypes NV;
1075 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1078 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1081 // Set calculated linkage.
1082 DGV->setLinkage(NewLinkage);
1083 DGV->setVisibility(*NewVisibility);
1084 DGV->setUnnamedAddr(HasUnnamedAddr);
1089 // Make sure to remember this mapping.
1090 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
1092 // Track the alias from the source module so we don't attempt to remap it.
1093 DoNotLinkFromSource.insert(SGA);
1099 // If the Comdat this alias was inside of wasn't selected, skip it.
1100 if (DC && !DGV && !LinkFromSrc) {
1101 DoNotLinkFromSource.insert(SGA);
1105 // If there is no linkage to be performed or we're linking from the source,
1107 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1109 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1110 SGA->getLinkage(), SGA->getName(), DstM);
1111 copyGVAttributes(NewDA, SGA);
1113 NewDA->setVisibility(*NewVisibility);
1114 NewDA->setUnnamedAddr(HasUnnamedAddr);
1117 // Any uses of DGV need to change to NewDA, with cast.
1118 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1119 DGV->eraseFromParent();
1122 ValueMap[SGA] = NewDA;
1126 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
1127 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1129 for (unsigned i = 0; i != NumElements; ++i)
1130 Dest.push_back(C->getAggregateElement(i));
1133 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1134 // Merge the initializer.
1135 SmallVector<Constant*, 16> Elements;
1136 getArrayElements(AVI.DstInit, Elements);
1138 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1139 getArrayElements(SrcInit, Elements);
1141 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1142 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
1145 /// linkGlobalInits - Update the initializers in the Dest module now that all
1146 /// globals that may be referenced are in Dest.
1147 void ModuleLinker::linkGlobalInits() {
1148 // Loop over all of the globals in the src module, mapping them over as we go
1149 for (Module::const_global_iterator I = SrcM->global_begin(),
1150 E = SrcM->global_end(); I != E; ++I) {
1152 // Only process initialized GV's or ones not already in dest.
1153 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1155 // Grab destination global variable.
1156 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1157 // Figure out what the initializer looks like in the dest module.
1158 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1159 RF_None, &TypeMap, &ValMaterializer));
1163 /// linkFunctionBody - Copy the source function over into the dest function and
1164 /// fix up references to values. At this point we know that Dest is an external
1165 /// function, and that Src is not.
1166 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1167 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1169 // Go through and convert function arguments over, remembering the mapping.
1170 Function::arg_iterator DI = Dst->arg_begin();
1171 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1172 I != E; ++I, ++DI) {
1173 DI->setName(I->getName()); // Copy the name over.
1175 // Add a mapping to our mapping.
1179 if (Mode == Linker::DestroySource) {
1180 // Splice the body of the source function into the dest function.
1181 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1183 // At this point, all of the instructions and values of the function are now
1184 // copied over. The only problem is that they are still referencing values in
1185 // the Source function as operands. Loop through all of the operands of the
1186 // functions and patch them up to point to the local versions.
1187 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1188 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1189 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1190 &TypeMap, &ValMaterializer);
1193 // Clone the body of the function into the dest function.
1194 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1195 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1196 &TypeMap, &ValMaterializer);
1199 // There is no need to map the arguments anymore.
1200 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1206 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1207 void ModuleLinker::linkAliasBodies() {
1208 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1210 if (DoNotLinkFromSource.count(I))
1212 if (Constant *Aliasee = I->getAliasee()) {
1213 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1215 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1216 DA->setAliasee(Val);
1221 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1223 void ModuleLinker::linkNamedMDNodes() {
1224 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1225 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1226 E = SrcM->named_metadata_end(); I != E; ++I) {
1227 // Don't link module flags here. Do them separately.
1228 if (&*I == SrcModFlags) continue;
1229 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1230 // Add Src elements into Dest node.
1231 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1232 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1233 RF_None, &TypeMap, &ValMaterializer));
1237 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1239 bool ModuleLinker::linkModuleFlagsMetadata() {
1240 // If the source module has no module flags, we are done.
1241 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1242 if (!SrcModFlags) return false;
1244 // If the destination module doesn't have module flags yet, then just copy
1245 // over the source module's flags.
1246 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1247 if (DstModFlags->getNumOperands() == 0) {
1248 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1249 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1254 // First build a map of the existing module flags and requirements.
1255 DenseMap<MDString*, MDNode*> Flags;
1256 SmallSetVector<MDNode*, 16> Requirements;
1257 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1258 MDNode *Op = DstModFlags->getOperand(I);
1259 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1260 MDString *ID = cast<MDString>(Op->getOperand(1));
1262 if (Behavior->getZExtValue() == Module::Require) {
1263 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1269 // Merge in the flags from the source module, and also collect its set of
1271 bool HasErr = false;
1272 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1273 MDNode *SrcOp = SrcModFlags->getOperand(I);
1274 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1275 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1276 MDNode *DstOp = Flags.lookup(ID);
1277 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1279 // If this is a requirement, add it and continue.
1280 if (SrcBehaviorValue == Module::Require) {
1281 // If the destination module does not already have this requirement, add
1283 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1284 DstModFlags->addOperand(SrcOp);
1289 // If there is no existing flag with this ID, just add it.
1292 DstModFlags->addOperand(SrcOp);
1296 // Otherwise, perform a merge.
1297 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1298 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1300 // If either flag has override behavior, handle it first.
1301 if (DstBehaviorValue == Module::Override) {
1302 // Diagnose inconsistent flags which both have override behavior.
1303 if (SrcBehaviorValue == Module::Override &&
1304 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1305 HasErr |= emitError("linking module flags '" + ID->getString() +
1306 "': IDs have conflicting override values");
1309 } else if (SrcBehaviorValue == Module::Override) {
1310 // Update the destination flag to that of the source.
1311 DstOp->replaceOperandWith(0, SrcBehavior);
1312 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1316 // Diagnose inconsistent merge behavior types.
1317 if (SrcBehaviorValue != DstBehaviorValue) {
1318 HasErr |= emitError("linking module flags '" + ID->getString() +
1319 "': IDs have conflicting behaviors");
1323 // Perform the merge for standard behavior types.
1324 switch (SrcBehaviorValue) {
1325 case Module::Require:
1326 case Module::Override: llvm_unreachable("not possible");
1327 case Module::Error: {
1328 // Emit an error if the values differ.
1329 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1330 HasErr |= emitError("linking module flags '" + ID->getString() +
1331 "': IDs have conflicting values");
1335 case Module::Warning: {
1336 // Emit a warning if the values differ.
1337 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1338 if (!SuppressWarnings) {
1339 errs() << "WARNING: linking module flags '" << ID->getString()
1340 << "': IDs have conflicting values";
1345 case Module::Append: {
1346 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1347 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1348 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1349 Value **VP, **Values = VP = new Value*[NumOps];
1350 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1351 *VP = DstValue->getOperand(i);
1352 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1353 *VP = SrcValue->getOperand(i);
1354 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1355 ArrayRef<Value*>(Values,
1360 case Module::AppendUnique: {
1361 SmallSetVector<Value*, 16> Elts;
1362 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1363 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1364 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1365 Elts.insert(DstValue->getOperand(i));
1366 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1367 Elts.insert(SrcValue->getOperand(i));
1368 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1369 ArrayRef<Value*>(Elts.begin(),
1376 // Check all of the requirements.
1377 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1378 MDNode *Requirement = Requirements[I];
1379 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1380 Value *ReqValue = Requirement->getOperand(1);
1382 MDNode *Op = Flags[Flag];
1383 if (!Op || Op->getOperand(2) != ReqValue) {
1384 HasErr |= emitError("linking module flags '" + Flag->getString() +
1385 "': does not have the required value");
1393 bool ModuleLinker::run() {
1394 assert(DstM && "Null destination module");
1395 assert(SrcM && "Null source module");
1397 // Inherit the target data from the source module if the destination module
1398 // doesn't have one already.
1399 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1400 DstM->setDataLayout(SrcM->getDataLayout());
1402 // Copy the target triple from the source to dest if the dest's is empty.
1403 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1404 DstM->setTargetTriple(SrcM->getTargetTriple());
1406 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1407 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1408 if (!SuppressWarnings) {
1409 errs() << "WARNING: Linking two modules of different data layouts: '"
1410 << SrcM->getModuleIdentifier() << "' is '"
1411 << SrcM->getDataLayoutStr() << "' whereas '"
1412 << DstM->getModuleIdentifier() << "' is '"
1413 << DstM->getDataLayoutStr() << "'\n";
1416 if (!SrcM->getTargetTriple().empty() &&
1417 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1418 if (!SuppressWarnings) {
1419 errs() << "WARNING: Linking two modules of different target triples: "
1420 << SrcM->getModuleIdentifier() << "' is '"
1421 << SrcM->getTargetTriple() << "' whereas '"
1422 << DstM->getModuleIdentifier() << "' is '"
1423 << DstM->getTargetTriple() << "'\n";
1427 // Append the module inline asm string.
1428 if (!SrcM->getModuleInlineAsm().empty()) {
1429 if (DstM->getModuleInlineAsm().empty())
1430 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1432 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1433 SrcM->getModuleInlineAsm());
1436 // Loop over all of the linked values to compute type mappings.
1437 computeTypeMapping();
1439 ComdatsChosen.clear();
1440 for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1441 const Comdat &C = SMEC.getValue();
1442 if (ComdatsChosen.count(&C))
1444 Comdat::SelectionKind SK;
1446 if (getComdatResult(&C, SK, LinkFromSrc))
1448 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1451 // Insert all of the globals in src into the DstM module... without linking
1452 // initializers (which could refer to functions not yet mapped over).
1453 for (Module::global_iterator I = SrcM->global_begin(),
1454 E = SrcM->global_end(); I != E; ++I)
1455 if (linkGlobalProto(I))
1458 // Link the functions together between the two modules, without doing function
1459 // bodies... this just adds external function prototypes to the DstM
1460 // function... We do this so that when we begin processing function bodies,
1461 // all of the global values that may be referenced are available in our
1463 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1464 if (linkFunctionProto(I))
1467 // If there were any aliases, link them now.
1468 for (Module::alias_iterator I = SrcM->alias_begin(),
1469 E = SrcM->alias_end(); I != E; ++I)
1470 if (linkAliasProto(I))
1473 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1474 linkAppendingVarInit(AppendingVars[i]);
1476 // Link in the function bodies that are defined in the source module into
1478 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1479 // Skip if not linking from source.
1480 if (DoNotLinkFromSource.count(SF)) continue;
1482 Function *DF = cast<Function>(ValueMap[SF]);
1483 if (SF->hasPrefixData()) {
1484 // Link in the prefix data.
1485 DF->setPrefixData(MapValue(
1486 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1489 // Skip if no body (function is external) or materialize.
1490 if (SF->isDeclaration()) {
1491 if (!SF->isMaterializable())
1493 if (SF->Materialize(&ErrorMsg))
1497 linkFunctionBody(DF, SF);
1498 SF->Dematerialize();
1501 // Resolve all uses of aliases with aliasees.
1504 // Remap all of the named MDNodes in Src into the DstM module. We do this
1505 // after linking GlobalValues so that MDNodes that reference GlobalValues
1506 // are properly remapped.
1509 // Merge the module flags into the DstM module.
1510 if (linkModuleFlagsMetadata())
1513 // Update the initializers in the DstM module now that all globals that may
1514 // be referenced are in DstM.
1517 // Process vector of lazily linked in functions.
1518 bool LinkedInAnyFunctions;
1520 LinkedInAnyFunctions = false;
1522 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1523 E = LazilyLinkFunctions.end(); I != E; ++I) {
1528 Function *DF = cast<Function>(ValueMap[SF]);
1529 if (SF->hasPrefixData()) {
1530 // Link in the prefix data.
1531 DF->setPrefixData(MapValue(SF->getPrefixData(),
1538 // Materialize if necessary.
1539 if (SF->isDeclaration()) {
1540 if (!SF->isMaterializable())
1542 if (SF->Materialize(&ErrorMsg))
1546 // Erase from vector *before* the function body is linked - linkFunctionBody could
1548 LazilyLinkFunctions.erase(I);
1550 // Link in function body.
1551 linkFunctionBody(DF, SF);
1552 SF->Dematerialize();
1554 // Set flag to indicate we may have more functions to lazily link in
1555 // since we linked in a function.
1556 LinkedInAnyFunctions = true;
1559 } while (LinkedInAnyFunctions);
1561 // Now that all of the types from the source are used, resolve any structs
1562 // copied over to the dest that didn't exist there.
1563 TypeMap.linkDefinedTypeBodies();
1568 Linker::Linker(Module *M, bool SuppressWarnings)
1569 : Composite(M), SuppressWarnings(SuppressWarnings) {
1570 TypeFinder StructTypes;
1571 StructTypes.run(*M, true);
1572 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1578 void Linker::deleteModule() {
1580 Composite = nullptr;
1583 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1584 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1586 if (TheLinker.run()) {
1588 *ErrorMsg = TheLinker.ErrorMsg;
1594 //===----------------------------------------------------------------------===//
1595 // LinkModules entrypoint.
1596 //===----------------------------------------------------------------------===//
1598 /// LinkModules - This function links two modules together, with the resulting
1599 /// Dest module modified to be the composite of the two input modules. If an
1600 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1601 /// the problem. Upon failure, the Dest module could be in a modified state,
1602 /// and shouldn't be relied on to be consistent.
1603 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1604 std::string *ErrorMsg) {
1606 return L.linkInModule(Src, Mode, ErrorMsg);
1609 //===----------------------------------------------------------------------===//
1611 //===----------------------------------------------------------------------===//
1613 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1614 LLVMLinkerMode Mode, char **OutMessages) {
1615 std::string Messages;
1616 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1617 Mode, OutMessages? &Messages : nullptr);
1619 *OutMessages = strdup(Messages.c_str());