32 std::unique_ptr<Module> SrcM;
45 std::function<void(Module &, const StringSet<> &)> InternalizeCallback;
56 bool shouldLinkFromSource(
bool &LinkFromSrc,
const GlobalValue &Dest,
60 bool emitError(
const Twine &Message) {
67 bool computeResultingSelectionKind(
StringRef ComdatName,
72 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
82 Module &DstM = Mover.getModule();
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!");
151 bool ModuleLinker::computeResultingSelectionKind(
StringRef ComdatName,
160 Dst == Comdat::SelectionKind::Largest;
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;
169 }
else if (Src == Dst) {
172 return emitError(
"Linking COMDATs named '" + ComdatName +
173 "': invalid selection kinds!");
181 case Comdat::SelectionKind::NoDuplicates:
182 return emitError(
"Linking COMDATs named '" + ComdatName +
183 "': noduplicates has been violated!");
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!");
202 }
else if (Result == Comdat::SelectionKind::Largest) {
203 LinkFromSrc = SrcSize > DstSize;
204 }
else if (Result == Comdat::SelectionKind::SameSize) {
205 if (SrcSize != DstSize)
206 return emitError(
"Linking COMDATs named '" + ComdatName +
207 "': SameSize violated!");
219 bool ModuleLinker::getComdatResult(
const Comdat *SrcC,
228 if (DstCI == ComdatSymTab.
end()) {
235 const Comdat *DstC = &DstCI->second;
237 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
241 bool ModuleLinker::shouldLinkFromSource(
bool &LinkFromSrc,
246 if (shouldOverrideFromSrc()) {
260 if (SrcIsDeclaration) {
265 LinkFromSrc = DestIsDeclaration;
278 if (DestIsDeclaration) {
298 LinkFromSrc = SrcSize > DestSize;
324 "Unexpected linkage type!");
325 return emitError(
"Linking globals named '" + Src.
getName() +
326 "': symbol multiply defined!");
332 if (shouldLinkOnlyNeeded() && !(DGV && DGV->
isDeclaration()))
338 if (DGVar && SGVar) {
339 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
340 (!DGVar->isConstant() || !SGVar->isConstant())) {
342 SGVar->setConstant(
false);
344 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
345 unsigned Align =
std::max(DGVar->getAlignment(), SGVar->getAlignment());
346 SGVar->setAlignment(Align);
347 DGVar->setAlignment(Align);
362 if (!DGV && !shouldOverrideFromSrc() &&
373 std::tie(SK, LinkFromSrc) = ComdatsChosen[
SC];
378 bool LinkFromSrc =
true;
379 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
382 ValuesToLink.insert(&GV);
389 !shouldLinkOnlyNeeded())
392 if (InternalizeCallback)
393 Internalize.insert(GV.
getName());
401 bool LinkFromSrc =
true;
402 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
406 if (InternalizeCallback)
407 Internalize.insert(GV2->getName());
412 void ModuleLinker::dropReplacedComdat(
417 if (!ReplacedDstComdats.
count(C))
424 if (
auto *
F = dyn_cast<Function>(&GV)) {
426 }
else if (
auto *Var = dyn_cast<GlobalVariable>(&GV)) {
427 Var->setInitializer(
nullptr);
429 auto &Alias = cast<GlobalAlias>(GV);
430 Module &M = *Alias.getParent();
431 PointerType &Ty = *cast<PointerType>(Alias.getType());
433 if (
auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
442 Alias.replaceAllUsesWith(Declaration);
443 Alias.eraseFromParent();
447 bool ModuleLinker::run() {
451 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
452 const Comdat &C = SMEC.getValue();
453 if (ComdatsChosen.count(&C))
457 if (getComdatResult(&C, SK, LinkFromSrc))
459 ComdatsChosen[&
C] = std::make_pair(SK, LinkFromSrc);
466 if (DstCI == ComdatSymTab.
end())
470 const Comdat *DstC = &DstCI->second;
471 ReplacedDstComdats.
insert(DstC);
478 dropReplacedComdat(GV, ReplacedDstComdats);
483 dropReplacedComdat(GV, ReplacedDstComdats);
488 dropReplacedComdat(GV, ReplacedDstComdats);
494 LazyComdatMembers[SC].push_back(&GV);
497 if (SF.hasLinkOnceLinkage())
498 if (
const Comdat *SC = SF.getComdat())
499 LazyComdatMembers[SC].push_back(&SF);
502 if (GA.hasLinkOnceLinkage())
503 if (
const Comdat *SC = GA.getComdat())
504 LazyComdatMembers[SC].push_back(&GA);
509 if (linkIfNeeded(GV))
513 if (linkIfNeeded(SF))
517 if (linkIfNeeded(GA))
520 for (
unsigned I = 0;
I < ValuesToLink.size(); ++
I) {
527 bool LinkFromSrc =
true;
528 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
531 ValuesToLink.insert(GV2);
535 if (InternalizeCallback) {
537 Internalize.insert(GV->
getName());
542 bool HasErrors =
false;
543 if (
Error E = Mover.
move(std::move(SrcM), ValuesToLink.getArrayRef(),
556 if (InternalizeCallback)
557 InternalizeCallback(DstM, Internalize);
565 std::unique_ptr<Module> Src,
unsigned Flags,
567 ModuleLinker ModLinker(Mover, std::move(Src), Flags,
568 std::move(InternalizeCallback));
569 return ModLinker.run();
582 Module &Dest, std::unique_ptr<Module> Src,
unsigned Flags,
585 return L.
linkInModule(std::move(Src), Flags, std::move(InternalizeCallback));
594 std::unique_ptr<Module> M(
unwrap(Src));
void setVisibility(VisibilityTypes V)
A parsed version of the target data layout string in and methods for querying it. ...
LinkageTypes getLinkage() const
VisibilityTypes getVisibility() const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
A Module instance is used to store all the information related to an LLVM module. ...
Implements a dense probed hash-table based set.
UnnamedAddr getUnnamedAddr() const
Type * getValueType() const
bool hasAppendingLinkage() const
iterator find(StringRef Key)
Externally visible function.
bool hasAvailableExternallyLinkage() const
ELFYAML::ELF_STV Visibility
Type * getElementType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Base class for error info classes.
LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src)
const Comdat * getComdat() const
static bool isLocalLinkage(LinkageTypes Linkage)
StringRef getName() const
Return a constant reference to the value's name.
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.
bool hasCommonLinkage() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Attribute unwrap(LLVMAttributeRef Attr)
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...
const GlobalObject * getBaseObject() const
StringRef getName() const
global_iterator global_begin()
VisibilityTypes
An enumeration for the kinds of visibility of global values.
This class provides the core functionality of linking in LLVM.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
void takeName(Value *V)
Transfer the name from V to this value.
Class to represent pointers.
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
alias_iterator alias_end()
std::pair< iterator, bool > insert(const ValueT &V)
SelectionKind getSelectionKind() const
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
static GlobalValue::VisibilityTypes getMinVisibility(GlobalValue::VisibilityTypes A, GlobalValue::VisibilityTypes B)
void setConstant(bool Val)
bool hasWeakLinkage() const
global_iterator global_end()
bool hasExternalWeakLinkage() const
bool hasExternalLinkage() const
bool hasDLLImportStorageClass() const
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Module.h This file contains the declarations for the Module class.
CHAIN = SC CHAIN, Imm128 - System call.
alias_iterator alias_begin()
bool linkInModule(std::unique_ptr< Module > Src, unsigned Flags=Flags::None, std::function< void(Module &, const StringSet<> &)> InternalizeCallback={})
Link Src into the composite.
llvm_unreachable("Unknown RegBank!")
static std::vector< std::string > Flags
bool hasLinkOnceLinkage() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
void setUnnamedAddr(UnnamedAddr Val)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool hasLocalLinkage() 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.
virtual std::string message() const
Return the error message as a string.
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B)
bool isDeclarationForLinker() const
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
LLVMContext & getContext() const
Get the global data context.