31 std::unique_ptr<Module> SrcM;
44 std::function<void(Module &, const StringSet<> &)> InternalizeCallback;
55 bool shouldLinkFromSource(
bool &LinkFromSrc,
const GlobalValue &Dest,
59 bool emitError(
const Twine &Message) {
66 bool computeResultingSelectionKind(
StringRef ComdatName,
71 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
109 ModuleLinker(
IRMover &Mover, std::unique_ptr<Module> SrcM,
unsigned Flags,
111 InternalizeCallback = {})
112 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
113 InternalizeCallback(std::move(InternalizeCallback)) {}
133 if (
const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
137 return emitError(
"Linking COMDATs named '" + ComdatName +
138 "': COMDAT key involves incomputable alias size.");
141 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
144 "Linking COMDATs named '" + ComdatName +
145 "': GlobalVariable required for data dependent selection!");
150 bool ModuleLinker::computeResultingSelectionKind(
StringRef ComdatName,
159 Dst == Comdat::SelectionKind::Largest;
161 Src == Comdat::SelectionKind::Largest;
162 if (DstAnyOrLargest && SrcAnyOrLargest) {
163 if (Dst == Comdat::SelectionKind::Largest ||
164 Src == Comdat::SelectionKind::Largest)
165 Result = Comdat::SelectionKind::Largest;
168 }
else if (Src == Dst) {
171 return emitError(
"Linking COMDATs named '" + ComdatName +
172 "': invalid selection kinds!");
180 case Comdat::SelectionKind::NoDuplicates:
181 return emitError(
"Linking COMDATs named '" + ComdatName +
182 "': noduplicates has been violated!");
183 case Comdat::SelectionKind::ExactMatch:
184 case Comdat::SelectionKind::Largest:
185 case Comdat::SelectionKind::SameSize: {
188 if (getComdatLeader(DstM, ComdatName, DstGV) ||
189 getComdatLeader(*SrcM, ComdatName, SrcGV))
193 const DataLayout &SrcDL = SrcM->getDataLayout();
196 if (Result == Comdat::SelectionKind::ExactMatch) {
198 return emitError(
"Linking COMDATs named '" + ComdatName +
199 "': ExactMatch violated!");
201 }
else if (Result == Comdat::SelectionKind::Largest) {
202 LinkFromSrc = SrcSize > DstSize;
203 }
else if (Result == Comdat::SelectionKind::SameSize) {
204 if (SrcSize != DstSize)
205 return emitError(
"Linking COMDATs named '" + ComdatName +
206 "': SameSize violated!");
218 bool ModuleLinker::getComdatResult(
const Comdat *SrcC,
227 if (DstCI == ComdatSymTab.
end()) {
234 const Comdat *DstC = &DstCI->second;
236 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
240 bool ModuleLinker::shouldLinkFromSource(
bool &LinkFromSrc,
245 if (shouldOverrideFromSrc()) {
259 if (SrcIsDeclaration) {
264 LinkFromSrc = DestIsDeclaration;
277 if (DestIsDeclaration) {
297 LinkFromSrc = SrcSize > DestSize;
323 "Unexpected linkage type!");
324 return emitError(
"Linking globals named '" + Src.
getName() +
325 "': symbol multiply defined!");
331 if (shouldLinkOnlyNeeded()) {
347 if (DGVar && SGVar) {
348 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
349 (!DGVar->isConstant() || !SGVar->isConstant())) {
351 SGVar->setConstant(
false);
353 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
355 std::max(DGVar->getAlignment(), SGVar->getAlignment()));
356 SGVar->setAlignment(Align);
357 DGVar->setAlignment(Align);
372 if (!DGV && !shouldOverrideFromSrc() &&
383 std::tie(SK, LinkFromSrc) = ComdatsChosen[
SC];
388 bool LinkFromSrc =
true;
389 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
399 !shouldLinkOnlyNeeded())
402 if (InternalizeCallback)
411 bool LinkFromSrc =
true;
412 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
416 if (InternalizeCallback)
417 Internalize.
insert(GV2->getName());
422 void ModuleLinker::dropReplacedComdat(
427 if (!ReplacedDstComdats.
count(C))
434 if (
auto *
F = dyn_cast<Function>(&GV)) {
436 }
else if (
auto *Var = dyn_cast<GlobalVariable>(&GV)) {
437 Var->setInitializer(
nullptr);
439 auto &Alias = cast<GlobalAlias>(GV);
440 Module &M = *Alias.getParent();
441 PointerType &Ty = *cast<PointerType>(Alias.getType());
443 if (
auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
452 Alias.replaceAllUsesWith(Declaration);
453 Alias.eraseFromParent();
457 bool ModuleLinker::run() {
461 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
462 const Comdat &
C = SMEC.getValue();
463 if (ComdatsChosen.count(&C))
467 if (getComdatResult(&C, SK, LinkFromSrc))
469 ComdatsChosen[&
C] = std::make_pair(SK, LinkFromSrc);
476 if (DstCI == ComdatSymTab.
end())
480 const Comdat *DstC = &DstCI->second;
481 ReplacedDstComdats.
insert(DstC);
488 dropReplacedComdat(GV, ReplacedDstComdats);
493 dropReplacedComdat(GV, ReplacedDstComdats);
498 dropReplacedComdat(GV, ReplacedDstComdats);
504 LazyComdatMembers[
SC].push_back(&GV);
507 if (SF.hasLinkOnceLinkage())
508 if (
const Comdat *
SC = SF.getComdat())
509 LazyComdatMembers[
SC].push_back(&SF);
512 if (GA.hasLinkOnceLinkage())
513 if (
const Comdat *
SC = GA.getComdat())
514 LazyComdatMembers[
SC].push_back(&GA);
519 if (linkIfNeeded(GV))
523 if (linkIfNeeded(SF))
527 if (linkIfNeeded(GA))
530 for (
unsigned I = 0;
I < ValuesToLink.
size(); ++
I) {
537 bool LinkFromSrc =
true;
538 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
545 if (InternalizeCallback) {
552 bool HasErrors =
false;
566 if (InternalizeCallback)
567 InternalizeCallback(DstM, Internalize);
575 std::unique_ptr<Module> Src,
unsigned Flags,
577 ModuleLinker ModLinker(Mover, std::move(Src), Flags,
578 std::move(InternalizeCallback));
579 return ModLinker.run();
592 Module &Dest, std::unique_ptr<Module> Src,
unsigned Flags,
595 return L.
linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
604 std::unique_ptr<Module> M(
unwrap(Src));
void setVisibility(VisibilityTypes V)
bool isDeclarationForLinker() const
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool hasLocalLinkage() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
ArrayRef< T > getArrayRef() const
size_type size() const
Determine the number of elements in the SetVector.
A Module instance is used to store all the information related to an LLVM module. ...
Implements a dense probed hash-table based set.
bool hasAvailableExternallyLinkage() const
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
iterator find(StringRef Key)
virtual std::string message() const
Return the error message as a string.
Externally visible function.
bool hasDLLImportStorageClass() const
bool hasExternalWeakLinkage() const
Base class for error info classes.
LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src)
static bool isLocalLinkage(LinkageTypes Linkage)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Attribute unwrap(LLVMAttributeRef Attr)
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
LLVMContext & getContext() const
Get the global data context.
UnnamedAddr getUnnamedAddr() const
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...
bool hasCommonLinkage() const
global_iterator global_begin()
bool hasExternalLinkage() const
bool insert(const value_type &X)
Insert a new element into the SetVector.
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue *> ValuesToLink, std::function< void(GlobalValue &GV, ValueAdder Add)> AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
This class provides the core functionality of linking in LLVM.
LinkageTypes getLinkage() const
bool hasLinkOnceLinkage() const
void takeName(Value *V)
Transfer the name from V to this value.
Class to represent pointers.
bool hasAppendingLinkage() const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
StringRef getName() const
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
VisibilityTypes getVisibility() const
alias_iterator alias_end()
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const ValueT &V)
static GlobalValue::VisibilityTypes getMinVisibility(GlobalValue::VisibilityTypes A, GlobalValue::VisibilityTypes B)
void setConstant(bool Val)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< typename base::iterator, bool > insert(StringRef Key)
bool hasWeakLinkage() const
global_iterator global_end()
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Module.h This file contains the declarations for the Module class.
CHAIN = SC CHAIN, Imm128 - System call.
alias_iterator alias_begin()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
const Comdat * getComdat() const
bool linkInModule(std::unique_ptr< Module > Src, unsigned Flags=Flags::None, std::function< void(Module &, const StringSet<> &)> InternalizeCallback={})
Link Src into the composite.
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
void setUnnamedAddr(UnnamedAddr Val)
StringRef getName() const
Return a constant reference to the value's name.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const GlobalObject * getBaseObject() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::function< void(GlobalValue &)> ValueAdder
Module * getParent()
Get the module that this global value is contained inside of...
A vector that has set insertion semantics.
Lightweight error class with error context and mandatory checking.
StringSet - A wrapper for StringMap that provides set-like functionality.
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B)
Type * getElementType() const
SelectionKind getSelectionKind() const