31 std::unique_ptr<Module> SrcM;
49 bool shouldLinkReferencedLinkOnce() {
54 bool shouldInternalizeLinkedSymbols() {
58 bool shouldLinkFromSource(
bool &LinkFromSrc,
const GlobalValue &Dest,
62 bool emitError(
const Twine &Message) {
69 bool computeResultingSelectionKind(
StringRef ComdatName,
74 std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
84 Module &DstM = Mover.getModule();
113 bool isPerformingImport()
const {
return GlobalsToImport !=
nullptr; }
120 ModuleLinker(
IRMover &Mover, std::unique_ptr<Module> SrcM,
unsigned Flags,
122 : Mover(Mover), SrcM(std::move(SrcM)), Flags(Flags),
123 GlobalsToImport(GlobalsToImport) {}
129 bool ModuleLinker::doImportAsDefinition(
const GlobalValue *SGV) {
130 if (!isPerformingImport())
132 return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
150 if (
const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
154 return emitError(
"Linking COMDATs named '" + ComdatName +
155 "': COMDAT key involves incomputable alias size.");
158 GVar = dyn_cast_or_null<GlobalVariable>(GVal);
161 "Linking COMDATs named '" + ComdatName +
162 "': GlobalVariable required for data dependent selection!");
167 bool ModuleLinker::computeResultingSelectionKind(
StringRef ComdatName,
172 Module &DstM = Mover.getModule();
176 Dst == Comdat::SelectionKind::Largest;
178 Src == Comdat::SelectionKind::Largest;
179 if (DstAnyOrLargest && SrcAnyOrLargest) {
180 if (Dst == Comdat::SelectionKind::Largest ||
181 Src == Comdat::SelectionKind::Largest)
182 Result = Comdat::SelectionKind::Largest;
185 }
else if (Src == Dst) {
188 return emitError(
"Linking COMDATs named '" + ComdatName +
189 "': invalid selection kinds!");
197 case Comdat::SelectionKind::NoDuplicates:
198 return emitError(
"Linking COMDATs named '" + ComdatName +
199 "': noduplicates has been violated!");
200 case Comdat::SelectionKind::ExactMatch:
201 case Comdat::SelectionKind::Largest:
202 case Comdat::SelectionKind::SameSize: {
205 if (getComdatLeader(DstM, ComdatName, DstGV) ||
206 getComdatLeader(*SrcM, ComdatName, SrcGV))
210 const DataLayout &SrcDL = SrcM->getDataLayout();
213 if (Result == Comdat::SelectionKind::ExactMatch) {
215 return emitError(
"Linking COMDATs named '" + ComdatName +
216 "': ExactMatch violated!");
218 }
else if (Result == Comdat::SelectionKind::Largest) {
219 LinkFromSrc = SrcSize > DstSize;
220 }
else if (Result == Comdat::SelectionKind::SameSize) {
221 if (SrcSize != DstSize)
222 return emitError(
"Linking COMDATs named '" + ComdatName +
223 "': SameSize violated!");
235 bool ModuleLinker::getComdatResult(
const Comdat *SrcC,
238 Module &DstM = Mover.getModule();
244 if (DstCI == ComdatSymTab.
end()) {
251 const Comdat *DstC = &DstCI->second;
253 return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
257 bool ModuleLinker::shouldLinkFromSource(
bool &LinkFromSrc,
262 if (shouldOverrideFromSrc()) {
270 assert(!isPerformingImport());
275 if (isPerformingImport()) {
277 LinkFromSrc = GlobalsToImport->count(&Src);
284 if (SrcIsDeclaration) {
289 LinkFromSrc = DestIsDeclaration;
302 if (DestIsDeclaration) {
322 LinkFromSrc = SrcSize > DestSize;
348 "Unexpected linkage type!");
349 return emitError(
"Linking globals named '" + Src.
getName() +
350 "': symbol multiply defined!");
356 if (shouldLinkOnlyNeeded() && !(DGV && DGV->
isDeclaration()))
362 if (DGVar && SGVar) {
363 if (DGVar->isDeclaration() && SGVar->isDeclaration() &&
364 (!DGVar->isConstant() || !SGVar->isConstant())) {
366 SGVar->setConstant(
false);
368 if (DGVar->hasCommonLinkage() && SGVar->hasCommonLinkage()) {
369 unsigned Align = std::max(DGVar->getAlignment(), SGVar->getAlignment());
370 SGVar->setAlignment(Align);
371 DGVar->setAlignment(Align);
393 if (isPerformingImport()) {
394 if (!doImportAsDefinition(&GV))
396 }
else if (!DGV && !shouldOverrideFromSrc() &&
407 std::tie(SK, LinkFromSrc) = ComdatsChosen[
SC];
412 bool LinkFromSrc =
true;
413 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, GV))
416 ValuesToLink.insert(&GV);
421 if (!shouldLinkReferencedLinkOnce())
431 if (shouldInternalizeLinkedSymbols())
432 Internalize.insert(GV.
getName());
440 bool LinkFromSrc =
true;
441 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
445 if (shouldInternalizeLinkedSymbols())
446 Internalize.insert(GV2->getName());
451 void ModuleLinker::dropReplacedComdat(
456 if (!ReplacedDstComdats.
count(C))
463 if (
auto *
F = dyn_cast<Function>(&GV)) {
465 }
else if (
auto *Var = dyn_cast<GlobalVariable>(&GV)) {
466 Var->setInitializer(
nullptr);
468 auto &Alias = cast<GlobalAlias>(GV);
469 Module &M = *Alias.getParent();
470 PointerType &Ty = *cast<PointerType>(Alias.getType());
472 if (
auto *FTy = dyn_cast<FunctionType>(Alias.getValueType())) {
481 Alias.replaceAllUsesWith(Declaration);
482 Alias.eraseFromParent();
486 bool ModuleLinker::run() {
487 Module &DstM = Mover.getModule();
490 for (
const auto &SMEC : SrcM->getComdatSymbolTable()) {
491 const Comdat &C = SMEC.getValue();
492 if (ComdatsChosen.count(&C))
496 if (getComdatResult(&C, SK, LinkFromSrc))
498 ComdatsChosen[&
C] = std::make_pair(SK, LinkFromSrc);
505 if (DstCI == ComdatSymTab.
end())
509 const Comdat *DstC = &DstCI->second;
510 ReplacedDstComdats.
insert(DstC);
517 dropReplacedComdat(GV, ReplacedDstComdats);
522 dropReplacedComdat(GV, ReplacedDstComdats);
527 dropReplacedComdat(GV, ReplacedDstComdats);
533 LazyComdatMembers[SC].push_back(&GV);
536 if (SF.hasLinkOnceLinkage())
537 if (
const Comdat *SC = SF.getComdat())
538 LazyComdatMembers[SC].push_back(&SF);
541 if (GA.hasLinkOnceLinkage())
542 if (
const Comdat *SC = GA.getComdat())
543 LazyComdatMembers[SC].push_back(&GA);
548 if (linkIfNeeded(GV))
552 if (linkIfNeeded(SF))
556 if (linkIfNeeded(GA))
559 for (
unsigned I = 0;
I < ValuesToLink.size(); ++
I) {
566 bool LinkFromSrc =
true;
567 if (DGV && shouldLinkFromSource(LinkFromSrc, *DGV, *GV2))
570 ValuesToLink.insert(GV2);
574 if (shouldInternalizeLinkedSymbols()) {
576 Internalize.insert(GV->
getName());
581 bool HasErrors =
false;
582 if (
Error E = Mover.move(std::move(SrcM), ValuesToLink.getArrayRef(),
586 !isPerformingImport(),
587 isPerformingImport())) {
596 for (
auto &
P : Internalize) {
608 ModuleLinker ModLinker(Mover, std::move(Src), Flags, GlobalsToImport);
609 return ModLinker.run();
633 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
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
static bool linkModules(Module &Dest, std::unique_ptr< Module > Src, unsigned Flags=Flags::None)
This function links two modules together, with the resulting Dest module modified to be the composite...
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)
static bool isLocalLinkage(LinkageTypes Linkage)
StringRef getName() const
Return a constant reference to the value's name.
Don't force link referenced linkonce definitions, import declaration.
bool hasCommonLinkage() const
struct fuzzer::@269 Flags
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Attribute unwrap(LLVMAttributeRef Attr)
static GCRegistry::Add< StatepointGC > D("statepoint-example","an example strategy for statepoint")
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.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
void takeName(Value *V)
Transfer the name from V to this value.
Class to represent pointers.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
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
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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...
CHAIN = SC CHAIN, Imm128 - System call.
alias_iterator alias_begin()
void setLinkage(LinkageTypes LT)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
const GlobalObject * getBaseObject() const
bool hasLinkOnceLinkage() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void setUnnamedAddr(UnnamedAddr Val)
size_type count(const ValueT &V) const
Return 1 if the specified key is in the set, 0 otherwise.
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).
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Rename collisions when linking (static functions).
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
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.
virtual void eraseFromParent()=0
This method unlinks 'this' from the containing module and deletes it.
StringSet - A wrapper for StringMap that provides set-like functionality.
virtual std::string message() const
Return the error message as a string.
StringRef - Represent a constant reference to a string, i.e.
bool linkInModule(std::unique_ptr< Module > Src, unsigned Flags=Flags::None, DenseSet< const GlobalValue * > *GlobalsToImport=nullptr)
Link Src into the composite.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B)
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
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.