26enum class LinkFrom { Dst, Src, Both };
32 std::unique_ptr<Module> SrcM;
56 bool shouldLinkFromSource(
bool &LinkFromSrc,
const GlobalValue &Dest,
60 bool emitError(
const Twine &Message) {
67 bool computeResultingSelectionKind(
StringRef ComdatName,
110 ModuleLinker(
IRMover &Mover, std::unique_ptr<Module> SrcM,
unsigned Flags,
112 InternalizeCallback = {})
113 : Mover(Mover), SrcM(std::move(SrcM)),
Flags(Flags),
114 InternalizeCallback(std::move(InternalizeCallback)) {}
134 if (
const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
138 return emitError(
"Linking COMDATs named '" + ComdatName +
139 "': COMDAT key involves incomputable alias size.");
142 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
145 "Linking COMDATs named '" + ComdatName +
146 "': GlobalVariable required for data dependent selection!");
151bool ModuleLinker::computeResultingSelectionKind(
StringRef ComdatName,
159 bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
160 Dst == Comdat::SelectionKind::Largest;
161 bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
162 Src == Comdat::SelectionKind::Largest;
163 if (DstAnyOrLargest && SrcAnyOrLargest) {
164 if (Dst == Comdat::SelectionKind::Largest ||
165 Src == Comdat::SelectionKind::Largest)
166 Result = Comdat::SelectionKind::Largest;
168 Result = Comdat::SelectionKind::Any;
169 }
else if (Src == Dst) {
172 return emitError(
"Linking COMDATs named '" + ComdatName +
173 "': invalid selection kinds!");
177 case Comdat::SelectionKind::Any:
179 From = LinkFrom::Dst;
181 case Comdat::SelectionKind::NoDeduplicate:
182 From = LinkFrom::Both;
184 case Comdat::SelectionKind::ExactMatch:
185 case Comdat::SelectionKind::Largest:
186 case Comdat::SelectionKind::SameSize: {
189 if (getComdatLeader(DstM, ComdatName, DstGV) ||
190 getComdatLeader(*SrcM, ComdatName, SrcGV))
194 const DataLayout &SrcDL = SrcM->getDataLayout();
197 if (Result == Comdat::SelectionKind::ExactMatch) {
199 return emitError(
"Linking COMDATs named '" + ComdatName +
200 "': ExactMatch violated!");
201 From = LinkFrom::Dst;
202 }
else if (Result == Comdat::SelectionKind::Largest) {
203 From = SrcSize > DstSize ? LinkFrom::Src : LinkFrom::Dst;
204 }
else if (Result == Comdat::SelectionKind::SameSize) {
205 if (SrcSize != DstSize)
206 return emitError(
"Linking COMDATs named '" + ComdatName +
207 "': SameSize violated!");
208 From = LinkFrom::Dst;
219bool ModuleLinker::getComdatResult(
const Comdat *SrcC,
228 if (DstCI == ComdatSymTab.
end()) {
230 From = LinkFrom::Src;
235 const Comdat *DstC = &DstCI->second;
237 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
From);
240bool ModuleLinker::shouldLinkFromSource(
bool &LinkFromSrc,
245 if (shouldOverrideFromSrc()) {
256 bool SrcIsDeclaration = Src.isDeclarationForLinker();
259 if (SrcIsDeclaration) {
262 if (Src.hasDLLImportStorageClass()) {
264 LinkFromSrc = DestIsDeclaration;
277 if (DestIsDeclaration) {
283 if (Src.hasCommonLinkage()) {
296 uint64_t SrcSize =
DL.getTypeAllocSize(Src.getValueType());
297 LinkFromSrc = SrcSize > DestSize;
301 if (Src.isWeakForLinker()) {
315 assert(Src.hasExternalLinkage());
320 assert(!Src.hasExternalWeakLinkage());
323 "Unexpected linkage type!");
324 return emitError(
"Linking globals named '" + Src.getName() +
325 "': symbol multiply defined!");
332 if (shouldLinkOnlyNeeded()) {
346 auto *DGVar = dyn_cast<GlobalVariable>(DGV);
347 auto *SGVar = dyn_cast<GlobalVariable>(&GV);
348 if (DGVar && SGVar) {
349 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
350 (!DGVar->isConstant() || !SGVar->isConstant())) {
351 DGVar->setConstant(
false);
352 SGVar->setConstant(
false);
354 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
358 if (DAlign || SAlign)
361 SGVar->setAlignment(
Align);
362 DGVar->setAlignment(
Align);
377 if (!DGV && !shouldOverrideFromSrc() &&
385 LinkFrom ComdatFrom = LinkFrom::Dst;
387 std::tie(std::ignore, ComdatFrom) = ComdatsChosen[
SC];
388 if (ComdatFrom == LinkFrom::Dst)
392 bool LinkFromSrc =
true;
393 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
395 if (DGV && ComdatFrom == LinkFrom::Both)
396 GVToClone.
push_back(LinkFromSrc ? DGV : &GV);
405 !shouldLinkOnlyNeeded())
408 if (InternalizeCallback)
417 bool LinkFromSrc =
true;
418 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
422 if (InternalizeCallback)
423 Internalize.
insert(GV2->getName());
428void ModuleLinker::dropReplacedComdat(
433 if (!ReplacedDstComdats.
count(
C))
440 if (
auto *
F = dyn_cast<Function>(&GV)) {
442 }
else if (
auto *Var = dyn_cast<GlobalVariable>(&GV)) {
443 Var->setInitializer(
nullptr);
445 auto &Alias = cast<GlobalAlias>(GV);
446 Module &
M = *Alias.getParent();
448 if (
auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
457 Alias.replaceAllUsesWith(Declaration);
458 Alias.eraseFromParent();
462bool ModuleLinker::run() {
466 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
467 const Comdat &
C = SMEC.getValue();
468 if (ComdatsChosen.
count(&
C))
472 if (getComdatResult(&
C, SK,
From))
474 ComdatsChosen[&
C] = std::make_pair(SK,
From);
476 if (
From != LinkFrom::Src)
481 if (DstCI == ComdatSymTab.
end())
485 const Comdat *DstC = &DstCI->second;
486 ReplacedDstComdats.
insert(DstC);
492 dropReplacedComdat(GV, ReplacedDstComdats);
495 dropReplacedComdat(GV, ReplacedDstComdats);
498 dropReplacedComdat(GV, ReplacedDstComdats);
503 LazyComdatMembers[
SC].push_back(&GV);
506 if (SF.hasLinkOnceLinkage())
507 if (
const Comdat *SC = SF.getComdat())
508 LazyComdatMembers[
SC].push_back(&SF);
511 if (GA.hasLinkOnceLinkage())
512 if (
const Comdat *SC = GA.getComdat())
513 LazyComdatMembers[
SC].push_back(&GA);
519 if (linkIfNeeded(GV, GVToClone))
523 if (linkIfNeeded(SF, GVToClone))
527 if (linkIfNeeded(GA, GVToClone))
531 if (linkIfNeeded(GI, GVToClone))
539 if (
auto *Var = dyn_cast<GlobalVariable>(GV)) {
540 auto *NewVar =
new GlobalVariable(*Var->getParent(), Var->getValueType(),
541 Var->isConstant(), Var->getLinkage(),
542 Var->getInitializer());
543 NewVar->copyAttributesFrom(Var);
546 NewVar->setDSOLocal(
true);
547 NewVar->setComdat(Var->getComdat());
548 if (Var->getParent() != &Mover.
getModule())
549 ValuesToLink.
insert(NewVar);
551 emitError(
"linking '" + GV->
getName() +
552 "': non-variables in comdat nodeduplicate are not handled");
556 for (
unsigned I = 0;
I < ValuesToLink.
size(); ++
I) {
563 bool LinkFromSrc =
true;
564 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
571 if (InternalizeCallback) {
578 bool HasErrors =
false;
580 Mover.
move(std::move(SrcM), ValuesToLink.getArrayRef(),
594 if (InternalizeCallback)
595 InternalizeCallback(DstM, Internalize);
603 std::unique_ptr<Module> Src,
unsigned Flags,
605 ModuleLinker ModLinker(Mover, std::move(Src),
Flags,
606 std::move(InternalizeCallback));
607 return ModLinker.run();
620 Module &Dest, std::unique_ptr<Module> Src,
unsigned Flags,
623 return L.linkInModule(std::move(Src),
Flags, std::move(InternalizeCallback));
632 std::unique_ptr<Module> M(
unwrap(Src));
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GlobalValue::VisibilityTypes getMinVisibility(GlobalValue::VisibilityTypes A, GlobalValue::VisibilityTypes B)
Module.h This file contains the declarations for the Module class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements a set that has insertion order iteration characteristics.
StringRef getName() const
SelectionKind getSelectionKind() const
A parsed version of the target data layout string in and methods for querying it.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Implements a dense probed hash-table based set.
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
Lightweight error class with error context and mandatory checking.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
bool hasLinkOnceLinkage() const
bool hasExternalLinkage() const
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
void setUnnamedAddr(UnnamedAddr Val)
bool hasLocalLinkage() const
const Comdat * getComdat() const
bool hasExternalWeakLinkage() const
bool isDeclarationForLinker() const
static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B)
Module * getParent()
Get the module that this global value is contained inside of...
const GlobalObject * getAliaseeObject() const
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
void setVisibility(VisibilityTypes V)
bool hasWeakLinkage() const
bool hasCommonLinkage() const
UnnamedAddr getUnnamedAddr() const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
bool hasAppendingLinkage() const
bool hasAvailableExternallyLinkage() const
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ ExternalLinkage
Externally visible function.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
std::function< void(GlobalValue &)> ValueAdder
This class provides the core functionality of linking in LLVM.
bool linkInModule(std::unique_ptr< Module > Src, unsigned Flags=Flags::None, std::function< void(Module &, const StringSet<> &)> InternalizeCallback={})
Link Src into the composite.
static bool linkModules(Module &Dest, std::unique_ptr< Module > Src, unsigned Flags=Flags::None, std::function< void(Module &, const StringSet<> &)> InternalizeCallback={})
This function links two modules together, with the resulting Dest module modified to be the composite...
A Module instance is used to store all the information related to an LLVM module.
LLVMContext & getContext() const
Get the global data context.
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
iterator_range< alias_iterator > aliases()
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
iterator_range< global_iterator > globals()
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
A vector that has set insertion semantics.
size_type size() const
Determine the number of elements in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator find(StringRef Key)
StringRef - Represent a constant reference to a string, i.e.
StringSet - A wrapper for StringMap that provides set-like functionality.
std::pair< typename Base::iterator, bool > insert(StringRef key)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
StringRef getName() const
Return a constant reference to the value's name.
void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
unique_function is a type-erasing functor similar to std::function.
LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src)
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Attribute unwrap(LLVMAttributeRef Attr)
This struct is a compact representation of a valid (non-zero power of two) alignment.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.