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 bool shouldLinkFromSource(const GlobalValue &Dest, const GlobalValue &Src);
425 /// emitError - Helper method for setting a message and returning an error
427 bool emitError(const Twine &Message) {
428 ErrorMsg = Message.str();
432 bool getComdatLeader(Module *M, StringRef ComdatName,
433 const GlobalVariable *&GVar);
434 bool computeResultingSelectionKind(StringRef ComdatName,
435 Comdat::SelectionKind Src,
436 Comdat::SelectionKind Dst,
437 Comdat::SelectionKind &Result,
439 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
441 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
444 /// getLinkageResult - This analyzes the two global values and determines
445 /// what the result will look like in the destination module.
446 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
447 GlobalValue::LinkageTypes <,
448 GlobalValue::VisibilityTypes &Vis,
451 /// getLinkedToGlobal - Given a global in the source module, return the
452 /// global in the destination module that is being linked to, if any.
453 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
454 // If the source has no name it can't link. If it has local linkage,
455 // there is no name match-up going on.
456 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
459 // Otherwise see if we have a match in the destination module's symtab.
460 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
461 if (!DGV) return nullptr;
463 // If we found a global with the same name in the dest module, but it has
464 // internal linkage, we are really not doing any linkage here.
465 if (DGV->hasLocalLinkage())
468 // Otherwise, we do in fact link to the destination global.
472 void computeTypeMapping();
474 void upgradeMismatchedGlobalArray(StringRef Name);
475 void upgradeMismatchedGlobals();
477 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
478 bool linkGlobalProto(GlobalVariable *SrcGV);
479 bool linkFunctionProto(Function *SrcF);
480 bool linkAliasProto(GlobalAlias *SrcA);
481 bool linkModuleFlagsMetadata();
483 void linkAppendingVarInit(const AppendingVarInfo &AVI);
484 void linkGlobalInits();
485 void linkFunctionBody(Function *Dst, Function *Src);
486 void linkAliasBodies();
487 void linkNamedMDNodes();
491 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
492 /// in the symbol table. This is good for all clients except for us. Go
493 /// through the trouble to force this back.
494 static void forceRenaming(GlobalValue *GV, StringRef Name) {
495 // If the global doesn't force its name or if it already has the right name,
496 // there is nothing for us to do.
497 if (GV->hasLocalLinkage() || GV->getName() == Name)
500 Module *M = GV->getParent();
502 // If there is a conflict, rename the conflict.
503 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
504 GV->takeName(ConflictGV);
505 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
506 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
508 GV->setName(Name); // Force the name back
512 /// copyGVAttributes - copy additional attributes (those not needed to construct
513 /// a GlobalValue) from the SrcGV to the DestGV.
514 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
515 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
516 auto *DestGO = dyn_cast<GlobalObject>(DestGV);
519 Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment());
521 DestGV->copyAttributesFrom(SrcGV);
524 DestGO->setAlignment(Alignment);
526 forceRenaming(DestGV, SrcGV->getName());
529 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
530 GlobalValue::VisibilityTypes b) {
531 if (a == GlobalValue::HiddenVisibility)
533 if (b == GlobalValue::HiddenVisibility)
535 if (a == GlobalValue::ProtectedVisibility)
537 if (b == GlobalValue::ProtectedVisibility)
542 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
543 Function *SF = dyn_cast<Function>(V);
547 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
548 SF->getLinkage(), SF->getName(), DstM);
549 copyGVAttributes(DF, SF);
551 if (Comdat *SC = SF->getComdat()) {
552 Comdat *DC = DstM->getOrInsertComdat(SC->getName());
556 LazilyLinkFunctions.push_back(SF);
560 bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
561 const GlobalVariable *&GVar) {
562 const GlobalValue *GVal = M->getNamedValue(ComdatName);
563 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
564 GVal = GA->getBaseObject();
566 // We cannot resolve the size of the aliasee yet.
567 return emitError("Linking COMDATs named '" + ComdatName +
568 "': COMDAT key involves incomputable alias size.");
571 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
574 "Linking COMDATs named '" + ComdatName +
575 "': GlobalVariable required for data dependent selection!");
580 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
581 Comdat::SelectionKind Src,
582 Comdat::SelectionKind Dst,
583 Comdat::SelectionKind &Result,
585 // The ability to mix Comdat::SelectionKind::Any with
586 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
587 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
588 Dst == Comdat::SelectionKind::Largest;
589 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
590 Src == Comdat::SelectionKind::Largest;
591 if (DstAnyOrLargest && SrcAnyOrLargest) {
592 if (Dst == Comdat::SelectionKind::Largest ||
593 Src == Comdat::SelectionKind::Largest)
594 Result = Comdat::SelectionKind::Largest;
596 Result = Comdat::SelectionKind::Any;
597 } else if (Src == Dst) {
600 return emitError("Linking COMDATs named '" + ComdatName +
601 "': invalid selection kinds!");
605 case Comdat::SelectionKind::Any:
609 case Comdat::SelectionKind::NoDuplicates:
610 return emitError("Linking COMDATs named '" + ComdatName +
611 "': noduplicates has been violated!");
612 case Comdat::SelectionKind::ExactMatch:
613 case Comdat::SelectionKind::Largest:
614 case Comdat::SelectionKind::SameSize: {
615 const GlobalVariable *DstGV;
616 const GlobalVariable *SrcGV;
617 if (getComdatLeader(DstM, ComdatName, DstGV) ||
618 getComdatLeader(SrcM, ComdatName, SrcGV))
621 const DataLayout *DstDL = DstM->getDataLayout();
622 const DataLayout *SrcDL = SrcM->getDataLayout();
623 if (!DstDL || !SrcDL) {
625 "Linking COMDATs named '" + ComdatName +
626 "': can't do size dependent selection without DataLayout!");
629 DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType());
631 SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType());
632 if (Result == Comdat::SelectionKind::ExactMatch) {
633 if (SrcGV->getInitializer() != DstGV->getInitializer())
634 return emitError("Linking COMDATs named '" + ComdatName +
635 "': ExactMatch violated!");
637 } else if (Result == Comdat::SelectionKind::Largest) {
638 LinkFromSrc = SrcSize > DstSize;
639 } else if (Result == Comdat::SelectionKind::SameSize) {
640 if (SrcSize != DstSize)
641 return emitError("Linking COMDATs named '" + ComdatName +
642 "': SameSize violated!");
645 llvm_unreachable("unknown selection kind");
654 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
655 Comdat::SelectionKind &Result,
657 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
658 StringRef ComdatName = SrcC->getName();
659 Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
660 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
662 if (DstCI == ComdatSymTab.end()) {
663 // Use the comdat if it is only available in one of the modules.
669 const Comdat *DstC = &DstCI->second;
670 Comdat::SelectionKind DSK = DstC->getSelectionKind();
671 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
675 bool ModuleLinker::shouldLinkFromSource(const GlobalValue &Dest,
676 const GlobalValue &Src) {
677 bool SrcIsDeclaration = Src.isDeclarationForLinker();
678 bool DestIsDeclaration = Dest.isDeclarationForLinker();
680 // FIXME: Make datalayout mandatory and just use getDataLayout().
681 DataLayout DL(Dest.getParent());
683 if (SrcIsDeclaration) {
684 // If Src is external or if both Src & Dest are external.. Just link the
685 // external globals, we aren't adding anything.
686 if (Src.hasDLLImportStorageClass())
687 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
688 return DestIsDeclaration;
689 // If the Dest is weak, use the source linkage.
690 return Dest.hasExternalWeakLinkage();
693 if (DestIsDeclaration)
694 // If Dest is external but Src is not:
697 if (Src.hasCommonLinkage()) {
698 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage())
701 if (!Dest.hasCommonLinkage())
704 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
705 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
706 return SrcSize > DestSize;
709 if (Src.isWeakForLinker()) {
710 assert(!Dest.hasExternalWeakLinkage());
711 assert(!Dest.hasAvailableExternallyLinkage());
713 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage())
719 if (Dest.isWeakForLinker()) {
720 assert(Src.hasExternalLinkage());
724 assert(!Src.hasExternalWeakLinkage());
725 assert(!Dest.hasExternalWeakLinkage());
726 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
727 "Unexpected linkage type!");
728 return emitError("Linking globals named '" + Src.getName() +
729 "': symbol multiply defined!");
732 /// This analyzes the two global values and determines what the result will look
733 /// like in the destination module. In particular, it computes the resultant
734 /// linkage type and visibility, computes whether the global in the source
735 /// should be copied over to the destination (replacing the existing one), and
736 /// computes whether this linkage is an error or not.
737 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
738 GlobalValue::LinkageTypes <,
739 GlobalValue::VisibilityTypes &Vis,
741 assert(Dest && "Must have two globals being queried");
742 assert(!Src->hasLocalLinkage() &&
743 "If Src has internal linkage, Dest shouldn't be set!");
745 assert(ErrorMsg.empty());
746 LinkFromSrc = shouldLinkFromSource(*Dest, *Src);
747 if (!ErrorMsg.empty())
751 LT = Src->getLinkage();
753 LT = Dest->getLinkage();
755 // Compute the visibility. We follow the rules in the System V Application
757 assert(!GlobalValue::isLocalLinkage(LT) &&
758 "Symbols with local linkage should not be merged");
759 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
760 Dest->getVisibility() : Src->getVisibility();
764 /// computeTypeMapping - Loop over all of the linked values to compute type
765 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
766 /// we have two struct types 'Foo' but one got renamed when the module was
767 /// loaded into the same LLVMContext.
768 void ModuleLinker::computeTypeMapping() {
769 // Incorporate globals.
770 for (Module::global_iterator I = SrcM->global_begin(),
771 E = SrcM->global_end(); I != E; ++I) {
772 GlobalValue *DGV = getLinkedToGlobal(I);
775 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
776 TypeMap.addTypeMapping(DGV->getType(), I->getType());
780 // Unify the element type of appending arrays.
781 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
782 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
783 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
786 // Incorporate functions.
787 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
788 if (GlobalValue *DGV = getLinkedToGlobal(I))
789 TypeMap.addTypeMapping(DGV->getType(), I->getType());
792 // Incorporate types by name, scanning all the types in the source module.
793 // At this point, the destination module may have a type "%foo = { i32 }" for
794 // example. When the source module got loaded into the same LLVMContext, if
795 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
796 TypeFinder SrcStructTypes;
797 SrcStructTypes.run(*SrcM, true);
798 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
799 SrcStructTypes.end());
801 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
802 StructType *ST = SrcStructTypes[i];
803 if (!ST->hasName()) continue;
805 // Check to see if there is a dot in the name followed by a digit.
806 size_t DotPos = ST->getName().rfind('.');
807 if (DotPos == 0 || DotPos == StringRef::npos ||
808 ST->getName().back() == '.' ||
809 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
812 // Check to see if the destination module has a struct with the prefix name.
813 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
814 // Don't use it if this actually came from the source module. They're in
815 // the same LLVMContext after all. Also don't use it unless the type is
816 // actually used in the destination module. This can happen in situations
821 // %Z = type { %A } %B = type { %C.1 }
822 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
823 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
824 // %C = type { i8* } %B.3 = type { %C.1 }
826 // When we link Module B with Module A, the '%B' in Module B is
827 // used. However, that would then use '%C.1'. But when we process '%C.1',
828 // we prefer to take the '%C' version. So we are then left with both
829 // '%C.1' and '%C' being used for the same types. This leads to some
830 // variables using one type and some using the other.
831 if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
832 TypeMap.addTypeMapping(DST, ST);
835 // Don't bother incorporating aliases, they aren't generally typed well.
837 // Now that we have discovered all of the type equivalences, get a body for
838 // any 'opaque' types in the dest module that are now resolved.
839 TypeMap.linkDefinedTypeBodies();
842 static void upgradeGlobalArray(GlobalVariable *GV) {
843 ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
844 StructType *OldTy = cast<StructType>(ATy->getElementType());
845 assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
847 // Get the upgraded 3 element type.
848 PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
849 Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
851 StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
853 // Build new constants with a null third field filled in.
854 Constant *OldInitC = GV->getInitializer();
855 ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
856 if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
857 // Invalid initializer; give up.
859 std::vector<Constant *> Initializers;
860 if (OldInit && OldInit->getNumOperands()) {
861 Value *Null = Constant::getNullValue(VoidPtrTy);
862 for (Use &U : OldInit->operands()) {
863 ConstantStruct *Init = cast<ConstantStruct>(U.get());
864 Initializers.push_back(ConstantStruct::get(
865 NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
868 assert(Initializers.size() == ATy->getNumElements() &&
869 "Failed to copy all array elements");
871 // Replace the old GV with a new one.
872 ATy = ArrayType::get(NewTy, Initializers.size());
873 Constant *NewInit = ConstantArray::get(ATy, Initializers);
874 GlobalVariable *NewGV = new GlobalVariable(
875 *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
876 GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
877 GV->isExternallyInitialized());
878 NewGV->copyAttributesFrom(GV);
880 assert(GV->use_empty() && "program cannot use initializer list");
881 GV->eraseFromParent();
884 void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
885 // Look for the global arrays.
886 auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
889 auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
893 // Check if the types already match.
894 auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
896 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
900 // Grab the element types. We can only upgrade an array of a two-field
901 // struct. Only bother if the other one has three-fields.
902 auto *DstEltTy = cast<StructType>(DstTy->getElementType());
903 auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
904 if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
905 upgradeGlobalArray(DstGV);
908 if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
909 upgradeGlobalArray(SrcGV);
911 // We can't upgrade any other differences.
914 void ModuleLinker::upgradeMismatchedGlobals() {
915 upgradeMismatchedGlobalArray("llvm.global_ctors");
916 upgradeMismatchedGlobalArray("llvm.global_dtors");
919 /// linkAppendingVarProto - If there were any appending global variables, link
920 /// them together now. Return true on error.
921 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
922 GlobalVariable *SrcGV) {
924 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
925 return emitError("Linking globals named '" + SrcGV->getName() +
926 "': can only link appending global with another appending global!");
928 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
930 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
931 Type *EltTy = DstTy->getElementType();
933 // Check to see that they two arrays agree on type.
934 if (EltTy != SrcTy->getElementType())
935 return emitError("Appending variables with different element types!");
936 if (DstGV->isConstant() != SrcGV->isConstant())
937 return emitError("Appending variables linked with different const'ness!");
939 if (DstGV->getAlignment() != SrcGV->getAlignment())
941 "Appending variables with different alignment need to be linked!");
943 if (DstGV->getVisibility() != SrcGV->getVisibility())
945 "Appending variables with different visibility need to be linked!");
947 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
949 "Appending variables with different unnamed_addr need to be linked!");
951 if (StringRef(DstGV->getSection()) != SrcGV->getSection())
953 "Appending variables with different section name need to be linked!");
955 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
956 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
958 // Create the new global variable.
960 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
961 DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV,
962 DstGV->getThreadLocalMode(),
963 DstGV->getType()->getAddressSpace());
965 // Propagate alignment, visibility and section info.
966 copyGVAttributes(NG, DstGV);
968 AppendingVarInfo AVI;
970 AVI.DstInit = DstGV->getInitializer();
971 AVI.SrcInit = SrcGV->getInitializer();
972 AppendingVars.push_back(AVI);
974 // Replace any uses of the two global variables with uses of the new
976 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
978 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
979 DstGV->eraseFromParent();
981 // Track the source variable so we don't try to link it.
982 DoNotLinkFromSource.insert(SrcGV);
987 /// linkGlobalProto - Loop through the global variables in the src module and
988 /// merge them into the dest module.
989 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
990 GlobalValue *DGV = getLinkedToGlobal(SGV);
991 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
992 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
993 unsigned Alignment = SGV->getAlignment();
995 bool LinkFromSrc = false;
996 Comdat *DC = nullptr;
997 if (const Comdat *SC = SGV->getComdat()) {
998 Comdat::SelectionKind SK;
999 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1000 DC = DstM->getOrInsertComdat(SC->getName());
1001 DC->setSelectionKind(SK);
1006 // Concatenation of appending linkage variables is magic and handled later.
1007 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
1008 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
1010 // Determine whether linkage of these two globals follows the source
1011 // module's definition or the destination module's definition.
1012 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1013 GlobalValue::VisibilityTypes NV;
1014 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
1017 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1018 if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1019 Alignment = std::max(Alignment, DGV->getAlignment());
1020 else if (!LinkFromSrc)
1021 Alignment = DGV->getAlignment();
1023 // If we're not linking from the source, then keep the definition that we
1026 // Special case for const propagation.
1027 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
1028 DGVar->setAlignment(Alignment);
1030 if (DGVar->isDeclaration() && SGV->isConstant() &&
1031 !DGVar->isConstant())
1032 DGVar->setConstant(true);
1035 // Set calculated linkage, visibility and unnamed_addr.
1036 DGV->setLinkage(NewLinkage);
1037 DGV->setVisibility(*NewVisibility);
1038 DGV->setUnnamedAddr(HasUnnamedAddr);
1043 // Make sure to remember this mapping.
1044 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
1046 // Track the source global so that we don't attempt to copy it over when
1047 // processing global initializers.
1048 DoNotLinkFromSource.insert(SGV);
1054 // If the Comdat this variable was inside of wasn't selected, skip it.
1055 if (DC && !DGV && !LinkFromSrc) {
1056 DoNotLinkFromSource.insert(SGV);
1060 // No linking to be performed or linking from the source: simply create an
1061 // identical version of the symbol over in the dest module... the
1062 // initializer will be filled in later by LinkGlobalInits.
1063 GlobalVariable *NewDGV =
1064 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
1065 SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr,
1066 SGV->getName(), /*insertbefore*/nullptr,
1067 SGV->getThreadLocalMode(),
1068 SGV->getType()->getAddressSpace());
1069 // Propagate alignment, visibility and section info.
1070 copyGVAttributes(NewDGV, SGV);
1071 NewDGV->setAlignment(Alignment);
1073 NewDGV->setVisibility(*NewVisibility);
1074 NewDGV->setUnnamedAddr(HasUnnamedAddr);
1077 NewDGV->setComdat(DC);
1080 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
1081 DGV->eraseFromParent();
1084 // Make sure to remember this mapping.
1085 ValueMap[SGV] = NewDGV;
1089 /// linkFunctionProto - Link the function in the source module into the
1090 /// destination module if needed, setting up mapping information.
1091 bool ModuleLinker::linkFunctionProto(Function *SF) {
1092 GlobalValue *DGV = getLinkedToGlobal(SF);
1093 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1094 bool HasUnnamedAddr = SF->hasUnnamedAddr();
1096 bool LinkFromSrc = false;
1097 Comdat *DC = nullptr;
1098 if (const Comdat *SC = SF->getComdat()) {
1099 Comdat::SelectionKind SK;
1100 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1101 DC = DstM->getOrInsertComdat(SC->getName());
1102 DC->setSelectionKind(SK);
1107 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1108 GlobalValue::VisibilityTypes NV;
1109 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
1112 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1115 // Set calculated linkage
1116 DGV->setLinkage(NewLinkage);
1117 DGV->setVisibility(*NewVisibility);
1118 DGV->setUnnamedAddr(HasUnnamedAddr);
1123 // Make sure to remember this mapping.
1124 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
1126 // Track the function from the source module so we don't attempt to remap
1128 DoNotLinkFromSource.insert(SF);
1134 // If the function is to be lazily linked, don't create it just yet.
1135 // The ValueMaterializerTy will deal with creating it if it's used.
1136 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
1137 SF->hasAvailableExternallyLinkage())) {
1138 DoNotLinkFromSource.insert(SF);
1142 // If the Comdat this function was inside of wasn't selected, skip it.
1143 if (DC && !DGV && !LinkFromSrc) {
1144 DoNotLinkFromSource.insert(SF);
1148 // If there is no linkage to be performed or we are linking from the source,
1150 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
1151 SF->getLinkage(), SF->getName(), DstM);
1152 copyGVAttributes(NewDF, SF);
1154 NewDF->setVisibility(*NewVisibility);
1155 NewDF->setUnnamedAddr(HasUnnamedAddr);
1158 NewDF->setComdat(DC);
1161 // Any uses of DF need to change to NewDF, with cast.
1162 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
1163 DGV->eraseFromParent();
1166 ValueMap[SF] = NewDF;
1170 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
1172 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
1173 GlobalValue *DGV = getLinkedToGlobal(SGA);
1174 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
1175 bool HasUnnamedAddr = SGA->hasUnnamedAddr();
1177 bool LinkFromSrc = false;
1178 Comdat *DC = nullptr;
1179 if (const Comdat *SC = SGA->getComdat()) {
1180 Comdat::SelectionKind SK;
1181 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1182 DC = DstM->getOrInsertComdat(SC->getName());
1183 DC->setSelectionKind(SK);
1188 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
1189 GlobalValue::VisibilityTypes NV;
1190 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
1193 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1196 // Set calculated linkage.
1197 DGV->setLinkage(NewLinkage);
1198 DGV->setVisibility(*NewVisibility);
1199 DGV->setUnnamedAddr(HasUnnamedAddr);
1204 // Make sure to remember this mapping.
1205 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
1207 // Track the alias from the source module so we don't attempt to remap it.
1208 DoNotLinkFromSource.insert(SGA);
1214 // If the Comdat this alias was inside of wasn't selected, skip it.
1215 if (DC && !DGV && !LinkFromSrc) {
1216 DoNotLinkFromSource.insert(SGA);
1220 // If there is no linkage to be performed or we're linking from the source,
1222 auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType()));
1224 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
1225 SGA->getLinkage(), SGA->getName(), DstM);
1226 copyGVAttributes(NewDA, SGA);
1228 NewDA->setVisibility(*NewVisibility);
1229 NewDA->setUnnamedAddr(HasUnnamedAddr);
1232 // Any uses of DGV need to change to NewDA, with cast.
1233 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
1234 DGV->eraseFromParent();
1237 ValueMap[SGA] = NewDA;
1241 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
1242 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1244 for (unsigned i = 0; i != NumElements; ++i)
1245 Dest.push_back(C->getAggregateElement(i));
1248 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
1249 // Merge the initializer.
1250 SmallVector<Constant *, 16> DstElements;
1251 getArrayElements(AVI.DstInit, DstElements);
1253 SmallVector<Constant *, 16> SrcElements;
1254 getArrayElements(AVI.SrcInit, SrcElements);
1256 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1258 StringRef Name = AVI.NewGV->getName();
1259 bool IsNewStructor =
1260 (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1261 cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1263 for (auto *V : SrcElements) {
1264 if (IsNewStructor) {
1265 Constant *Key = V->getAggregateElement(2);
1266 if (DoNotLinkFromSource.count(Key))
1269 DstElements.push_back(
1270 MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer));
1272 if (IsNewStructor) {
1273 NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
1274 AVI.NewGV->mutateType(PointerType::get(NewType, 0));
1277 AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1280 /// linkGlobalInits - Update the initializers in the Dest module now that all
1281 /// globals that may be referenced are in Dest.
1282 void ModuleLinker::linkGlobalInits() {
1283 // Loop over all of the globals in the src module, mapping them over as we go
1284 for (Module::const_global_iterator I = SrcM->global_begin(),
1285 E = SrcM->global_end(); I != E; ++I) {
1287 // Only process initialized GV's or ones not already in dest.
1288 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
1290 // Grab destination global variable.
1291 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
1292 // Figure out what the initializer looks like in the dest module.
1293 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
1294 RF_None, &TypeMap, &ValMaterializer));
1298 /// linkFunctionBody - Copy the source function over into the dest function and
1299 /// fix up references to values. At this point we know that Dest is an external
1300 /// function, and that Src is not.
1301 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
1302 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
1304 // Go through and convert function arguments over, remembering the mapping.
1305 Function::arg_iterator DI = Dst->arg_begin();
1306 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1307 I != E; ++I, ++DI) {
1308 DI->setName(I->getName()); // Copy the name over.
1310 // Add a mapping to our mapping.
1314 if (Mode == Linker::DestroySource) {
1315 // Splice the body of the source function into the dest function.
1316 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
1318 // At this point, all of the instructions and values of the function are now
1319 // copied over. The only problem is that they are still referencing values in
1320 // the Source function as operands. Loop through all of the operands of the
1321 // functions and patch them up to point to the local versions.
1322 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
1323 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1324 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
1325 &TypeMap, &ValMaterializer);
1328 // Clone the body of the function into the dest function.
1329 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1330 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr,
1331 &TypeMap, &ValMaterializer);
1334 // There is no need to map the arguments anymore.
1335 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1341 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1342 void ModuleLinker::linkAliasBodies() {
1343 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1345 if (DoNotLinkFromSource.count(I))
1347 if (Constant *Aliasee = I->getAliasee()) {
1348 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1350 MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer);
1351 DA->setAliasee(Val);
1356 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1358 void ModuleLinker::linkNamedMDNodes() {
1359 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1360 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1361 E = SrcM->named_metadata_end(); I != E; ++I) {
1362 // Don't link module flags here. Do them separately.
1363 if (&*I == SrcModFlags) continue;
1364 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1365 // Add Src elements into Dest node.
1366 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1367 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1368 RF_None, &TypeMap, &ValMaterializer));
1372 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1374 bool ModuleLinker::linkModuleFlagsMetadata() {
1375 // If the source module has no module flags, we are done.
1376 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1377 if (!SrcModFlags) return false;
1379 // If the destination module doesn't have module flags yet, then just copy
1380 // over the source module's flags.
1381 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1382 if (DstModFlags->getNumOperands() == 0) {
1383 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1384 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1389 // First build a map of the existing module flags and requirements.
1390 DenseMap<MDString*, MDNode*> Flags;
1391 SmallSetVector<MDNode*, 16> Requirements;
1392 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1393 MDNode *Op = DstModFlags->getOperand(I);
1394 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1395 MDString *ID = cast<MDString>(Op->getOperand(1));
1397 if (Behavior->getZExtValue() == Module::Require) {
1398 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1404 // Merge in the flags from the source module, and also collect its set of
1406 bool HasErr = false;
1407 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1408 MDNode *SrcOp = SrcModFlags->getOperand(I);
1409 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1410 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1411 MDNode *DstOp = Flags.lookup(ID);
1412 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1414 // If this is a requirement, add it and continue.
1415 if (SrcBehaviorValue == Module::Require) {
1416 // If the destination module does not already have this requirement, add
1418 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1419 DstModFlags->addOperand(SrcOp);
1424 // If there is no existing flag with this ID, just add it.
1427 DstModFlags->addOperand(SrcOp);
1431 // Otherwise, perform a merge.
1432 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1433 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1435 // If either flag has override behavior, handle it first.
1436 if (DstBehaviorValue == Module::Override) {
1437 // Diagnose inconsistent flags which both have override behavior.
1438 if (SrcBehaviorValue == Module::Override &&
1439 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1440 HasErr |= emitError("linking module flags '" + ID->getString() +
1441 "': IDs have conflicting override values");
1444 } else if (SrcBehaviorValue == Module::Override) {
1445 // Update the destination flag to that of the source.
1446 DstOp->replaceOperandWith(0, SrcBehavior);
1447 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1451 // Diagnose inconsistent merge behavior types.
1452 if (SrcBehaviorValue != DstBehaviorValue) {
1453 HasErr |= emitError("linking module flags '" + ID->getString() +
1454 "': IDs have conflicting behaviors");
1458 // Perform the merge for standard behavior types.
1459 switch (SrcBehaviorValue) {
1460 case Module::Require:
1461 case Module::Override: llvm_unreachable("not possible");
1462 case Module::Error: {
1463 // Emit an error if the values differ.
1464 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1465 HasErr |= emitError("linking module flags '" + ID->getString() +
1466 "': IDs have conflicting values");
1470 case Module::Warning: {
1471 // Emit a warning if the values differ.
1472 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1473 if (!SuppressWarnings) {
1474 errs() << "WARNING: linking module flags '" << ID->getString()
1475 << "': IDs have conflicting values";
1480 case Module::Append: {
1481 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1482 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1483 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1484 Value **VP, **Values = VP = new Value*[NumOps];
1485 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1486 *VP = DstValue->getOperand(i);
1487 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1488 *VP = SrcValue->getOperand(i);
1489 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1490 ArrayRef<Value*>(Values,
1495 case Module::AppendUnique: {
1496 SmallSetVector<Value*, 16> Elts;
1497 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1498 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1499 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1500 Elts.insert(DstValue->getOperand(i));
1501 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1502 Elts.insert(SrcValue->getOperand(i));
1503 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1504 ArrayRef<Value*>(Elts.begin(),
1511 // Check all of the requirements.
1512 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1513 MDNode *Requirement = Requirements[I];
1514 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1515 Value *ReqValue = Requirement->getOperand(1);
1517 MDNode *Op = Flags[Flag];
1518 if (!Op || Op->getOperand(2) != ReqValue) {
1519 HasErr |= emitError("linking module flags '" + Flag->getString() +
1520 "': does not have the required value");
1528 bool ModuleLinker::run() {
1529 assert(DstM && "Null destination module");
1530 assert(SrcM && "Null source module");
1532 // Inherit the target data from the source module if the destination module
1533 // doesn't have one already.
1534 if (!DstM->getDataLayout() && SrcM->getDataLayout())
1535 DstM->setDataLayout(SrcM->getDataLayout());
1537 // Copy the target triple from the source to dest if the dest's is empty.
1538 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1539 DstM->setTargetTriple(SrcM->getTargetTriple());
1541 if (SrcM->getDataLayout() && DstM->getDataLayout() &&
1542 *SrcM->getDataLayout() != *DstM->getDataLayout()) {
1543 if (!SuppressWarnings) {
1544 errs() << "WARNING: Linking two modules of different data layouts: '"
1545 << SrcM->getModuleIdentifier() << "' is '"
1546 << SrcM->getDataLayoutStr() << "' whereas '"
1547 << DstM->getModuleIdentifier() << "' is '"
1548 << DstM->getDataLayoutStr() << "'\n";
1551 if (!SrcM->getTargetTriple().empty() &&
1552 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1553 if (!SuppressWarnings) {
1554 errs() << "WARNING: Linking two modules of different target triples: "
1555 << SrcM->getModuleIdentifier() << "' is '"
1556 << SrcM->getTargetTriple() << "' whereas '"
1557 << DstM->getModuleIdentifier() << "' is '"
1558 << DstM->getTargetTriple() << "'\n";
1562 // Append the module inline asm string.
1563 if (!SrcM->getModuleInlineAsm().empty()) {
1564 if (DstM->getModuleInlineAsm().empty())
1565 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1567 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1568 SrcM->getModuleInlineAsm());
1571 // Loop over all of the linked values to compute type mappings.
1572 computeTypeMapping();
1574 ComdatsChosen.clear();
1575 for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) {
1576 const Comdat &C = SMEC.getValue();
1577 if (ComdatsChosen.count(&C))
1579 Comdat::SelectionKind SK;
1581 if (getComdatResult(&C, SK, LinkFromSrc))
1583 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1586 // Upgrade mismatched global arrays.
1587 upgradeMismatchedGlobals();
1589 // Insert all of the globals in src into the DstM module... without linking
1590 // initializers (which could refer to functions not yet mapped over).
1591 for (Module::global_iterator I = SrcM->global_begin(),
1592 E = SrcM->global_end(); I != E; ++I)
1593 if (linkGlobalProto(I))
1596 // Link the functions together between the two modules, without doing function
1597 // bodies... this just adds external function prototypes to the DstM
1598 // function... We do this so that when we begin processing function bodies,
1599 // all of the global values that may be referenced are available in our
1601 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1602 if (linkFunctionProto(I))
1605 // If there were any aliases, link them now.
1606 for (Module::alias_iterator I = SrcM->alias_begin(),
1607 E = SrcM->alias_end(); I != E; ++I)
1608 if (linkAliasProto(I))
1611 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1612 linkAppendingVarInit(AppendingVars[i]);
1614 // Link in the function bodies that are defined in the source module into
1616 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1617 // Skip if not linking from source.
1618 if (DoNotLinkFromSource.count(SF)) continue;
1620 Function *DF = cast<Function>(ValueMap[SF]);
1621 if (SF->hasPrefixData()) {
1622 // Link in the prefix data.
1623 DF->setPrefixData(MapValue(
1624 SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1627 // Materialize if needed.
1628 if (SF->isMaterializable()) {
1629 if (std::error_code EC = SF->materialize()) {
1630 ErrorMsg = EC.message();
1635 // Skip if no body (function is external).
1636 if (SF->isDeclaration())
1639 linkFunctionBody(DF, SF);
1640 SF->Dematerialize();
1643 // Resolve all uses of aliases with aliasees.
1646 // Remap all of the named MDNodes in Src into the DstM module. We do this
1647 // after linking GlobalValues so that MDNodes that reference GlobalValues
1648 // are properly remapped.
1651 // Merge the module flags into the DstM module.
1652 if (linkModuleFlagsMetadata())
1655 // Update the initializers in the DstM module now that all globals that may
1656 // be referenced are in DstM.
1659 // Process vector of lazily linked in functions.
1660 bool LinkedInAnyFunctions;
1662 LinkedInAnyFunctions = false;
1664 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1665 E = LazilyLinkFunctions.end(); I != E; ++I) {
1670 Function *DF = cast<Function>(ValueMap[SF]);
1671 if (SF->hasPrefixData()) {
1672 // Link in the prefix data.
1673 DF->setPrefixData(MapValue(SF->getPrefixData(),
1680 // Materialize if needed.
1681 if (SF->isMaterializable()) {
1682 if (std::error_code EC = SF->materialize()) {
1683 ErrorMsg = EC.message();
1688 // Skip if no body (function is external).
1689 if (SF->isDeclaration())
1692 // Erase from vector *before* the function body is linked - linkFunctionBody could
1694 LazilyLinkFunctions.erase(I);
1696 // Link in function body.
1697 linkFunctionBody(DF, SF);
1698 SF->Dematerialize();
1700 // Set flag to indicate we may have more functions to lazily link in
1701 // since we linked in a function.
1702 LinkedInAnyFunctions = true;
1705 } while (LinkedInAnyFunctions);
1707 // Now that all of the types from the source are used, resolve any structs
1708 // copied over to the dest that didn't exist there.
1709 TypeMap.linkDefinedTypeBodies();
1714 Linker::Linker(Module *M, bool SuppressWarnings)
1715 : Composite(M), SuppressWarnings(SuppressWarnings) {
1716 TypeFinder StructTypes;
1717 StructTypes.run(*M, true);
1718 IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1724 void Linker::deleteModule() {
1726 Composite = nullptr;
1729 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1730 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode,
1732 if (TheLinker.run()) {
1734 *ErrorMsg = TheLinker.ErrorMsg;
1740 //===----------------------------------------------------------------------===//
1741 // LinkModules entrypoint.
1742 //===----------------------------------------------------------------------===//
1744 /// LinkModules - This function links two modules together, with the resulting
1745 /// Dest module modified to be the composite of the two input modules. If an
1746 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1747 /// the problem. Upon failure, the Dest module could be in a modified state,
1748 /// and shouldn't be relied on to be consistent.
1749 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1750 std::string *ErrorMsg) {
1752 return L.linkInModule(Src, Mode, ErrorMsg);
1755 //===----------------------------------------------------------------------===//
1757 //===----------------------------------------------------------------------===//
1759 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1760 LLVMLinkerMode Mode, char **OutMessages) {
1761 std::string Messages;
1762 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1763 Mode, OutMessages? &Messages : nullptr);
1765 *OutMessages = strdup(Messages.c_str());