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;
424 ModuleLinker(Module &DstM, Linker::IdentifiedStructTypeSet &Set, Module &SrcM,
425 DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
426 const FunctionInfoIndex *Index = nullptr,
427 DenseSet<const GlobalValue *> *FunctionsToImport = nullptr)
428 : DstM(DstM), SrcM(SrcM), TypeMap(Set), ValMaterializer(this),
429 DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
430 ImportFunction(FunctionsToImport) {
431 assert((ImportIndex || !ImportFunction) &&
432 "Expect a FunctionInfoIndex when importing");
433 // If we have a FunctionInfoIndex but no function to import,
434 // then this is the primary module being compiled in a ThinLTO
435 // backend compilation, and we need to see if it has functions that
436 // may be exported to another backend compilation.
437 if (ImportIndex && !ImportFunction)
438 HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
442 Value *materializeDeclFor(Value *V);
443 void materializeInitFor(GlobalValue *New, GlobalValue *Old);
446 bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
447 bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
448 bool shouldInternalizeLinkedSymbols() {
449 return Flags & Linker::InternalizeLinkedSymbols;
452 /// Handles cloning of a global values from the source module into
453 /// the destination module, including setting the attributes and visibility.
454 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
456 /// Check if we should promote the given local value to global scope.
457 bool doPromoteLocalToGlobal(const GlobalValue *SGV);
459 bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
460 const GlobalValue &Src);
462 /// Helper method for setting a message and returning an error code.
463 bool emitError(const Twine &Message) {
464 DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
469 void emitWarning(const Twine &Message) {
470 DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
473 bool getComdatLeader(Module &M, StringRef ComdatName,
474 const GlobalVariable *&GVar);
475 bool computeResultingSelectionKind(StringRef ComdatName,
476 Comdat::SelectionKind Src,
477 Comdat::SelectionKind Dst,
478 Comdat::SelectionKind &Result,
480 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
482 bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
484 // Keep track of the global value members of each comdat in source.
485 DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
487 /// Given a global in the source module, return the global in the
488 /// destination module that is being linked to, if any.
489 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
490 // If the source has no name it can't link. If it has local linkage,
491 // there is no name match-up going on.
492 if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
495 // Otherwise see if we have a match in the destination module's symtab.
496 GlobalValue *DGV = DstM.getNamedValue(getName(SrcGV));
500 // If we found a global with the same name in the dest module, but it has
501 // internal linkage, we are really not doing any linkage here.
502 if (DGV->hasLocalLinkage())
505 // Otherwise, we do in fact link to the destination global.
509 void computeTypeMapping();
511 bool linkIfNeeded(GlobalValue &GV);
512 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
513 const GlobalVariable *SrcGV);
515 Constant *linkGlobalValueProto(GlobalValue *GV);
516 bool linkModuleFlagsMetadata();
518 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
519 bool linkFunctionBody(Function &Dst, Function &Src);
520 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
521 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
523 /// Functions that take care of cloning a specific global value type
524 /// into the destination module.
525 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
526 Function *copyFunctionProto(const Function *SF);
527 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
529 /// Helper methods to check if we are importing from or potentially
530 /// exporting from the current source module.
531 bool isPerformingImport() { return ImportFunction != nullptr; }
532 bool isModuleExporting() { return HasExportedFunctions; }
534 /// If we are importing from the source module, checks if we should
535 /// import SGV as a definition, otherwise import as a declaration.
536 bool doImportAsDefinition(const GlobalValue *SGV);
538 /// Get the name for SGV that should be used in the linked destination
539 /// module. Specifically, this handles the case where we need to rename
540 /// a local that is being promoted to global scope.
541 std::string getName(const GlobalValue *SGV);
543 /// Get the new linkage for SGV that should be used in the linked destination
544 /// module. Specifically, for ThinLTO importing or exporting it may need
546 GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
548 /// Copies the necessary global value attributes and name from the source
549 /// to the newly cloned global value.
550 void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
552 /// Updates the visibility for the new global cloned from the source
553 /// and, if applicable, linked with an existing destination global.
554 /// Handles visibility change required for promoted locals.
555 void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
556 const GlobalValue *DGV = nullptr);
558 void linkNamedMDNodes();
562 /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
563 /// table. This is good for all clients except for us. Go through the trouble
564 /// to force this back.
565 static void forceRenaming(GlobalValue *GV, StringRef Name) {
566 // If the global doesn't force its name or if it already has the right name,
567 // there is nothing for us to do.
568 // Note that any required local to global promotion should already be done,
569 // so promoted locals will not skip this handling as their linkage is no
571 if (GV->hasLocalLinkage() || GV->getName() == Name)
574 Module *M = GV->getParent();
576 // If there is a conflict, rename the conflict.
577 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
578 GV->takeName(ConflictGV);
579 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
580 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
582 GV->setName(Name); // Force the name back
586 /// copy additional attributes (those not needed to construct a GlobalValue)
587 /// from the SrcGV to the DestGV.
588 void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
589 const GlobalValue *SrcGV) {
590 NewGV->copyAttributesFrom(SrcGV);
591 forceRenaming(NewGV, getName(SrcGV));
594 bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
595 if (!isPerformingImport())
597 auto *GA = dyn_cast<GlobalAlias>(SGV);
599 if (GA->hasWeakAnyLinkage())
601 const GlobalObject *GO = GA->getBaseObject();
602 if (!GO->hasLinkOnceODRLinkage())
604 return doImportAsDefinition(GO);
606 // Always import GlobalVariable definitions, except for the special
607 // case of WeakAny which are imported as ExternalWeak declarations
608 // (see comments in ModuleLinker::getLinkage). The linkage changes
609 // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
610 // global variables with external linkage are transformed to
611 // available_externally definitions, which are ultimately turned into
612 // declarations after the EliminateAvailableExternally pass).
613 if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
614 !SGV->hasWeakAnyLinkage())
616 // Only import the function requested for importing.
617 auto *SF = dyn_cast<Function>(SGV);
618 if (SF && ImportFunction->count(SF))
624 bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
625 assert(SGV->hasLocalLinkage());
626 // Both the imported references and the original local variable must
628 if (!isPerformingImport() && !isModuleExporting())
631 // Local const variables never need to be promoted unless they are address
632 // taken. The imported uses can simply use the clone created in this module.
633 // For now we are conservative in determining which variables are not
634 // address taken by checking the unnamed addr flag. To be more aggressive,
635 // the address taken information must be checked earlier during parsing
636 // of the module and recorded in the function index for use when importing
638 auto *GVar = dyn_cast<GlobalVariable>(SGV);
639 if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
642 // Eventually we only need to promote functions in the exporting module that
643 // are referenced by a potentially exported function (i.e. one that is in the
648 std::string ModuleLinker::getName(const GlobalValue *SGV) {
649 // For locals that must be promoted to global scope, ensure that
650 // the promoted name uniquely identifies the copy in the original module,
651 // using the ID assigned during combined index creation. When importing,
652 // we rename all locals (not just those that are promoted) in order to
653 // avoid naming conflicts between locals imported from different modules.
654 if (SGV->hasLocalLinkage() &&
655 (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
656 return FunctionInfoIndex::getGlobalNameForLocal(
658 ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
659 return SGV->getName();
662 GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
663 // Any local variable that is referenced by an exported function needs
664 // to be promoted to global scope. Since we don't currently know which
665 // functions reference which local variables/functions, we must treat
666 // all as potentially exported if this module is exporting anything.
667 if (isModuleExporting()) {
668 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
669 return GlobalValue::ExternalLinkage;
670 return SGV->getLinkage();
673 // Otherwise, if we aren't importing, no linkage change is needed.
674 if (!isPerformingImport())
675 return SGV->getLinkage();
677 switch (SGV->getLinkage()) {
678 case GlobalValue::ExternalLinkage:
679 // External defnitions are converted to available_externally
680 // definitions upon import, so that they are available for inlining
681 // and/or optimization, but are turned into declarations later
682 // during the EliminateAvailableExternally pass.
683 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
684 return GlobalValue::AvailableExternallyLinkage;
685 // An imported external declaration stays external.
686 return SGV->getLinkage();
688 case GlobalValue::AvailableExternallyLinkage:
689 // An imported available_externally definition converts
690 // to external if imported as a declaration.
691 if (!doImportAsDefinition(SGV))
692 return GlobalValue::ExternalLinkage;
693 // An imported available_externally declaration stays that way.
694 return SGV->getLinkage();
696 case GlobalValue::LinkOnceAnyLinkage:
697 case GlobalValue::LinkOnceODRLinkage:
698 // These both stay the same when importing the definition.
699 // The ThinLTO pass will eventually force-import their definitions.
700 return SGV->getLinkage();
702 case GlobalValue::WeakAnyLinkage:
703 // Can't import weak_any definitions correctly, or we might change the
704 // program semantics, since the linker will pick the first weak_any
705 // definition and importing would change the order they are seen by the
706 // linker. The module linking caller needs to enforce this.
707 assert(!doImportAsDefinition(SGV));
708 // If imported as a declaration, it becomes external_weak.
709 return GlobalValue::ExternalWeakLinkage;
711 case GlobalValue::WeakODRLinkage:
712 // For weak_odr linkage, there is a guarantee that all copies will be
713 // equivalent, so the issue described above for weak_any does not exist,
714 // and the definition can be imported. It can be treated similarly
715 // to an imported externally visible global value.
716 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
717 return GlobalValue::AvailableExternallyLinkage;
719 return GlobalValue::ExternalLinkage;
721 case GlobalValue::AppendingLinkage:
722 // It would be incorrect to import an appending linkage variable,
723 // since it would cause global constructors/destructors to be
724 // executed multiple times. This should have already been handled
725 // by linkIfNeeded, and we will assert in shouldLinkFromSource
726 // if we try to import, so we simply return AppendingLinkage here
727 // as this helper is called more widely in getLinkedToGlobal.
728 return GlobalValue::AppendingLinkage;
730 case GlobalValue::InternalLinkage:
731 case GlobalValue::PrivateLinkage:
732 // If we are promoting the local to global scope, it is handled
733 // similarly to a normal externally visible global.
734 if (doPromoteLocalToGlobal(SGV)) {
735 if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
736 return GlobalValue::AvailableExternallyLinkage;
738 return GlobalValue::ExternalLinkage;
740 // A non-promoted imported local definition stays local.
741 // The ThinLTO pass will eventually force-import their definitions.
742 return SGV->getLinkage();
744 case GlobalValue::ExternalWeakLinkage:
745 // External weak doesn't apply to definitions, must be a declaration.
746 assert(!doImportAsDefinition(SGV));
747 // Linkage stays external_weak.
748 return SGV->getLinkage();
750 case GlobalValue::CommonLinkage:
751 // Linkage stays common on definitions.
752 // The ThinLTO pass will eventually force-import their definitions.
753 return SGV->getLinkage();
756 llvm_unreachable("unknown linkage type");
759 /// Loop through the global variables in the src module and merge them into the
762 ModuleLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
763 // No linking to be performed or linking from the source: simply create an
764 // identical version of the symbol over in the dest module... the
765 // initializer will be filled in later by LinkGlobalInits.
766 GlobalVariable *NewDGV =
767 new GlobalVariable(DstM, TypeMap.get(SGVar->getType()->getElementType()),
768 SGVar->isConstant(), GlobalValue::ExternalLinkage,
769 /*init*/ nullptr, getName(SGVar),
770 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
771 SGVar->getType()->getAddressSpace());
776 /// Link the function in the source module into the destination module if
777 /// needed, setting up mapping information.
778 Function *ModuleLinker::copyFunctionProto(const Function *SF) {
779 // If there is no linkage to be performed or we are linking from the source,
781 return Function::Create(TypeMap.get(SF->getFunctionType()),
782 GlobalValue::ExternalLinkage, getName(SF), &DstM);
785 /// Set up prototypes for any aliases that come over from the source module.
786 GlobalValue *ModuleLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
787 // If there is no linkage to be performed or we're linking from the source,
789 auto *Ty = TypeMap.get(SGA->getValueType());
790 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
791 GlobalValue::ExternalLinkage, getName(SGA), &DstM);
794 static GlobalValue::VisibilityTypes
795 getMinVisibility(GlobalValue::VisibilityTypes A,
796 GlobalValue::VisibilityTypes B) {
797 if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
798 return GlobalValue::HiddenVisibility;
799 if (A == GlobalValue::ProtectedVisibility ||
800 B == GlobalValue::ProtectedVisibility)
801 return GlobalValue::ProtectedVisibility;
802 return GlobalValue::DefaultVisibility;
805 void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
806 const GlobalValue *DGV) {
807 GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
809 Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
810 // For promoted locals, mark them hidden so that they can later be
811 // stripped from the symbol table to reduce bloat.
812 if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
813 Visibility = GlobalValue::HiddenVisibility;
814 NewGV->setVisibility(Visibility);
817 GlobalValue *ModuleLinker::copyGlobalValueProto(const GlobalValue *SGV,
818 bool ForDefinition) {
820 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
821 NewGV = copyGlobalVariableProto(SGVar);
822 } else if (auto *SF = dyn_cast<Function>(SGV)) {
823 NewGV = copyFunctionProto(SF);
826 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
828 NewGV = new GlobalVariable(
829 DstM, TypeMap.get(SGV->getType()->getElementType()),
830 /*isConstant*/ false, GlobalValue::ExternalLinkage,
831 /*init*/ nullptr, getName(SGV),
832 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
833 SGV->getType()->getAddressSpace());
837 NewGV->setLinkage(getLinkage(SGV));
838 else if (SGV->hasAvailableExternallyLinkage() || SGV->hasWeakLinkage() ||
839 SGV->hasLinkOnceLinkage())
840 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
842 copyGVAttributes(NewGV, SGV);
846 Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
847 return ModLinker->materializeDeclFor(V);
850 Value *ModuleLinker::materializeDeclFor(Value *V) {
851 auto *SGV = dyn_cast<GlobalValue>(V);
855 return linkGlobalValueProto(SGV);
858 void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
860 return ModLinker->materializeInitFor(New, Old);
863 static bool shouldLazyLink(const GlobalValue &GV) {
864 return GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
865 GV.hasAvailableExternallyLinkage();
868 void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
869 if (auto *F = dyn_cast<Function>(New)) {
870 if (!F->isDeclaration())
872 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
873 if (V->hasInitializer())
876 auto *A = cast<GlobalAlias>(New);
881 if (Old->isDeclaration())
884 if (isPerformingImport() && !doImportAsDefinition(Old))
887 if (!ValuesToLink.count(Old) && !shouldLazyLink(*Old))
890 linkGlobalValueBody(*New, *Old);
893 bool ModuleLinker::getComdatLeader(Module &M, StringRef ComdatName,
894 const GlobalVariable *&GVar) {
895 const GlobalValue *GVal = M.getNamedValue(ComdatName);
896 if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
897 GVal = GA->getBaseObject();
899 // We cannot resolve the size of the aliasee yet.
900 return emitError("Linking COMDATs named '" + ComdatName +
901 "': COMDAT key involves incomputable alias size.");
904 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
907 "Linking COMDATs named '" + ComdatName +
908 "': GlobalVariable required for data dependent selection!");
913 bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
914 Comdat::SelectionKind Src,
915 Comdat::SelectionKind Dst,
916 Comdat::SelectionKind &Result,
918 // The ability to mix Comdat::SelectionKind::Any with
919 // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
920 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
921 Dst == Comdat::SelectionKind::Largest;
922 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
923 Src == Comdat::SelectionKind::Largest;
924 if (DstAnyOrLargest && SrcAnyOrLargest) {
925 if (Dst == Comdat::SelectionKind::Largest ||
926 Src == Comdat::SelectionKind::Largest)
927 Result = Comdat::SelectionKind::Largest;
929 Result = Comdat::SelectionKind::Any;
930 } else if (Src == Dst) {
933 return emitError("Linking COMDATs named '" + ComdatName +
934 "': invalid selection kinds!");
938 case Comdat::SelectionKind::Any:
942 case Comdat::SelectionKind::NoDuplicates:
943 return emitError("Linking COMDATs named '" + ComdatName +
944 "': noduplicates has been violated!");
945 case Comdat::SelectionKind::ExactMatch:
946 case Comdat::SelectionKind::Largest:
947 case Comdat::SelectionKind::SameSize: {
948 const GlobalVariable *DstGV;
949 const GlobalVariable *SrcGV;
950 if (getComdatLeader(DstM, ComdatName, DstGV) ||
951 getComdatLeader(SrcM, ComdatName, SrcGV))
954 const DataLayout &DstDL = DstM.getDataLayout();
955 const DataLayout &SrcDL = SrcM.getDataLayout();
957 DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
959 SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
960 if (Result == Comdat::SelectionKind::ExactMatch) {
961 if (SrcGV->getInitializer() != DstGV->getInitializer())
962 return emitError("Linking COMDATs named '" + ComdatName +
963 "': ExactMatch violated!");
965 } else if (Result == Comdat::SelectionKind::Largest) {
966 LinkFromSrc = SrcSize > DstSize;
967 } else if (Result == Comdat::SelectionKind::SameSize) {
968 if (SrcSize != DstSize)
969 return emitError("Linking COMDATs named '" + ComdatName +
970 "': SameSize violated!");
973 llvm_unreachable("unknown selection kind");
982 bool ModuleLinker::getComdatResult(const Comdat *SrcC,
983 Comdat::SelectionKind &Result,
985 Comdat::SelectionKind SSK = SrcC->getSelectionKind();
986 StringRef ComdatName = SrcC->getName();
987 Module::ComdatSymTabType &ComdatSymTab = DstM.getComdatSymbolTable();
988 Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
990 if (DstCI == ComdatSymTab.end()) {
991 // Use the comdat if it is only available in one of the modules.
997 const Comdat *DstC = &DstCI->second;
998 Comdat::SelectionKind DSK = DstC->getSelectionKind();
999 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
1003 bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1004 const GlobalValue &Dest,
1005 const GlobalValue &Src) {
1006 // Should we unconditionally use the Src?
1007 if (shouldOverrideFromSrc()) {
1012 // We always have to add Src if it has appending linkage.
1013 if (Src.hasAppendingLinkage()) {
1014 // Should have prevented importing for appending linkage in linkIfNeeded.
1015 assert(!isPerformingImport());
1020 bool SrcIsDeclaration = Src.isDeclarationForLinker();
1021 bool DestIsDeclaration = Dest.isDeclarationForLinker();
1023 if (isPerformingImport()) {
1024 if (isa<Function>(&Src)) {
1025 // For functions, LinkFromSrc iff this is the function requested
1026 // for importing. For variables, decide below normally.
1027 LinkFromSrc = ImportFunction->count(&Src);
1031 // Check if this is an alias with an already existing definition
1032 // in Dest, which must have come from a prior importing pass from
1033 // the same Src module. Unlike imported function and variable
1034 // definitions, which are imported as available_externally and are
1035 // not definitions for the linker, that is not a valid linkage for
1036 // imported aliases which must be definitions. Simply use the existing
1038 if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1039 assert(isa<GlobalAlias>(&Dest));
1040 LinkFromSrc = false;
1045 if (SrcIsDeclaration) {
1046 // If Src is external or if both Src & Dest are external.. Just link the
1047 // external globals, we aren't adding anything.
1048 if (Src.hasDLLImportStorageClass()) {
1049 // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1050 LinkFromSrc = DestIsDeclaration;
1053 // If the Dest is weak, use the source linkage.
1054 LinkFromSrc = Dest.hasExternalWeakLinkage();
1058 if (DestIsDeclaration) {
1059 // If Dest is external but Src is not:
1064 if (Src.hasCommonLinkage()) {
1065 if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1070 if (!Dest.hasCommonLinkage()) {
1071 LinkFromSrc = false;
1075 const DataLayout &DL = Dest.getParent()->getDataLayout();
1076 uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
1077 uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1078 LinkFromSrc = SrcSize > DestSize;
1082 if (Src.isWeakForLinker()) {
1083 assert(!Dest.hasExternalWeakLinkage());
1084 assert(!Dest.hasAvailableExternallyLinkage());
1086 if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1091 LinkFromSrc = false;
1095 if (Dest.isWeakForLinker()) {
1096 assert(Src.hasExternalLinkage());
1101 assert(!Src.hasExternalWeakLinkage());
1102 assert(!Dest.hasExternalWeakLinkage());
1103 assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1104 "Unexpected linkage type!");
1105 return emitError("Linking globals named '" + Src.getName() +
1106 "': symbol multiply defined!");
1109 /// Loop over all of the linked values to compute type mappings. For example,
1110 /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
1111 /// types 'Foo' but one got renamed when the module was loaded into the same
1113 void ModuleLinker::computeTypeMapping() {
1114 for (GlobalValue &SGV : SrcM.globals()) {
1115 GlobalValue *DGV = getLinkedToGlobal(&SGV);
1119 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1120 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1124 // Unify the element type of appending arrays.
1125 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1126 ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1127 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1130 for (GlobalValue &SGV : SrcM) {
1131 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1132 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1135 for (GlobalValue &SGV : SrcM.aliases()) {
1136 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1137 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1140 // Incorporate types by name, scanning all the types in the source module.
1141 // At this point, the destination module may have a type "%foo = { i32 }" for
1142 // example. When the source module got loaded into the same LLVMContext, if
1143 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
1144 std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
1145 for (StructType *ST : Types) {
1149 // Check to see if there is a dot in the name followed by a digit.
1150 size_t DotPos = ST->getName().rfind('.');
1151 if (DotPos == 0 || DotPos == StringRef::npos ||
1152 ST->getName().back() == '.' ||
1153 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1156 // Check to see if the destination module has a struct with the prefix name.
1157 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
1161 // Don't use it if this actually came from the source module. They're in
1162 // the same LLVMContext after all. Also don't use it unless the type is
1163 // actually used in the destination module. This can happen in situations
1166 // Module A Module B
1167 // -------- --------
1168 // %Z = type { %A } %B = type { %C.1 }
1169 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
1170 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
1171 // %C = type { i8* } %B.3 = type { %C.1 }
1173 // When we link Module B with Module A, the '%B' in Module B is
1174 // used. However, that would then use '%C.1'. But when we process '%C.1',
1175 // we prefer to take the '%C' version. So we are then left with both
1176 // '%C.1' and '%C' being used for the same types. This leads to some
1177 // variables using one type and some using the other.
1178 if (TypeMap.DstStructTypesSet.hasType(DST))
1179 TypeMap.addTypeMapping(DST, ST);
1182 // Now that we have discovered all of the type equivalences, get a body for
1183 // any 'opaque' types in the dest module that are now resolved.
1184 TypeMap.linkDefinedTypeBodies();
1187 static void getArrayElements(const Constant *C,
1188 SmallVectorImpl<Constant *> &Dest) {
1189 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
1191 for (unsigned i = 0; i != NumElements; ++i)
1192 Dest.push_back(C->getAggregateElement(i));
1195 /// If there were any appending global variables, link them together now.
1196 /// Return true on error.
1197 Constant *ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
1198 const GlobalVariable *SrcGV) {
1199 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
1202 StringRef Name = SrcGV->getName();
1203 bool IsNewStructor = false;
1204 bool IsOldStructor = false;
1205 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
1206 if (cast<StructType>(EltTy)->getNumElements() == 3)
1207 IsNewStructor = true;
1209 IsOldStructor = true;
1212 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
1213 if (IsOldStructor) {
1214 auto &ST = *cast<StructType>(EltTy);
1215 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1216 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
1220 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1222 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
1224 "Linking globals named '" + SrcGV->getName() +
1225 "': can only link appending global with another appending global!");
1229 // Check to see that they two arrays agree on type.
1230 if (EltTy != DstTy->getElementType()) {
1231 emitError("Appending variables with different element types!");
1234 if (DstGV->isConstant() != SrcGV->isConstant()) {
1235 emitError("Appending variables linked with different const'ness!");
1239 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
1241 "Appending variables with different alignment need to be linked!");
1245 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
1247 "Appending variables with different visibility need to be linked!");
1251 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
1253 "Appending variables with different unnamed_addr need to be linked!");
1257 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
1259 "Appending variables with different section name need to be linked!");
1264 SmallVector<Constant *, 16> DstElements;
1266 getArrayElements(DstGV->getInitializer(), DstElements);
1268 SmallVector<Constant *, 16> SrcElements;
1269 getArrayElements(SrcGV->getInitializer(), SrcElements);
1273 std::remove_if(SrcElements.begin(), SrcElements.end(),
1274 [this](Constant *E) {
1275 auto *Key = dyn_cast<GlobalValue>(
1276 E->getAggregateElement(2)->stripPointerCasts());
1277 return Key && !ValuesToLink.count(Key) &&
1278 !shouldLazyLink(*Key);
1281 uint64_t NewSize = DstElements.size() + SrcElements.size();
1282 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1284 // Create the new global variable.
1285 GlobalVariable *NG = new GlobalVariable(
1286 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1287 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1288 SrcGV->getType()->getAddressSpace());
1290 // Propagate alignment, visibility and section info.
1291 copyGVAttributes(NG, SrcGV);
1293 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1296 ValueMap[SrcGV] = Ret;
1298 for (auto *V : SrcElements) {
1300 if (IsOldStructor) {
1301 auto *S = cast<ConstantStruct>(V);
1302 auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
1303 &TypeMap, &ValMaterializer);
1304 auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
1305 &TypeMap, &ValMaterializer);
1306 Value *Null = Constant::getNullValue(VoidPtrTy);
1308 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
1311 MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1313 DstElements.push_back(NewV);
1316 NG->setInitializer(ConstantArray::get(NewType, DstElements));
1318 // Replace any uses of the two global variables with uses of the new
1321 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1322 DstGV->eraseFromParent();
1328 Constant *ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1329 GlobalValue *DGV = getLinkedToGlobal(SGV);
1331 // Handle the ultra special appending linkage case first.
1332 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1333 if (SGV->hasAppendingLinkage()) {
1334 // Should have prevented importing for appending linkage in linkIfNeeded.
1335 assert(!isPerformingImport());
1336 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1337 cast<GlobalVariable>(SGV));
1340 bool LinkFromSrc = true;
1341 Comdat *C = nullptr;
1342 bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1344 if (isPerformingImport() && !doImportAsDefinition(SGV)) {
1345 LinkFromSrc = false;
1346 } else if (const Comdat *SC = SGV->getComdat()) {
1347 Comdat::SelectionKind SK;
1348 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1349 C = DstM.getOrInsertComdat(SC->getName());
1350 C->setSelectionKind(SK);
1351 if (SGV->hasLocalLinkage())
1354 if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1359 HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1362 if (!LinkFromSrc && DGV) {
1365 // If we are done linking global value bodies (i.e. we are performing
1366 // metadata linking), don't link in the global value due to this
1367 // reference, simply map it to null.
1368 if (DoneLinkingBodies)
1371 NewGV = copyGlobalValueProto(SGV, LinkFromSrc);
1374 setVisibility(NewGV, SGV, DGV);
1375 NewGV->setUnnamedAddr(HasUnnamedAddr);
1377 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1378 if (C && LinkFromSrc)
1379 NewGO->setComdat(C);
1381 if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1382 NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1385 if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1386 auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1387 auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1388 if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1389 (!DGVar->isConstant() || !SGVar->isConstant()))
1390 NewGVar->setConstant(false);
1393 if (NewGV != DGV && DGV) {
1394 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1395 DGV->eraseFromParent();
1398 return ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1401 /// Update the initializers in the Dest module now that all globals that may be
1402 /// referenced are in Dest.
1403 void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1404 // Figure out what the initializer looks like in the dest module.
1405 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
1406 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1409 /// Copy the source function over into the dest function and fix up references
1410 /// to values. At this point we know that Dest is an external function, and
1411 /// that Src is not.
1412 bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1413 assert(Dst.isDeclaration() && !Src.isDeclaration());
1415 // Materialize if needed.
1416 if (std::error_code EC = Src.materialize())
1417 return emitError(EC.message());
1419 // Link in the prefix data.
1420 if (Src.hasPrefixData())
1421 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
1422 RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1424 // Link in the prologue data.
1425 if (Src.hasPrologueData())
1426 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
1427 RF_MoveDistinctMDs, &TypeMap,
1430 // Link in the personality function.
1431 if (Src.hasPersonalityFn())
1432 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
1433 RF_MoveDistinctMDs, &TypeMap,
1436 // Go through and convert function arguments over, remembering the mapping.
1437 Function::arg_iterator DI = Dst.arg_begin();
1438 for (Argument &Arg : Src.args()) {
1439 DI->setName(Arg.getName()); // Copy the name over.
1441 // Add a mapping to our mapping.
1442 ValueMap[&Arg] = &*DI;
1446 // Copy over the metadata attachments.
1447 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1448 Src.getAllMetadata(MDs);
1449 for (const auto &I : MDs)
1450 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
1451 &TypeMap, &ValMaterializer));
1453 // Splice the body of the source function into the dest function.
1454 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1456 // At this point, all of the instructions and values of the function are now
1457 // copied over. The only problem is that they are still referencing values in
1458 // the Source function as operands. Loop through all of the operands of the
1459 // functions and patch them up to point to the local versions.
1460 for (BasicBlock &BB : Dst)
1461 for (Instruction &I : BB)
1462 RemapInstruction(&I, ValueMap,
1463 RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
1466 // There is no need to map the arguments anymore.
1467 for (Argument &Arg : Src.args())
1468 ValueMap.erase(&Arg);
1470 Src.dematerialize();
1474 void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1475 Constant *Aliasee = Src.getAliasee();
1476 Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
1478 Dst.setAliasee(Val);
1481 bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1482 if (const Comdat *SC = Src.getComdat()) {
1483 // To ensure that we don't generate an incomplete comdat group,
1484 // we must materialize and map in any other members that are not
1485 // yet materialized in Dst, which also ensures their definitions
1486 // are linked in. Otherwise, linkonce and other lazy linked GVs will
1487 // not be materialized if they aren't referenced.
1488 for (auto *SGV : ComdatMembers[SC]) {
1489 auto *DGV = cast_or_null<GlobalValue>(ValueMap.lookup(SGV));
1490 if (DGV && !DGV->isDeclaration())
1492 MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1495 if (shouldInternalizeLinkedSymbols())
1496 if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
1497 DGV->setLinkage(GlobalValue::InternalLinkage);
1498 if (auto *F = dyn_cast<Function>(&Src))
1499 return linkFunctionBody(cast<Function>(Dst), *F);
1500 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1501 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1504 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1508 /// Insert all of the named MDNodes in Src into the Dest module.
1509 void ModuleLinker::linkNamedMDNodes() {
1510 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1511 for (const NamedMDNode &NMD : SrcM.named_metadata()) {
1512 // Don't link module flags here. Do them separately.
1513 if (&NMD == SrcModFlags)
1515 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1516 // Add Src elements into Dest node.
1517 for (const MDNode *op : NMD.operands())
1518 DestNMD->addOperand(MapMetadata(
1519 op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
1520 &TypeMap, &ValMaterializer));
1524 /// Merge the linker flags in Src into the Dest module.
1525 bool ModuleLinker::linkModuleFlagsMetadata() {
1526 // If the source module has no module flags, we are done.
1527 const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
1531 // If the destination module doesn't have module flags yet, then just copy
1532 // over the source module's flags.
1533 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1534 if (DstModFlags->getNumOperands() == 0) {
1535 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1536 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1541 // First build a map of the existing module flags and requirements.
1542 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1543 SmallSetVector<MDNode *, 16> Requirements;
1544 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1545 MDNode *Op = DstModFlags->getOperand(I);
1546 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1547 MDString *ID = cast<MDString>(Op->getOperand(1));
1549 if (Behavior->getZExtValue() == Module::Require) {
1550 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1552 Flags[ID] = std::make_pair(Op, I);
1556 // Merge in the flags from the source module, and also collect its set of
1558 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1559 MDNode *SrcOp = SrcModFlags->getOperand(I);
1560 ConstantInt *SrcBehavior =
1561 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1562 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1565 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1566 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1568 // If this is a requirement, add it and continue.
1569 if (SrcBehaviorValue == Module::Require) {
1570 // If the destination module does not already have this requirement, add
1572 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1573 DstModFlags->addOperand(SrcOp);
1578 // If there is no existing flag with this ID, just add it.
1580 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1581 DstModFlags->addOperand(SrcOp);
1585 // Otherwise, perform a merge.
1586 ConstantInt *DstBehavior =
1587 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1588 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1590 // If either flag has override behavior, handle it first.
1591 if (DstBehaviorValue == Module::Override) {
1592 // Diagnose inconsistent flags which both have override behavior.
1593 if (SrcBehaviorValue == Module::Override &&
1594 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1595 emitError("linking module flags '" + ID->getString() +
1596 "': IDs have conflicting override values");
1599 } else if (SrcBehaviorValue == Module::Override) {
1600 // Update the destination flag to that of the source.
1601 DstModFlags->setOperand(DstIndex, SrcOp);
1602 Flags[ID].first = SrcOp;
1606 // Diagnose inconsistent merge behavior types.
1607 if (SrcBehaviorValue != DstBehaviorValue) {
1608 emitError("linking module flags '" + ID->getString() +
1609 "': IDs have conflicting behaviors");
1613 auto replaceDstValue = [&](MDNode *New) {
1614 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1615 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1616 DstModFlags->setOperand(DstIndex, Flag);
1617 Flags[ID].first = Flag;
1620 // Perform the merge for standard behavior types.
1621 switch (SrcBehaviorValue) {
1622 case Module::Require:
1623 case Module::Override:
1624 llvm_unreachable("not possible");
1625 case Module::Error: {
1626 // Emit an error if the values differ.
1627 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1628 emitError("linking module flags '" + ID->getString() +
1629 "': IDs have conflicting values");
1633 case Module::Warning: {
1634 // Emit a warning if the values differ.
1635 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1636 emitWarning("linking module flags '" + ID->getString() +
1637 "': IDs have conflicting values");
1641 case Module::Append: {
1642 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1643 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1644 SmallVector<Metadata *, 8> MDs;
1645 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1646 MDs.append(DstValue->op_begin(), DstValue->op_end());
1647 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1649 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1652 case Module::AppendUnique: {
1653 SmallSetVector<Metadata *, 16> Elts;
1654 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1655 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1656 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1657 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1659 replaceDstValue(MDNode::get(DstM.getContext(),
1660 makeArrayRef(Elts.begin(), Elts.end())));
1666 // Check all of the requirements.
1667 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1668 MDNode *Requirement = Requirements[I];
1669 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1670 Metadata *ReqValue = Requirement->getOperand(1);
1672 MDNode *Op = Flags[Flag].first;
1673 if (!Op || Op->getOperand(2) != ReqValue) {
1674 emitError("linking module flags '" + Flag->getString() +
1675 "': does not have the required value");
1683 // This function returns true if the triples match.
1684 static bool triplesMatch(const Triple &T0, const Triple &T1) {
1685 // If vendor is apple, ignore the version number.
1686 if (T0.getVendor() == Triple::Apple)
1687 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1688 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1693 // This function returns the merged triple.
1694 static std::string mergeTriples(const Triple &SrcTriple,
1695 const Triple &DstTriple) {
1696 // If vendor is apple, pick the triple with the larger version number.
1697 if (SrcTriple.getVendor() == Triple::Apple)
1698 if (DstTriple.isOSVersionLT(SrcTriple))
1699 return SrcTriple.str();
1701 return DstTriple.str();
1704 bool ModuleLinker::linkIfNeeded(GlobalValue &GV) {
1705 GlobalValue *DGV = getLinkedToGlobal(&GV);
1707 if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration()))
1710 if (DGV && !GV.hasLocalLinkage() && !GV.hasAppendingLinkage()) {
1711 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
1712 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
1713 if (DGVar && SGVar) {
1714 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
1715 (!DGVar->isConstant() || !SGVar->isConstant())) {
1716 DGVar->setConstant(false);
1717 SGVar->setConstant(false);
1719 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
1720 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
1721 SGVar->setAlignment(Align);
1722 DGVar->setAlignment(Align);
1726 GlobalValue::VisibilityTypes Visibility =
1727 getMinVisibility(DGV->getVisibility(), GV.getVisibility());
1728 DGV->setVisibility(Visibility);
1729 GV.setVisibility(Visibility);
1731 bool HasUnnamedAddr = GV.hasUnnamedAddr() && DGV->hasUnnamedAddr();
1732 DGV->setUnnamedAddr(HasUnnamedAddr);
1733 GV.setUnnamedAddr(HasUnnamedAddr);
1736 // Don't want to append to global_ctors list, for example, when we
1737 // are importing for ThinLTO, otherwise the global ctors and dtors
1738 // get executed multiple times for local variables (the latter causing
1740 if (GV.hasAppendingLinkage() && isPerformingImport())
1743 if (isPerformingImport() && !doImportAsDefinition(&GV))
1746 if (!DGV && !shouldOverrideFromSrc() &&
1747 (GV.hasLocalLinkage() || GV.hasLinkOnceLinkage() ||
1748 GV.hasAvailableExternallyLinkage()))
1751 if (GV.isDeclaration())
1754 if (const Comdat *SC = GV.getComdat()) {
1756 Comdat::SelectionKind SK;
1757 std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1759 ValuesToLink.insert(&GV);
1763 bool LinkFromSrc = true;
1764 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
1767 ValuesToLink.insert(&GV);
1771 bool ModuleLinker::run() {
1772 // Inherit the target data from the source module if the destination module
1773 // doesn't have one already.
1774 if (DstM.getDataLayout().isDefault())
1775 DstM.setDataLayout(SrcM.getDataLayout());
1777 if (SrcM.getDataLayout() != DstM.getDataLayout()) {
1778 emitWarning("Linking two modules of different data layouts: '" +
1779 SrcM.getModuleIdentifier() + "' is '" +
1780 SrcM.getDataLayoutStr() + "' whereas '" +
1781 DstM.getModuleIdentifier() + "' is '" +
1782 DstM.getDataLayoutStr() + "'\n");
1785 // Copy the target triple from the source to dest if the dest's is empty.
1786 if (DstM.getTargetTriple().empty() && !SrcM.getTargetTriple().empty())
1787 DstM.setTargetTriple(SrcM.getTargetTriple());
1789 Triple SrcTriple(SrcM.getTargetTriple()), DstTriple(DstM.getTargetTriple());
1791 if (!SrcM.getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1792 emitWarning("Linking two modules of different target triples: " +
1793 SrcM.getModuleIdentifier() + "' is '" + SrcM.getTargetTriple() +
1794 "' whereas '" + DstM.getModuleIdentifier() + "' is '" +
1795 DstM.getTargetTriple() + "'\n");
1797 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1799 // Append the module inline asm string.
1800 if (!SrcM.getModuleInlineAsm().empty()) {
1801 if (DstM.getModuleInlineAsm().empty())
1802 DstM.setModuleInlineAsm(SrcM.getModuleInlineAsm());
1804 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
1805 SrcM.getModuleInlineAsm());
1808 // Loop over all of the linked values to compute type mappings.
1809 computeTypeMapping();
1811 ComdatsChosen.clear();
1812 for (const auto &SMEC : SrcM.getComdatSymbolTable()) {
1813 const Comdat &C = SMEC.getValue();
1814 if (ComdatsChosen.count(&C))
1816 Comdat::SelectionKind SK;
1818 if (getComdatResult(&C, SK, LinkFromSrc))
1820 ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1823 for (GlobalVariable &GV : SrcM.globals())
1824 if (const Comdat *SC = GV.getComdat())
1825 ComdatMembers[SC].push_back(&GV);
1827 for (Function &SF : SrcM)
1828 if (const Comdat *SC = SF.getComdat())
1829 ComdatMembers[SC].push_back(&SF);
1831 for (GlobalAlias &GA : SrcM.aliases())
1832 if (const Comdat *SC = GA.getComdat())
1833 ComdatMembers[SC].push_back(&GA);
1835 // Insert all of the globals in src into the DstM module... without linking
1836 // initializers (which could refer to functions not yet mapped over).
1837 for (GlobalVariable &GV : SrcM.globals())
1838 if (linkIfNeeded(GV))
1841 for (Function &SF : SrcM)
1842 if (linkIfNeeded(SF))
1845 for (GlobalAlias &GA : SrcM.aliases())
1846 if (linkIfNeeded(GA))
1849 for (GlobalValue *GV : ValuesToLink) {
1850 MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1855 // Note that we are done linking global value bodies. This prevents
1856 // metadata linking from creating new references.
1857 DoneLinkingBodies = true;
1859 // Remap all of the named MDNodes in Src into the DstM module. We do this
1860 // after linking GlobalValues so that MDNodes that reference GlobalValues
1861 // are properly remapped.
1864 // Merge the module flags into the DstM module.
1865 if (linkModuleFlagsMetadata())
1871 Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1872 : ETypes(E), IsPacked(P) {}
1874 Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1875 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1877 bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1878 if (IsPacked != That.IsPacked)
1880 if (ETypes != That.ETypes)
1885 bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1886 return !this->operator==(That);
1889 StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
1890 return DenseMapInfo<StructType *>::getEmptyKey();
1893 StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
1894 return DenseMapInfo<StructType *>::getTombstoneKey();
1897 unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1898 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1902 unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1903 return getHashValue(KeyTy(ST));
1906 bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1907 const StructType *RHS) {
1908 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1910 return LHS == KeyTy(RHS);
1913 bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
1914 const StructType *RHS) {
1915 if (RHS == getEmptyKey())
1916 return LHS == getEmptyKey();
1918 if (RHS == getTombstoneKey())
1919 return LHS == getTombstoneKey();
1921 return KeyTy(LHS) == KeyTy(RHS);
1924 void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1925 assert(!Ty->isOpaque());
1926 NonOpaqueStructTypes.insert(Ty);
1929 void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1930 assert(!Ty->isOpaque());
1931 NonOpaqueStructTypes.insert(Ty);
1932 bool Removed = OpaqueStructTypes.erase(Ty);
1937 void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1938 assert(Ty->isOpaque());
1939 OpaqueStructTypes.insert(Ty);
1943 Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1945 Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1946 auto I = NonOpaqueStructTypes.find_as(Key);
1947 if (I == NonOpaqueStructTypes.end())
1952 bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1954 return OpaqueStructTypes.count(Ty);
1955 auto I = NonOpaqueStructTypes.find(Ty);
1956 if (I == NonOpaqueStructTypes.end())
1961 Linker::Linker(Module &M, DiagnosticHandlerFunction DiagnosticHandler)
1962 : Composite(M), DiagnosticHandler(DiagnosticHandler) {
1963 TypeFinder StructTypes;
1964 StructTypes.run(M, true);
1965 for (StructType *Ty : StructTypes) {
1967 IdentifiedStructTypes.addOpaque(Ty);
1969 IdentifiedStructTypes.addNonOpaque(Ty);
1973 bool Linker::linkInModule(Module &Src, unsigned Flags,
1974 const FunctionInfoIndex *Index,
1975 DenseSet<const GlobalValue *> *FunctionsToImport) {
1976 ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
1977 DiagnosticHandler, Flags, Index, FunctionsToImport);
1978 bool RetCode = TheLinker.run();
1979 Composite.dropTriviallyDeadConstantArrays();
1983 //===----------------------------------------------------------------------===//
1984 // LinkModules entrypoint.
1985 //===----------------------------------------------------------------------===//
1987 /// This function links two modules together, with the resulting Dest module
1988 /// modified to be the composite of the two input modules. If an error occurs,
1989 /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
1990 /// Upon failure, the Dest module could be in a modified state, and shouldn't be
1991 /// relied on to be consistent.
1992 bool Linker::linkModules(Module &Dest, Module &Src,
1993 DiagnosticHandlerFunction DiagnosticHandler,
1995 Linker L(Dest, DiagnosticHandler);
1996 return L.linkInModule(Src, Flags);
1999 std::unique_ptr<Module>
2000 llvm::renameModuleForThinLTO(std::unique_ptr<Module> &M,
2001 const FunctionInfoIndex *Index,
2002 DiagnosticHandlerFunction DiagnosticHandler) {
2003 std::unique_ptr<llvm::Module> RenamedModule(
2004 new llvm::Module(M->getModuleIdentifier(), M->getContext()));
2005 Linker L(*RenamedModule.get(), DiagnosticHandler);
2006 if (L.linkInModule(*M.get(), llvm::Linker::Flags::None, Index))
2008 return RenamedModule;
2011 //===----------------------------------------------------------------------===//
2013 //===----------------------------------------------------------------------===//
2015 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2016 LLVMLinkerMode Unused, char **OutMessages) {
2017 Module *D = unwrap(Dest);
2018 std::string Message;
2019 raw_string_ostream Stream(Message);
2020 DiagnosticPrinterRawOStream DP(Stream);
2022 LLVMBool Result = Linker::linkModules(
2023 *D, *unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
2025 if (OutMessages && Result) {
2027 *OutMessages = strdup(Message.c_str());