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/SetVector.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/TypeFinder.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
28 //===----------------------------------------------------------------------===//
29 // TypeMap implementation.
30 //===----------------------------------------------------------------------===//
33 class TypeMapTy : public ValueMapTypeRemapper {
34 /// This is a mapping from a source type to a destination type to use.
35 DenseMap<Type *, Type *> MappedTypes;
37 /// When checking to see if two subgraphs are isomorphic, we speculatively
38 /// add types to MappedTypes, but keep track of them here in case we need to
40 SmallVector<Type *, 16> SpeculativeTypes;
42 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
44 /// This is a list of non-opaque structs in the source module that are mapped
45 /// to an opaque struct in the destination module.
46 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
48 /// This is the set of opaque types in the destination modules who are
49 /// getting a body from the source module.
50 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
53 TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
54 : DstStructTypesSet(DstStructTypesSet) {}
56 Linker::IdentifiedStructTypeSet &DstStructTypesSet;
57 /// Indicate that the specified type in the destination module is conceptually
58 /// equivalent to the specified type in the source module.
59 void addTypeMapping(Type *DstTy, Type *SrcTy);
61 /// Produce a body for an opaque type in the dest module from a type
62 /// definition in the source module.
63 void linkDefinedTypeBodies();
65 /// Return the mapped type to use for the specified input type from the
67 Type *get(Type *SrcTy);
68 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
70 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
72 FunctionType *get(FunctionType *T) {
73 return cast<FunctionType>(get((Type *)T));
76 /// Dump out the type map for debugging purposes.
78 for (auto &Pair : MappedTypes) {
79 dbgs() << "TypeMap: ";
80 Pair.first->print(dbgs());
82 Pair.second->print(dbgs());
88 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
90 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
94 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
95 assert(SpeculativeTypes.empty());
96 assert(SpeculativeDstOpaqueTypes.empty());
98 // Check to see if these types are recursively isomorphic and establish a
99 // mapping between them if so.
100 if (!areTypesIsomorphic(DstTy, SrcTy)) {
101 // Oops, they aren't isomorphic. Just discard this request by rolling out
102 // any speculative mappings we've established.
103 for (Type *Ty : SpeculativeTypes)
104 MappedTypes.erase(Ty);
106 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
107 SpeculativeDstOpaqueTypes.size());
108 for (StructType *Ty : SpeculativeDstOpaqueTypes)
109 DstResolvedOpaqueTypes.erase(Ty);
111 for (Type *Ty : SpeculativeTypes)
112 if (auto *STy = dyn_cast<StructType>(Ty))
116 SpeculativeTypes.clear();
117 SpeculativeDstOpaqueTypes.clear();
120 /// Recursively walk this pair of types, returning true if they are isomorphic,
121 /// false if they are not.
122 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
123 // Two types with differing kinds are clearly not isomorphic.
124 if (DstTy->getTypeID() != SrcTy->getTypeID())
127 // If we have an entry in the MappedTypes table, then we have our answer.
128 Type *&Entry = MappedTypes[SrcTy];
130 return Entry == DstTy;
132 // Two identical types are clearly isomorphic. Remember this
133 // non-speculatively.
134 if (DstTy == SrcTy) {
139 // Okay, we have two types with identical kinds that we haven't seen before.
141 // If this is an opaque struct type, special case it.
142 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
143 // Mapping an opaque type to any struct, just keep the dest struct.
144 if (SSTy->isOpaque()) {
146 SpeculativeTypes.push_back(SrcTy);
150 // Mapping a non-opaque source type to an opaque dest. If this is the first
151 // type that we're mapping onto this destination type then we succeed. Keep
152 // the dest, but fill it in later. If this is the second (different) type
153 // that we're trying to map onto the same opaque type then we fail.
154 if (cast<StructType>(DstTy)->isOpaque()) {
155 // We can only map one source type onto the opaque destination type.
156 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
158 SrcDefinitionsToResolve.push_back(SSTy);
159 SpeculativeTypes.push_back(SrcTy);
160 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
166 // If the number of subtypes disagree between the two types, then we fail.
167 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
170 // Fail if any of the extra properties (e.g. array size) of the type disagree.
171 if (isa<IntegerType>(DstTy))
172 return false; // bitwidth disagrees.
173 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
177 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
180 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181 StructType *SSTy = cast<StructType>(SrcTy);
182 if (DSTy->isLiteral() != SSTy->isLiteral() ||
183 DSTy->isPacked() != SSTy->isPacked())
185 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
188 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
189 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
193 // Otherwise, we speculate that these two types will line up and recursively
194 // check the subelements.
196 SpeculativeTypes.push_back(SrcTy);
198 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
199 if (!areTypesIsomorphic(DstTy->getContainedType(I),
200 SrcTy->getContainedType(I)))
203 // If everything seems to have lined up, then everything is great.
207 void TypeMapTy::linkDefinedTypeBodies() {
208 SmallVector<Type *, 16> Elements;
209 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
210 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
211 assert(DstSTy->isOpaque());
213 // Map the body of the source type over to a new body for the dest type.
214 Elements.resize(SrcSTy->getNumElements());
215 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
216 Elements[I] = get(SrcSTy->getElementType(I));
218 DstSTy->setBody(Elements, SrcSTy->isPacked());
219 DstStructTypesSet.switchToNonOpaque(DstSTy);
221 SrcDefinitionsToResolve.clear();
222 DstResolvedOpaqueTypes.clear();
225 void TypeMapTy::finishType(StructType *DTy, StructType *STy,
226 ArrayRef<Type *> ETypes) {
227 DTy->setBody(ETypes, STy->isPacked());
230 if (STy->hasName()) {
231 SmallString<16> TmpName = STy->getName();
233 DTy->setName(TmpName);
236 DstStructTypesSet.addNonOpaque(DTy);
239 Type *TypeMapTy::get(Type *Ty) {
240 SmallPtrSet<StructType *, 8> Visited;
241 return get(Ty, Visited);
244 Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
245 // If we already have an entry for this type, return it.
246 Type **Entry = &MappedTypes[Ty];
250 // These are types that LLVM itself will unique.
251 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
255 for (auto &Pair : MappedTypes) {
256 assert(!(Pair.first != Ty && Pair.second == Ty) &&
257 "mapping to a source type");
262 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
263 StructType *DTy = StructType::create(Ty->getContext());
267 // If this is not a recursive type, then just map all of the elements and
268 // then rebuild the type from inside out.
269 SmallVector<Type *, 4> ElementTypes;
271 // If there are no element types to map, then the type is itself. This is
272 // true for the anonymous {} struct, things like 'float', integers, etc.
273 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
276 // Remap all of the elements, keeping track of whether any of them change.
277 bool AnyChange = false;
278 ElementTypes.resize(Ty->getNumContainedTypes());
279 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
280 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
281 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
284 // If we found our type while recursively processing stuff, just use it.
285 Entry = &MappedTypes[Ty];
287 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
288 if (DTy->isOpaque()) {
289 auto *STy = cast<StructType>(Ty);
290 finishType(DTy, STy, ElementTypes);
296 // If all of the element types mapped directly over and the type is not
297 // a nomed struct, then the type is usable as-is.
298 if (!AnyChange && IsUniqued)
301 // Otherwise, rebuild a modified type.
302 switch (Ty->getTypeID()) {
304 llvm_unreachable("unknown derived type to remap");
305 case Type::ArrayTyID:
306 return *Entry = ArrayType::get(ElementTypes[0],
307 cast<ArrayType>(Ty)->getNumElements());
308 case Type::VectorTyID:
309 return *Entry = VectorType::get(ElementTypes[0],
310 cast<VectorType>(Ty)->getNumElements());
311 case Type::PointerTyID:
312 return *Entry = PointerType::get(ElementTypes[0],
313 cast<PointerType>(Ty)->getAddressSpace());
314 case Type::FunctionTyID:
315 return *Entry = FunctionType::get(ElementTypes[0],
316 makeArrayRef(ElementTypes).slice(1),
317 cast<FunctionType>(Ty)->isVarArg());
318 case Type::StructTyID: {
319 auto *STy = cast<StructType>(Ty);
320 bool IsPacked = STy->isPacked();
322 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
324 // If the type is opaque, we can just use it directly.
325 if (STy->isOpaque()) {
326 DstStructTypesSet.addOpaque(STy);
330 if (StructType *OldT =
331 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
333 return *Entry = OldT;
337 DstStructTypesSet.addNonOpaque(STy);
341 StructType *DTy = StructType::create(Ty->getContext());
342 finishType(DTy, STy, ElementTypes);
348 //===----------------------------------------------------------------------===//
349 // ModuleLinker implementation.
350 //===----------------------------------------------------------------------===//
355 /// Creates prototypes for functions that are lazily linked on the fly. This
356 /// speeds up linking for modules with many/ lazily linked functions of which
358 class ValueMaterializerTy final : public ValueMaterializer {
359 ModuleLinker *ModLinker;
362 ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
364 Value *materializeDeclFor(Value *V) override;
365 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
368 class LinkDiagnosticInfo : public DiagnosticInfo {
372 LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
373 void print(DiagnosticPrinter &DP) const override;
375 LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
377 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
378 void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
380 /// This is an implementation class for the LinkModules function, which is the
381 /// entrypoint for this file.
387 ValueMaterializerTy ValMaterializer;
389 /// Mapping of values from what they used to be in Src, to what they are now
390 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
391 /// due to the use of Value handles which the Linker doesn't actually need,
392 /// but this allows us to reuse the ValueMapper code.
393 ValueToValueMapTy ValueMap;
395 SetVector<GlobalValue *> ValuesToLink;
397 DiagnosticHandlerFunction DiagnosticHandler;
399 /// For symbol clashes, prefer those from Src.
402 /// Function index passed into ModuleLinker for using in function
403 /// importing/exporting handling.
404 const FunctionInfoIndex *ImportIndex;
406 /// Function to import from source module, all other functions are
407 /// imported as declarations instead of definitions.
408 DenseSet<const GlobalValue *> *ImportFunction;
410 /// Set to true if the given FunctionInfoIndex contains any functions
411 /// from this source module, in which case we must conservatively assume
412 /// that any of its functions may be imported into another module
413 /// as part of a different backend compilation process.
414 bool HasExportedFunctions = false;
416 /// Set to true when all global value body linking is complete (including
417 /// lazy linking). Used to prevent metadata linking from creating new
419 bool DoneLinkingBodies = false;
421 bool HasError = false;
423 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
424 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
425 bool shouldInternalizeLinkedSymbols() {
426 return Flags & Linker::InternalizeLinkedSymbols;
429 /// Handles cloning of a global values from the source module into
430 /// the destination module, including setting the attributes and visibility.
431 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
433 /// Check if we should promote the given local value to global scope.
434 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
436 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
437 const GlobalValue &Src);
439 /// Helper method for setting a message and returning an error code.
440 bool emitError(const Twine &Message) {
441 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
446 void emitWarning(const Twine &Message) {
447 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
450 bool getComdatLeader(Module &M, StringRef ComdatName,
451 const GlobalVariable *&GVar);
452 bool computeResultingSelectionKind(StringRef ComdatName,
453 Comdat::SelectionKind Src,
454 Comdat::SelectionKind Dst,
455 Comdat::SelectionKind &Result,
457 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
459 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
461 // Keep track of the global value members of each comdat in source.
462 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
464 /// Given a global in the source module, return the global in the
465 /// destination module that is being linked to, if any.
466 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
467 // If the source has no name it can't link. If it has local linkage,
468 // there is no name match-up going on.
469 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
472 // Otherwise see if we have a match in the destination module's symtab.
473 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
477 // If we found a global with the same name in the dest module, but it has
478 // internal linkage, we are really not doing any linkage here.
479 if (DGV->hasLocalLinkage())
482 // Otherwise, we do in fact link to the destination global.
486 void computeTypeMapping();
488 bool linkIfNeeded(GlobalValue &GV);
489 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
490 const GlobalVariable *SrcGV);
492 Constant *linkGlobalValueProto(GlobalValue *GV);
493 bool linkModuleFlagsMetadata();
495 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
496 bool linkFunctionBody(Function &Dst, Function &Src);
497 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
498 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
500 /// Functions that take care of cloning a specific global value type
501 /// into the destination module.
502 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
503 Function *copyFunctionProto(const Function *SF);
504 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
506 /// Helper methods to check if we are importing from or potentially
507 /// exporting from the current source module.
508 bool isPerformingImport() { return ImportFunction != nullptr; }
509 bool isModuleExporting() { return HasExportedFunctions; }
511 /// If we are importing from the source module, checks if we should
512 /// import SGV as a definition, otherwise import as a declaration.
513 bool doImportAsDefinition(const GlobalValue *SGV);
515 /// Get the name for SGV that should be used in the linked destination
516 /// module. Specifically, this handles the case where we need to rename
517 /// a local that is being promoted to global scope.
518 std::string getName(const GlobalValue *SGV);
520 /// Get the new linkage for SGV that should be used in the linked destination
521 /// module. Specifically, for ThinLTO importing or exporting it may need
523 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
525 /// Copies the necessary global value attributes and name from the source
526 /// to the newly cloned global value.
527 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
529 /// Updates the visibility for the new global cloned from the source
530 /// and, if applicable, linked with an existing destination global.
531 /// Handles visibility change required for promoted locals.
532 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
533 const GlobalValue *DGV = nullptr);
535 void linkNamedMDNodes();
538 ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
539 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
540 const FunctionInfoIndex *Index = nullptr,
541 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
542 : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
543 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
544 ImportFunction(FunctionsToImport) {
545 assert((ImportIndex || !ImportFunction) &&
546 "Expect a FunctionInfoIndex when importing");
547 // If we have a FunctionInfoIndex but no function to import,
548 // then this is the primary module being compiled in a ThinLTO
549 // backend compilation, and we need to see if it has functions that
550 // may be exported to another backend compilation.
551 if (ImportIndex && !ImportFunction)
552 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
556 Value *materializeDeclFor(Value *V);
557 void materializeInitFor(GlobalValue *New, GlobalValue *Old);
561 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
562 /// table. This is good for all clients except for us. Go through the trouble
563 /// to force this back.
564 static void forceRenaming(GlobalValue *GV, StringRef Name) {
565 // If the global doesn't force its name or if it already has the right name,
566 // there is nothing for us to do.
567 // Note that any required local to global promotion should already be done,
568 // so promoted locals will not skip this handling as their linkage is no
570 if (GV->hasLocalLinkage() || GV->getName() == Name)
573 Module *M = GV->getParent();
575 // If there is a conflict, rename the conflict.
576 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
577 GV->takeName(ConflictGV);
578 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
579 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
581 GV->setName(Name); // Force the name back
585 /// copy additional attributes (those not needed to construct a GlobalValue)
586 /// from the SrcGV to the DestGV.
587 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
588 const GlobalValue *SrcGV) {
589 NewGV->copyAttributesFrom(SrcGV);
590 forceRenaming(NewGV, getName(SrcGV));
593 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
594 if (!isPerformingImport())
596 auto *GA = dyn_cast<GlobalAlias>(SGV);
598 if (GA->hasWeakAnyLinkage())
600 const GlobalObject *GO = GA->getBaseObject();
601 if (!GO->hasLinkOnceODRLinkage())
603 return doImportAsDefinition(GO);
605 // Always import GlobalVariable definitions, except for the special
606 // case of WeakAny which are imported as ExternalWeak declarations
607 // (see comments in ModuleLinker::getLinkage). The linkage changes
608 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
609 // global variables with external linkage are transformed to
610 // available_externally definitions, which are ultimately turned into
611 // declarations after the EliminateAvailableExternally pass).
612 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
613 !SGV->hasWeakAnyLinkage())
615 // Only import the function requested for importing.
616 auto *SF = dyn_cast<Function>(SGV);
617 if (SF && ImportFunction->count(SF))
623 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
624 assert(SGV->hasLocalLinkage());
625 // Both the imported references and the original local variable must
627 if (!isPerformingImport() && !isModuleExporting())
630 // Local const variables never need to be promoted unless they are address
631 // taken. The imported uses can simply use the clone created in this module.
632 // For now we are conservative in determining which variables are not
633 // address taken by checking the unnamed addr flag. To be more aggressive,
634 // the address taken information must be checked earlier during parsing
635 // of the module and recorded in the function index for use when importing
637 auto *GVar = dyn_cast<GlobalVariable>(SGV);
638 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
641 // Eventually we only need to promote functions in the exporting module that
642 // are referenced by a potentially exported function (i.e. one that is in the
647 std::string ModuleLinker::getName(const GlobalValue *SGV) {
648 // For locals that must be promoted to global scope, ensure that
649 // the promoted name uniquely identifies the copy in the original module,
650 // using the ID assigned during combined index creation. When importing,
651 // we rename all locals (not just those that are promoted) in order to
652 // avoid naming conflicts between locals imported from different modules.
653 if (SGV->hasLocalLinkage() &&
654 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
655 return FunctionInfoIndex::getGlobalNameForLocal(
657 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
658 return SGV->getName();
661 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
662 // Any local variable that is referenced by an exported function needs
663 // to be promoted to global scope. Since we don't currently know which
664 // functions reference which local variables/functions, we must treat
665 // all as potentially exported if this module is exporting anything.
666 if (isModuleExporting()) {
667 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
668 return GlobalValue::ExternalLinkage;
669 return SGV->getLinkage();
672 // Otherwise, if we aren't importing, no linkage change is needed.
673 if (!isPerformingImport())
674 return SGV->getLinkage();
676 switch (SGV->getLinkage()) {
677 case GlobalValue::ExternalLinkage:
678 // External defnitions are converted to available_externally
679 // definitions upon import, so that they are available for inlining
680 // and/or optimization, but are turned into declarations later
681 // during the EliminateAvailableExternally pass.
682 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
683 return GlobalValue::AvailableExternallyLinkage;
684 // An imported external declaration stays external.
685 return SGV->getLinkage();
687 case GlobalValue::AvailableExternallyLinkage:
688 // An imported available_externally definition converts
689 // to external if imported as a declaration.
690 if (!doImportAsDefinition(SGV))
691 return GlobalValue::ExternalLinkage;
692 // An imported available_externally declaration stays that way.
693 return SGV->getLinkage();
695 case GlobalValue::LinkOnceAnyLinkage:
696 case GlobalValue::LinkOnceODRLinkage:
697 // These both stay the same when importing the definition.
698 // The ThinLTO pass will eventually force-import their definitions.
699 return SGV->getLinkage();
701 case GlobalValue::WeakAnyLinkage:
702 // Can't import weak_any definitions correctly, or we might change the
703 // program semantics, since the linker will pick the first weak_any
704 // definition and importing would change the order they are seen by the
705 // linker. The module linking caller needs to enforce this.
706 assert(!doImportAsDefinition(SGV));
707 // If imported as a declaration, it becomes external_weak.
708 return GlobalValue::ExternalWeakLinkage;
710 case GlobalValue::WeakODRLinkage:
711 // For weak_odr linkage, there is a guarantee that all copies will be
712 // equivalent, so the issue described above for weak_any does not exist,
713 // and the definition can be imported. It can be treated similarly
714 // to an imported externally visible global value.
715 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
716 return GlobalValue::AvailableExternallyLinkage;
718 return GlobalValue::ExternalLinkage;
720 case GlobalValue::AppendingLinkage:
721 // It would be incorrect to import an appending linkage variable,
722 // since it would cause global constructors/destructors to be
723 // executed multiple times. This should have already been handled
724 // by linkIfNeeded, and we will assert in shouldLinkFromSource
725 // if we try to import, so we simply return AppendingLinkage here
726 // as this helper is called more widely in getLinkedToGlobal.
727 return GlobalValue::AppendingLinkage;
729 case GlobalValue::InternalLinkage:
730 case GlobalValue::PrivateLinkage:
731 // If we are promoting the local to global scope, it is handled
732 // similarly to a normal externally visible global.
733 if (doPromoteLocalToGlobal(SGV)) {
734 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
735 return GlobalValue::AvailableExternallyLinkage;
737 return GlobalValue::ExternalLinkage;
739 // A non-promoted imported local definition stays local.
740 // The ThinLTO pass will eventually force-import their definitions.
741 return SGV->getLinkage();
743 case GlobalValue::ExternalWeakLinkage:
744 // External weak doesn't apply to definitions, must be a declaration.
745 assert(!doImportAsDefinition(SGV));
746 // Linkage stays external_weak.
747 return SGV->getLinkage();
749 case GlobalValue::CommonLinkage:
750 // Linkage stays common on definitions.
751 // The ThinLTO pass will eventually force-import their definitions.
752 return SGV->getLinkage();
755 llvm_unreachable("unknown linkage type");
758 /// Loop through the global variables in the src module and merge them into the
761 ModuleLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
762 // No linking to be performed or linking from the source: simply create an
763 // identical version of the symbol over in the dest module... the
764 // initializer will be filled in later by LinkGlobalInits.
765 GlobalVariable *NewDGV =
766 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
767 SGVar->isConstant(), GlobalValue::ExternalLinkage,
768 /*init*/ nullptr, getName(SGVar),
769 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
770 SGVar->getType()->getAddressSpace());
775 /// Link the function in the source module into the destination module if
776 /// needed, setting up mapping information.
777 Function *ModuleLinker::copyFunctionProto(const Function *SF) {
778 // If there is no linkage to be performed or we are linking from the source,
780 return Function::Create(TypeMap.get(SF->getFunctionType()),
781 GlobalValue::ExternalLinkage, getName(SF), &DstM);
784 /// Set up prototypes for any aliases that come over from the source module.
785 GlobalValue *ModuleLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
786 // If there is no linkage to be performed or we're linking from the source,
788 auto *Ty = TypeMap.get(SGA->getValueType());
789 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
790 GlobalValue::ExternalLinkage, getName(SGA), &DstM);
793 static GlobalValue::VisibilityTypes
794 getMinVisibility(GlobalValue::VisibilityTypes A,
795 GlobalValue::VisibilityTypes B) {
796 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
797 return GlobalValue::HiddenVisibility;
798 if (A == GlobalValue::ProtectedVisibility ||
799 B == GlobalValue::ProtectedVisibility)
800 return GlobalValue::ProtectedVisibility;
801 return GlobalValue::DefaultVisibility;
804 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
805 const GlobalValue *DGV) {
806 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
808 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
809 // For promoted locals, mark them hidden so that they can later be
810 // stripped from the symbol table to reduce bloat.
811 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
812 Visibility = GlobalValue::HiddenVisibility;
813 NewGV->setVisibility(Visibility);
816 GlobalValue *ModuleLinker::copyGlobalValueProto(const GlobalValue *SGV,
817 bool ForDefinition) {
819 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
820 NewGV = copyGlobalVariableProto(SGVar);
821 } else if (auto *SF = dyn_cast<Function>(SGV)) {
822 NewGV = copyFunctionProto(SF);
825 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
827 NewGV = new GlobalVariable(
828 DstM, TypeMap.get(SGV->getType()->getElementType()),
829 /*isConstant*/ false, GlobalValue::ExternalLinkage,
830 /*init*/ nullptr, getName(SGV),
831 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
832 SGV->getType()->getAddressSpace());
836 NewGV->setLinkage(getLinkage(SGV));
837 else if (SGV->hasAvailableExternallyLinkage() || SGV->hasWeakLinkage() ||
838 SGV->hasLinkOnceLinkage())
839 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
841 copyGVAttributes(NewGV, SGV);
845 Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
846 return ModLinker->materializeDeclFor(V);
849 Value *ModuleLinker::materializeDeclFor(Value *V) {
850 auto *SGV = dyn_cast<GlobalValue>(V);
854 return linkGlobalValueProto(SGV);
857 void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
859 return ModLinker->materializeInitFor(New, Old);
862 static bool shouldLazyLink(const GlobalValue &GV) {
863 return GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
864 GV.hasAvailableExternallyLinkage();
867 void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
868 if (auto *F = dyn_cast<Function>(New)) {
869 if (!F->isDeclaration())
871 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
872 if (V->hasInitializer())
875 auto *A = cast<GlobalAlias>(New);
880 if (Old->isDeclaration())
883 if (isPerformingImport() && !doImportAsDefinition(Old))
886 if (!ValuesToLink.count(Old) && !shouldLazyLink(*Old))
889 linkGlobalValueBody(*New, *Old);
892 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
893 const GlobalVariable *&GVar) {
894 const GlobalValue *GVal = M.getNamedValue(ComdatName);
895 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
896 GVal = GA->getBaseObject();
898 // We cannot resolve the size of the aliasee yet.
899 return emitError("Linking COMDATs named '" + ComdatName +
900 "': COMDAT key involves incomputable alias size.");
903 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
906 "Linking COMDATs named '" + ComdatName +
907 "': GlobalVariable required for data dependent selection!");
912 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
913 Comdat::SelectionKind Src,
914 Comdat::SelectionKind Dst,
915 Comdat::SelectionKind &Result,
917 // The ability to mix Comdat::SelectionKind::Any with
918 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
919 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
920 Dst == Comdat::SelectionKind::Largest;
921 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
922 Src == Comdat::SelectionKind::Largest;
923 if (DstAnyOrLargest && SrcAnyOrLargest) {
924 if (Dst == Comdat::SelectionKind::Largest ||
925 Src == Comdat::SelectionKind::Largest)
926 Result = Comdat::SelectionKind::Largest;
928 Result = Comdat::SelectionKind::Any;
929 } else if (Src == Dst) {
932 return emitError("Linking COMDATs named '" + ComdatName +
933 "': invalid selection kinds!");
937 case Comdat::SelectionKind::Any:
941 case Comdat::SelectionKind::NoDuplicates:
942 return emitError("Linking COMDATs named '" + ComdatName +
943 "': noduplicates has been violated!");
944 case Comdat::SelectionKind::ExactMatch:
945 case Comdat::SelectionKind::Largest:
946 case Comdat::SelectionKind::SameSize: {
947 const GlobalVariable *DstGV;
948 const GlobalVariable *SrcGV;
949 if (getComdatLeader(DstM, ComdatName, DstGV) ||
950 getComdatLeader(SrcM, ComdatName, SrcGV))
953 const DataLayout &DstDL = DstM.getDataLayout();
954 const DataLayout &SrcDL = SrcM.getDataLayout();
956 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
958 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
959 if (Result == Comdat::SelectionKind::ExactMatch) {
960 if (SrcGV->getInitializer() != DstGV->getInitializer())
961 return emitError("Linking COMDATs named '" + ComdatName +
962 "': ExactMatch violated!");
964 } else if (Result == Comdat::SelectionKind::Largest) {
965 LinkFromSrc = SrcSize > DstSize;
966 } else if (Result == Comdat::SelectionKind::SameSize) {
967 if (SrcSize != DstSize)
968 return emitError("Linking COMDATs named '" + ComdatName +
969 "': SameSize violated!");
972 llvm_unreachable("unknown selection kind");
981 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
982 Comdat::SelectionKind &Result,
984 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
985 StringRef ComdatName = SrcC->getName();
986 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
987 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
989 if (DstCI == ComdatSymTab.end()) {
990 // Use the comdat if it is only available in one of the modules.
996 const Comdat *DstC = &DstCI->second;
997 Comdat::SelectionKind DSK = DstC->getSelectionKind();
998 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1002 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1003 const GlobalValue &Dest,
1004 const GlobalValue &Src) {
1005 // Should we unconditionally use the Src?
1006 if (shouldOverrideFromSrc()) {
1011 // We always have to add Src if it has appending linkage.
1012 if (Src.hasAppendingLinkage()) {
1013 // Should have prevented importing for appending linkage in linkIfNeeded.
1014 assert(!isPerformingImport());
1019 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1020 bool DestIsDeclaration = Dest.isDeclarationForLinker();
1022 if (isPerformingImport()) {
1023 if (isa<Function>(&Src)) {
1024 // For functions, LinkFromSrc iff this is the function requested
1025 // for importing. For variables, decide below normally.
1026 LinkFromSrc = ImportFunction->count(&Src);
1030 // Check if this is an alias with an already existing definition
1031 // in Dest, which must have come from a prior importing pass from
1032 // the same Src module. Unlike imported function and variable
1033 // definitions, which are imported as available_externally and are
1034 // not definitions for the linker, that is not a valid linkage for
1035 // imported aliases which must be definitions. Simply use the existing
1037 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1038 assert(isa<GlobalAlias>(&Dest));
1039 LinkFromSrc = false;
1044 if (SrcIsDeclaration) {
1045 // If Src is external or if both Src & Dest are external.. Just link the
1046 // external globals, we aren't adding anything.
1047 if (Src.hasDLLImportStorageClass()) {
1048 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1049 LinkFromSrc = DestIsDeclaration;
1052 // If the Dest is weak, use the source linkage.
1053 LinkFromSrc = Dest.hasExternalWeakLinkage();
1057 if (DestIsDeclaration) {
1058 // If Dest is external but Src is not:
1063 if (Src.hasCommonLinkage()) {
1064 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1069 if (!Dest.hasCommonLinkage()) {
1070 LinkFromSrc = false;
1074 const DataLayout &DL = Dest.getParent()->getDataLayout();
1075 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1076 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1077 LinkFromSrc = SrcSize > DestSize;
1081 if (Src.isWeakForLinker()) {
1082 assert(!Dest.hasExternalWeakLinkage());
1083 assert(!Dest.hasAvailableExternallyLinkage());
1085 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1090 LinkFromSrc = false;
1094 if (Dest.isWeakForLinker()) {
1095 assert(Src.hasExternalLinkage());
1100 assert(!Src.hasExternalWeakLinkage());
1101 assert(!Dest.hasExternalWeakLinkage());
1102 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1103 "Unexpected linkage type!");
1104 return emitError("Linking globals named '" + Src.getName() +
1105 "': symbol multiply defined!");
1108 /// Loop over all of the linked values to compute type mappings. For example,
1109 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1110 /// types 'Foo' but one got renamed when the module was loaded into the same
1112 void ModuleLinker::computeTypeMapping() {
1113 for (GlobalValue &SGV : SrcM.globals()) {
1114 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1118 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1119 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1123 // Unify the element type of appending arrays.
1124 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1125 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1126 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1129 for (GlobalValue &SGV : SrcM) {
1130 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1131 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1134 for (GlobalValue &SGV : SrcM.aliases()) {
1135 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1136 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1139 // Incorporate types by name, scanning all the types in the source module.
1140 // At this point, the destination module may have a type "%foo = { i32 }" for
1141 // example. When the source module got loaded into the same LLVMContext, if
1142 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1143 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
1144 for (StructType *ST : Types) {
1148 // Check to see if there is a dot in the name followed by a digit.
1149 size_t DotPos = ST->getName().rfind('.');
1150 if (DotPos == 0 || DotPos == StringRef::npos ||
1151 ST->getName().back() == '.' ||
1152 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1155 // Check to see if the destination module has a struct with the prefix name.
1156 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1160 // Don't use it if this actually came from the source module. They're in
1161 // the same LLVMContext after all. Also don't use it unless the type is
1162 // actually used in the destination module. This can happen in situations
1165 // Module A Module B
1166 // -------- --------
1167 // %Z = type { %A } %B = type { %C.1 }
1168 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1169 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1170 // %C = type { i8* } %B.3 = type { %C.1 }
1172 // When we link Module B with Module A, the '%B' in Module B is
1173 // used. However, that would then use '%C.1'. But when we process '%C.1',
1174 // we prefer to take the '%C' version. So we are then left with both
1175 // '%C.1' and '%C' being used for the same types. This leads to some
1176 // variables using one type and some using the other.
1177 if (TypeMap.DstStructTypesSet.hasType(DST))
1178 TypeMap.addTypeMapping(DST, ST);
1181 // Now that we have discovered all of the type equivalences, get a body for
1182 // any 'opaque' types in the dest module that are now resolved.
1183 TypeMap.linkDefinedTypeBodies();
1186 static void getArrayElements(const Constant *C,
1187 SmallVectorImpl<Constant *> &Dest) {
1188 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1190 for (unsigned i = 0; i != NumElements; ++i)
1191 Dest.push_back(C->getAggregateElement(i));
1194 /// If there were any appending global variables, link them together now.
1195 /// Return true on error.
1196 Constant *ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1197 const GlobalVariable *SrcGV) {
1198 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
1201 StringRef Name = SrcGV->getName();
1202 bool IsNewStructor = false;
1203 bool IsOldStructor = false;
1204 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
1205 if (cast<StructType>(EltTy)->getNumElements() == 3)
1206 IsNewStructor = true;
1208 IsOldStructor = true;
1211 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
1212 if (IsOldStructor) {
1213 auto &ST = *cast<StructType>(EltTy);
1214 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1215 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
1219 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1221 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
1223 "Linking globals named '" + SrcGV->getName() +
1224 "': can only link appending global with another appending global!");
1228 // Check to see that they two arrays agree on type.
1229 if (EltTy != DstTy->getElementType()) {
1230 emitError("Appending variables with different element types!");
1233 if (DstGV->isConstant() != SrcGV->isConstant()) {
1234 emitError("Appending variables linked with different const'ness!");
1238 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
1240 "Appending variables with different alignment need to be linked!");
1244 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
1246 "Appending variables with different visibility need to be linked!");
1250 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
1252 "Appending variables with different unnamed_addr need to be linked!");
1256 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
1258 "Appending variables with different section name need to be linked!");
1263 SmallVector<Constant *, 16> DstElements;
1265 getArrayElements(DstGV->getInitializer(), DstElements);
1267 SmallVector<Constant *, 16> SrcElements;
1268 getArrayElements(SrcGV->getInitializer(), SrcElements);
1272 std::remove_if(SrcElements.begin(), SrcElements.end(),
1273 [this](Constant *E) {
1274 auto *Key = dyn_cast<GlobalValue>(
1275 E->getAggregateElement(2)->stripPointerCasts());
1276 return Key && !ValuesToLink.count(Key) &&
1277 !shouldLazyLink(*Key);
1280 uint64_t NewSize = DstElements.size() + SrcElements.size();
1281 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1283 // Create the new global variable.
1284 GlobalVariable *NG = new GlobalVariable(
1285 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1286 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1287 SrcGV->getType()->getAddressSpace());
1289 // Propagate alignment, visibility and section info.
1290 copyGVAttributes(NG, SrcGV);
1292 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1295 ValueMap[SrcGV] = Ret;
1297 for (auto *V : SrcElements) {
1299 if (IsOldStructor) {
1300 auto *S = cast<ConstantStruct>(V);
1301 auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
1302 &TypeMap, &ValMaterializer);
1303 auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
1304 &TypeMap, &ValMaterializer);
1305 Value *Null = Constant::getNullValue(VoidPtrTy);
1307 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
1310 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1312 DstElements.push_back(NewV);
1315 NG->setInitializer(ConstantArray::get(NewType, DstElements));
1317 // Replace any uses of the two global variables with uses of the new
1320 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1321 DstGV->eraseFromParent();
1327 Constant *ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1328 GlobalValue *DGV = getLinkedToGlobal(SGV);
1330 // Handle the ultra special appending linkage case first.
1331 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1332 if (SGV->hasAppendingLinkage()) {
1333 // Should have prevented importing for appending linkage in linkIfNeeded.
1334 assert(!isPerformingImport());
1335 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1336 cast<GlobalVariable>(SGV));
1339 bool LinkFromSrc = true;
1340 Comdat *C = nullptr;
1341 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1343 if (isPerformingImport() && !doImportAsDefinition(SGV)) {
1344 LinkFromSrc = false;
1345 } else if (const Comdat *SC = SGV->getComdat()) {
1346 Comdat::SelectionKind SK;
1347 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1348 C = DstM.getOrInsertComdat(SC->getName());
1349 C->setSelectionKind(SK);
1350 if (SGV->hasLocalLinkage())
1353 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1358 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1361 if (!LinkFromSrc && DGV) {
1364 // If we are done linking global value bodies (i.e. we are performing
1365 // metadata linking), don't link in the global value due to this
1366 // reference, simply map it to null.
1367 if (DoneLinkingBodies)
1370 NewGV = copyGlobalValueProto(SGV, LinkFromSrc);
1373 setVisibility(NewGV, SGV, DGV);
1374 NewGV->setUnnamedAddr(HasUnnamedAddr);
1376 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1377 if (C && LinkFromSrc)
1378 NewGO->setComdat(C);
1380 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1381 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1384 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1385 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1386 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1387 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1388 (!DGVar->isConstant() || !SGVar->isConstant()))
1389 NewGVar->setConstant(false);
1392 if (NewGV != DGV && DGV) {
1393 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1394 DGV->eraseFromParent();
1397 return ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1400 /// Update the initializers in the Dest module now that all globals that may be
1401 /// referenced are in Dest.
1402 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1403 // Figure out what the initializer looks like in the dest module.
1404 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1405 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1408 /// Copy the source function over into the dest function and fix up references
1409 /// to values. At this point we know that Dest is an external function, and
1410 /// that Src is not.
1411 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1412 assert(Dst.isDeclaration() && !Src.isDeclaration());
1414 // Materialize if needed.
1415 if (std::error_code EC = Src.materialize())
1416 return emitError(EC.message());
1418 // Link in the prefix data.
1419 if (Src.hasPrefixData())
1420 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1421 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1423 // Link in the prologue data.
1424 if (Src.hasPrologueData())
1425 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1426 RF_MoveDistinctMDs, &TypeMap,
1429 // Link in the personality function.
1430 if (Src.hasPersonalityFn())
1431 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1432 RF_MoveDistinctMDs, &TypeMap,
1435 // Go through and convert function arguments over, remembering the mapping.
1436 Function::arg_iterator DI = Dst.arg_begin();
1437 for (Argument &Arg : Src.args()) {
1438 DI->setName(Arg.getName()); // Copy the name over.
1440 // Add a mapping to our mapping.
1441 ValueMap[&Arg] = &*DI;
1445 // Copy over the metadata attachments.
1446 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1447 Src.getAllMetadata(MDs);
1448 for (const auto &I : MDs)
1449 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1450 &TypeMap, &ValMaterializer));
1452 // Splice the body of the source function into the dest function.
1453 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1455 // At this point, all of the instructions and values of the function are now
1456 // copied over. The only problem is that they are still referencing values in
1457 // the Source function as operands. Loop through all of the operands of the
1458 // functions and patch them up to point to the local versions.
1459 for (BasicBlock &BB : Dst)
1460 for (Instruction &I : BB)
1461 RemapInstruction(&I, ValueMap,
1462 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1465 // There is no need to map the arguments anymore.
1466 for (Argument &Arg : Src.args())
1467 ValueMap.erase(&Arg);
1469 Src.dematerialize();
1473 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1474 Constant *Aliasee = Src.getAliasee();
1475 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1477 Dst.setAliasee(Val);
1480 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1481 if (const Comdat *SC = Src.getComdat()) {
1482 // To ensure that we don't generate an incomplete comdat group,
1483 // we must materialize and map in any other members that are not
1484 // yet materialized in Dst, which also ensures their definitions
1485 // are linked in. Otherwise, linkonce and other lazy linked GVs will
1486 // not be materialized if they aren't referenced.
1487 for (auto *SGV : ComdatMembers[SC]) {
1488 auto *DGV = cast_or_null<GlobalValue>(ValueMap.lookup(SGV));
1489 if (DGV && !DGV->isDeclaration())
1491 MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1494 if (shouldInternalizeLinkedSymbols())
1495 if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1496 DGV->setLinkage(GlobalValue::InternalLinkage);
1497 if (auto *F = dyn_cast<Function>(&Src))
1498 return linkFunctionBody(cast<Function>(Dst), *F);
1499 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1500 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1503 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1507 /// Insert all of the named MDNodes in Src into the Dest module.
1508 void ModuleLinker::linkNamedMDNodes() {
1509 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1510 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1511 // Don't link module flags here. Do them separately.
1512 if (&NMD == SrcModFlags)
1514 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1515 // Add Src elements into Dest node.
1516 for (const MDNode *op : NMD.operands())
1517 DestNMD->addOperand(MapMetadata(
1518 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1519 &TypeMap, &ValMaterializer));
1523 /// Merge the linker flags in Src into the Dest module.
1524 bool ModuleLinker::linkModuleFlagsMetadata() {
1525 // If the source module has no module flags, we are done.
1526 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1530 // If the destination module doesn't have module flags yet, then just copy
1531 // over the source module's flags.
1532 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1533 if (DstModFlags->getNumOperands() == 0) {
1534 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1535 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1540 // First build a map of the existing module flags and requirements.
1541 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1542 SmallSetVector<MDNode *, 16> Requirements;
1543 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1544 MDNode *Op = DstModFlags->getOperand(I);
1545 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1546 MDString *ID = cast<MDString>(Op->getOperand(1));
1548 if (Behavior->getZExtValue() == Module::Require) {
1549 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1551 Flags[ID] = std::make_pair(Op, I);
1555 // Merge in the flags from the source module, and also collect its set of
1557 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1558 MDNode *SrcOp = SrcModFlags->getOperand(I);
1559 ConstantInt *SrcBehavior =
1560 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1561 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1564 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1565 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1567 // If this is a requirement, add it and continue.
1568 if (SrcBehaviorValue == Module::Require) {
1569 // If the destination module does not already have this requirement, add
1571 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1572 DstModFlags->addOperand(SrcOp);
1577 // If there is no existing flag with this ID, just add it.
1579 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1580 DstModFlags->addOperand(SrcOp);
1584 // Otherwise, perform a merge.
1585 ConstantInt *DstBehavior =
1586 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1587 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1589 // If either flag has override behavior, handle it first.
1590 if (DstBehaviorValue == Module::Override) {
1591 // Diagnose inconsistent flags which both have override behavior.
1592 if (SrcBehaviorValue == Module::Override &&
1593 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1594 emitError("linking module flags '" + ID->getString() +
1595 "': IDs have conflicting override values");
1598 } else if (SrcBehaviorValue == Module::Override) {
1599 // Update the destination flag to that of the source.
1600 DstModFlags->setOperand(DstIndex, SrcOp);
1601 Flags[ID].first = SrcOp;
1605 // Diagnose inconsistent merge behavior types.
1606 if (SrcBehaviorValue != DstBehaviorValue) {
1607 emitError("linking module flags '" + ID->getString() +
1608 "': IDs have conflicting behaviors");
1612 auto replaceDstValue = [&](MDNode *New) {
1613 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1614 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1615 DstModFlags->setOperand(DstIndex, Flag);
1616 Flags[ID].first = Flag;
1619 // Perform the merge for standard behavior types.
1620 switch (SrcBehaviorValue) {
1621 case Module::Require:
1622 case Module::Override:
1623 llvm_unreachable("not possible");
1624 case Module::Error: {
1625 // Emit an error if the values differ.
1626 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1627 emitError("linking module flags '" + ID->getString() +
1628 "': IDs have conflicting values");
1632 case Module::Warning: {
1633 // Emit a warning if the values differ.
1634 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1635 emitWarning("linking module flags '" + ID->getString() +
1636 "': IDs have conflicting values");
1640 case Module::Append: {
1641 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1642 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1643 SmallVector<Metadata *, 8> MDs;
1644 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1645 MDs.append(DstValue->op_begin(), DstValue->op_end());
1646 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1648 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1651 case Module::AppendUnique: {
1652 SmallSetVector<Metadata *, 16> Elts;
1653 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1654 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1655 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1656 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1658 replaceDstValue(MDNode::get(DstM.getContext(),
1659 makeArrayRef(Elts.begin(), Elts.end())));
1665 // Check all of the requirements.
1666 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1667 MDNode *Requirement = Requirements[I];
1668 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1669 Metadata *ReqValue = Requirement->getOperand(1);
1671 MDNode *Op = Flags[Flag].first;
1672 if (!Op || Op->getOperand(2) != ReqValue) {
1673 emitError("linking module flags '" + Flag->getString() +
1674 "': does not have the required value");
1682 // This function returns true if the triples match.
1683 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1684 // If vendor is apple, ignore the version number.
1685 if (T0.getVendor() == Triple::Apple)
1686 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1687 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1692 // This function returns the merged triple.
1693 static std::string mergeTriples(const Triple &SrcTriple,
1694 const Triple &DstTriple) {
1695 // If vendor is apple, pick the triple with the larger version number.
1696 if (SrcTriple.getVendor() == Triple::Apple)
1697 if (DstTriple.isOSVersionLT(SrcTriple))
1698 return SrcTriple.str();
1700 return DstTriple.str();
1703 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1704 GlobalValue *DGV = getLinkedToGlobal(&GV);
1706 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1709 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
1710 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1711 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
1712 if (DGVar && SGVar) {
1713 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
1714 (!DGVar->isConstant() || !SGVar->isConstant())) {
1715 DGVar->setConstant(false);
1716 SGVar->setConstant(false);
1718 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
1719 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
1720 SGVar->setAlignment(Align);
1721 DGVar->setAlignment(Align);
1725 GlobalValue::VisibilityTypes Visibility =
1726 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1727 DGV->setVisibility(Visibility);
1728 GV.setVisibility(Visibility);
1730 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
1731 DGV->setUnnamedAddr(HasUnnamedAddr);
1732 GV.setUnnamedAddr(HasUnnamedAddr);
1735 // Don't want to append to global_ctors list, for example, when we
1736 // are importing for ThinLTO, otherwise the global ctors and dtors
1737 // get executed multiple times for local variables (the latter causing
1739 if (GV.hasAppendingLinkage() && isPerformingImport())
1742 if (isPerformingImport() && !doImportAsDefinition(&GV))
1745 if (!DGV && !shouldOverrideFromSrc() &&
1746 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1747 GV.hasAvailableExternallyLinkage()))
1750 if (GV.isDeclaration())
1753 if (const Comdat *SC = GV.getComdat()) {
1755 Comdat::SelectionKind SK;
1756 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1758 ValuesToLink.insert(&GV);
1762 bool LinkFromSrc = true;
1763 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
1766 ValuesToLink.insert(&GV);
1770 bool ModuleLinker::run() {
1771 // Inherit the target data from the source module if the destination module
1772 // doesn't have one already.
1773 if (DstM.getDataLayout().isDefault())
1774 DstM.setDataLayout(SrcM.getDataLayout());
1776 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1777 emitWarning("Linking two modules of different data layouts: '" +
1778 SrcM.getModuleIdentifier() + "' is '" +
1779 SrcM.getDataLayoutStr() + "' whereas '" +
1780 DstM.getModuleIdentifier() + "' is '" +
1781 DstM.getDataLayoutStr() + "'\n");
1784 // Copy the target triple from the source to dest if the dest's is empty.
1785 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1786 DstM.setTargetTriple(SrcM.getTargetTriple());
1788 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1790 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1791 emitWarning("Linking two modules of different target triples: " +
1792 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1793 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1794 DstM.getTargetTriple() + "'\n");
1796 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1798 // Append the module inline asm string.
1799 if (!SrcM.getModuleInlineAsm().empty()) {
1800 if (DstM.getModuleInlineAsm().empty())
1801 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1803 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1804 SrcM.getModuleInlineAsm());
1807 // Loop over all of the linked values to compute type mappings.
1808 computeTypeMapping();
1810 ComdatsChosen.clear();
1811 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1812 const Comdat &C = SMEC.getValue();
1813 if (ComdatsChosen.count(&C))
1815 Comdat::SelectionKind SK;
1817 if (getComdatResult(&C, SK, LinkFromSrc))
1819 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1822 for (GlobalVariable &GV : SrcM.globals())
1823 if (const Comdat *SC = GV.getComdat())
1824 ComdatMembers[SC].push_back(&GV);
1826 for (Function &SF : SrcM)
1827 if (const Comdat *SC = SF.getComdat())
1828 ComdatMembers[SC].push_back(&SF);
1830 for (GlobalAlias &GA : SrcM.aliases())
1831 if (const Comdat *SC = GA.getComdat())
1832 ComdatMembers[SC].push_back(&GA);
1834 // Insert all of the globals in src into the DstM module... without linking
1835 // initializers (which could refer to functions not yet mapped over).
1836 for (GlobalVariable &GV : SrcM.globals())
1837 if (linkIfNeeded(GV))
1840 for (Function &SF : SrcM)
1841 if (linkIfNeeded(SF))
1844 for (GlobalAlias &GA : SrcM.aliases())
1845 if (linkIfNeeded(GA))
1848 for (GlobalValue *GV : ValuesToLink) {
1849 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1854 // Note that we are done linking global value bodies. This prevents
1855 // metadata linking from creating new references.
1856 DoneLinkingBodies = true;
1858 // Remap all of the named MDNodes in Src into the DstM module. We do this
1859 // after linking GlobalValues so that MDNodes that reference GlobalValues
1860 // are properly remapped.
1863 // Merge the module flags into the DstM module.
1864 if (linkModuleFlagsMetadata())
1870 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1871 : ETypes(E), IsPacked(P) {}
1873 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1874 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1876 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1877 if (IsPacked != That.IsPacked)
1879 if (ETypes != That.ETypes)
1884 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1885 return !this->operator==(That);
1888 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1889 return DenseMapInfo<StructType *>::getEmptyKey();
1892 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1893 return DenseMapInfo<StructType *>::getTombstoneKey();
1896 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1897 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1901 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1902 return getHashValue(KeyTy(ST));
1905 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1906 const StructType *RHS) {
1907 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1909 return LHS == KeyTy(RHS);
1912 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1913 const StructType *RHS) {
1914 if (RHS == getEmptyKey())
1915 return LHS == getEmptyKey();
1917 if (RHS == getTombstoneKey())
1918 return LHS == getTombstoneKey();
1920 return KeyTy(LHS) == KeyTy(RHS);
1923 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1924 assert(!Ty->isOpaque());
1925 NonOpaqueStructTypes.insert(Ty);
1928 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1929 assert(!Ty->isOpaque());
1930 NonOpaqueStructTypes.insert(Ty);
1931 bool Removed = OpaqueStructTypes.erase(Ty);
1936 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1937 assert(Ty->isOpaque());
1938 OpaqueStructTypes.insert(Ty);
1942 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1944 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1945 auto I = NonOpaqueStructTypes.find_as(Key);
1946 if (I == NonOpaqueStructTypes.end())
1951 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1953 return OpaqueStructTypes.count(Ty);
1954 auto I = NonOpaqueStructTypes.find(Ty);
1955 if (I == NonOpaqueStructTypes.end())
1960 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
1961 : Composite(M), DiagnosticHandler(DiagnosticHandler) {
1962 TypeFinder StructTypes;
1963 StructTypes.run(M, true);
1964 for (StructType *Ty : StructTypes) {
1966 IdentifiedStructTypes.addOpaque(Ty);
1968 IdentifiedStructTypes.addNonOpaque(Ty);
1972 bool Linker::linkInModule(Module &Src, unsigned Flags,
1973 const FunctionInfoIndex *Index,
1974 DenseSet<const GlobalValue *> *FunctionsToImport) {
1975 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1976 DiagnosticHandler, Flags, Index, FunctionsToImport);
1977 bool RetCode = TheLinker.run();
1978 Composite.dropTriviallyDeadConstantArrays();
1982 //===----------------------------------------------------------------------===//
1983 // LinkModules entrypoint.
1984 //===----------------------------------------------------------------------===//
1986 /// This function links two modules together, with the resulting Dest module
1987 /// modified to be the composite of the two input modules. If an error occurs,
1988 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1989 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1990 /// relied on to be consistent.
1991 bool Linker::linkModules(Module &Dest, Module &Src,
1992 DiagnosticHandlerFunction DiagnosticHandler,
1994 Linker L(Dest, DiagnosticHandler);
1995 return L.linkInModule(Src, Flags);
1998 std::unique_ptr<Module>
1999 llvm::renameModuleForThinLTO(std::unique_ptr<Module> &M,
2000 const FunctionInfoIndex *Index,
2001 DiagnosticHandlerFunction DiagnosticHandler) {
2002 std::unique_ptr<llvm::Module> RenamedModule(
2003 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
2004 Linker L(*RenamedModule.get(), DiagnosticHandler);
2005 if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
2007 return RenamedModule;
2010 //===----------------------------------------------------------------------===//
2012 //===----------------------------------------------------------------------===//
2014 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2015 LLVMLinkerMode Unused, char **OutMessages) {
2016 Module *D = unwrap(Dest);
2017 std::string Message;
2018 raw_string_ostream Stream(Message);
2019 DiagnosticPrinterRawOStream DP(Stream);
2021 LLVMBool Result = Linker::linkModules(
2022 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2024 if (OutMessages && Result) {
2026 *OutMessages = strdup(Message.c_str());