62 : DstStructTypesSet(DstStructTypesSet) {}
67 void addTypeMapping(
Type *DstTy,
Type *SrcTy);
71 void linkDefinedTypeBodies();
81 return cast<FunctionType>(
get((
Type *)
T));
87 bool areTypesIsomorphic(
Type *DstTy,
Type *SrcTy);
91void TypeMapTy::addTypeMapping(
Type *DstTy,
Type *SrcTy) {
97 if (!areTypesIsomorphic(DstTy, SrcTy)) {
100 for (
Type *Ty : SpeculativeTypes)
101 MappedTypes.
erase(Ty);
103 SrcDefinitionsToResolve.
resize(SrcDefinitionsToResolve.
size() -
104 SpeculativeDstOpaqueTypes.
size());
105 for (
StructType *Ty : SpeculativeDstOpaqueTypes)
106 DstResolvedOpaqueTypes.
erase(Ty);
114 for (
Type *Ty : SpeculativeTypes)
115 if (
auto *STy = dyn_cast<StructType>(Ty))
119 SpeculativeTypes.clear();
120 SpeculativeDstOpaqueTypes.clear();
125bool TypeMapTy::areTypesIsomorphic(
Type *DstTy,
Type *SrcTy) {
131 Type *&Entry = MappedTypes[SrcTy];
133 return Entry == DstTy;
137 if (DstTy == SrcTy) {
145 if (
StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
147 if (SSTy->isOpaque()) {
149 SpeculativeTypes.push_back(SrcTy);
157 if (cast<StructType>(DstTy)->isOpaque()) {
159 if (!DstResolvedOpaqueTypes.
insert(cast<StructType>(DstTy)).second)
162 SpeculativeTypes.push_back(SrcTy);
163 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
174 if (isa<IntegerType>(DstTy))
176 if (
PointerType *PT = dyn_cast<PointerType>(DstTy)) {
177 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
179 }
else if (
FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
180 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
182 }
else if (
StructType *DSTy = dyn_cast<StructType>(DstTy)) {
184 if (DSTy->isLiteral() != SSTy->
isLiteral() ||
185 DSTy->isPacked() != SSTy->
isPacked())
187 }
else if (
auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
188 if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
190 }
else if (
auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
191 if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
198 SpeculativeTypes.push_back(SrcTy);
209void TypeMapTy::linkDefinedTypeBodies() {
211 for (
StructType *SrcSTy : SrcDefinitionsToResolve) {
212 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
216 Elements.resize(SrcSTy->getNumElements());
220 DstSTy->
setBody(Elements, SrcSTy->isPacked());
223 SrcDefinitionsToResolve.clear();
224 DstResolvedOpaqueTypes.
clear();
243 return get(Ty, Visited);
248 Type **Entry = &MappedTypes[Ty];
253 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
257 for (
auto &Pair : MappedTypes) {
258 assert(!(Pair.first != Ty && Pair.second == Ty) &&
259 "mapping to a source type");
263 if (!Visited.
insert(cast<StructType>(Ty)).second) {
279 bool AnyChange =
false;
287 Entry = &MappedTypes[Ty];
289 if (
auto *DTy = dyn_cast<StructType>(*Entry)) {
291 auto *STy = cast<StructType>(Ty);
292 finishType(DTy, STy, ElementTypes);
300 if (!AnyChange && IsUniqued)
308 return *Entry = ArrayType::get(ElementTypes[0],
309 cast<ArrayType>(Ty)->getNumElements());
312 return *Entry = VectorType::get(ElementTypes[0],
313 cast<VectorType>(Ty)->getElementCount());
315 return *Entry = PointerType::get(ElementTypes[0],
318 return *Entry = FunctionType::get(ElementTypes[0],
320 cast<FunctionType>(Ty)->isVarArg());
322 auto *STy = cast<StructType>(Ty);
336 return *Entry = OldT;
345 finishType(DTy, STy, ElementTypes);
367 IRLinker &TheIRLinker;
370 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
375 IRLinker &TheIRLinker;
378 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
389 std::unique_ptr<Module> SrcM;
395 GlobalValueMaterializer GValMaterializer;
396 LocalValueMaterializer LValMaterializer;
409 std::vector<GlobalValue *> Worklist;
410 std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
413 if (ValuesToLink.
insert(GV).second)
414 Worklist.push_back(GV);
422 bool IsPerformingImport;
427 bool DoneLinkingBodies =
false;
431 std::optional<Error> FoundError;
434 FoundError = std::move(
E);
445 unsigned IndirectSymbolMCID;
451 void emitWarning(
const Twine &Message) {
475 if (
auto *FDGV = dyn_cast<Function>(DGV))
476 if (FDGV->isIntrinsic())
477 if (
const auto *FSrcGV = dyn_cast<Function>(SrcGV))
478 if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
485 void computeTypeMapping();
497 bool ForIndirectSymbol);
499 Error linkModuleFlagsMetadata();
523 void flushRAUWWorklist();
528 void prepareCompileUnitsForImport();
529 void linkNamedMDNodes();
535 IRLinker(
Module &DstM, MDMapT &SharedMDs,
539 : DstM(DstM), SrcM(
std::
move(SrcM)), AddLazyFor(
std::
move(AddLazyFor)),
540 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
541 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
543 &TypeMap, &GValMaterializer),
544 IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
545 IndirectSymbolValueMap, &LValMaterializer)) {
549 if (IsPerformingImport)
550 prepareCompileUnitsForImport();
555 Value *materialize(
Value *V,
bool ForIndirectSymbol);
573 ConflictGV->setName(
Name);
574 assert(ConflictGV->getName() !=
Name &&
"forceRenaming didn't work");
580Value *GlobalValueMaterializer::materialize(
Value *SGV) {
581 return TheIRLinker.materialize(SGV,
false);
584Value *LocalValueMaterializer::materialize(
Value *SGV) {
585 return TheIRLinker.materialize(SGV,
true);
588Value *IRLinker::materialize(
Value *V,
bool ForIndirectSymbol) {
589 auto *SGV = dyn_cast<GlobalValue>(V);
597 if (SGV->getParent() != &DstM && SGV->getParent() != SrcM.get())
613 if (
auto *
F = dyn_cast<Function>(New)) {
614 if (!
F->isDeclaration())
616 }
else if (
auto *V = dyn_cast<GlobalVariable>(New)) {
617 if (V->hasInitializer() || V->hasAppendingLinkage())
619 }
else if (
auto *GA = dyn_cast<GlobalAlias>(New)) {
620 if (GA->getAliasee())
622 }
else if (
auto *GI = dyn_cast<GlobalIFunc>(New)) {
623 if (GI->getResolver())
638 (!ForIndirectSymbol && IndirectSymbolValueMap.
lookup(SGV) == New))
641 if (ForIndirectSymbol || shouldLink(New, *SGV))
642 setError(linkGlobalValueBody(*New, *SGV));
644 updateAttributes(*New);
666 for (
unsigned i = 0; i <
Attrs.getNumAttrSets(); ++i) {
667 for (
int AttrIdx = Attribute::FirstTypeAttr;
668 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
670 if (
Attrs.hasAttributeAtIndex(i, TypedAttr)) {
672 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
673 Attrs =
Attrs.replaceAttributeTypeAtIndex(
C, i, TypedAttr,
691 F->copyAttributesFrom(SF);
692 F->setAttributes(mapAttributeTypes(
F->getContext(),
F->getAttributes()));
703 if (
auto *GA = dyn_cast<GlobalAlias>(SGV)) {
707 DGA->copyAttributesFrom(GA);
711 if (
auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
714 SGV->
getName(),
nullptr, &DstM);
715 DGI->copyAttributesFrom(GI);
723 bool ForDefinition) {
725 if (
auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
726 NewGV = copyGlobalVariableProto(SGVar);
727 }
else if (
auto *SF = dyn_cast<Function>(SGV)) {
728 NewGV = copyFunctionProto(SF);
731 NewGV = copyIndirectSymbolProto(SGV);
751 if (
auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
754 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
760 if (
auto *NewF = dyn_cast<Function>(NewGV)) {
761 NewF->setPersonalityFn(
nullptr);
762 NewF->setPrefixData(
nullptr);
763 NewF->setPrologueData(
nullptr);
770 size_t DotPos =
Name.rfind(
'.');
772 !isdigit(
static_cast<unsigned char>(
Name[DotPos + 1])))
774 :
Name.substr(0, DotPos);
781void IRLinker::computeTypeMapping() {
795 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
820 std::vector<StructType *>
Types = SrcM->getIdentifiedStructTypes();
825 if (TypeMap.DstStructTypesSet.hasType(ST)) {
834 if (STTypePrefix.size() ==
ST->getName().size())
859 if (TypeMap.DstStructTypesSet.hasType(DST))
860 TypeMap.addTypeMapping(DST, ST);
865 TypeMap.linkDefinedTypeBodies();
870 unsigned NumElements = cast<ArrayType>(
C->getType())->getNumElements();
872 for (
unsigned i = 0; i != NumElements; ++i)
884 "Linking globals named '" + SrcGV->
getName() +
885 "': can only link appending global with another appending "
889 return stringErr(
"Appending variables linked with different const'ness!");
893 "Appending variables with different alignment need to be linked!");
897 "Appending variables with different visibility need to be linked!");
901 "Appending variables with different unnamed_addr need to be linked!");
905 "Appending variables with different section name need to be linked!");
908 return stringErr(
"Appending variables with different address spaces need "
924 bool IsNewStructor =
false;
925 bool IsOldStructor =
false;
926 if (
Name ==
"llvm.global_ctors" ||
Name ==
"llvm.global_dtors") {
927 if (cast<StructType>(EltTy)->getNumElements() == 3)
928 IsNewStructor =
true;
930 IsOldStructor =
true;
935 auto &
ST = *cast<StructType>(EltTy);
936 Type *Tys[3] = {
ST.getElementType(0),
ST.getElementType(1), VoidPtrTy};
943 DstNumElements = DstTy->getNumElements();
946 if (EltTy != DstTy->getElementType())
947 return stringErr(
"Appending variables with different element types!");
956 dyn_cast<GlobalValue>(
E->getAggregateElement(2)->stripPointerCasts());
960 return !shouldLink(DGV, *Key);
980 IsOldStructor, SrcElements);
985 RAUWWorklist.push_back(
1004 bool LazilyAdded =
false;
1006 AddLazyFor(SGV, [
this, &LazilyAdded](
GlobalValue &GV) {
1014 bool ForIndirectSymbol) {
1017 bool ShouldLink = shouldLink(DGV, *SGV);
1023 return cast<Constant>(
I->second);
1025 I = IndirectSymbolValueMap.
find(SGV);
1026 if (
I != IndirectSymbolValueMap.
end())
1027 return cast<Constant>(
I->second);
1030 if (!ShouldLink && ForIndirectSymbol)
1035 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1036 cast<GlobalVariable>(SGV));
1038 bool NeedsRenaming =
false;
1040 if (DGV && !ShouldLink) {
1046 if (DoneLinkingBodies)
1049 NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1050 if (ShouldLink || !ForIndirectSymbol)
1051 NeedsRenaming =
true;
1057 if (
Function *
F = dyn_cast<Function>(NewGV))
1061 NeedsRenaming =
false;
1067 if (ShouldLink || ForIndirectSymbol) {
1069 if (
auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1077 if (!ShouldLink && ForIndirectSymbol)
1086 if (DGV && NewGV != SGV) {
1088 NewGV, TypeMap.get(SGV->
getType()));
1091 if (DGV && NewGV != DGV) {
1095 RAUWWorklist.push_back(std::make_pair(
1114 assert(Dst.isDeclaration() && !Src.isDeclaration());
1117 if (
Error Err = Src.materialize())
1121 if (Src.hasPrefixData())
1122 Dst.setPrefixData(Src.getPrefixData());
1123 if (Src.hasPrologueData())
1124 Dst.setPrologueData(Src.getPrologueData());
1125 if (Src.hasPersonalityFn())
1126 Dst.setPersonalityFn(Src.getPersonalityFn());
1129 Dst.copyMetadata(&Src, 0);
1132 Dst.stealArgumentListFrom(Src);
1133 Dst.splice(Dst.end(), &Src);
1149 if (
auto *
F = dyn_cast<Function>(&Src))
1150 return linkFunctionBody(cast<Function>(Dst), *
F);
1151 if (
auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1152 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
1155 if (
auto *GA = dyn_cast<GlobalAlias>(&Src)) {
1156 linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
1159 linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
1163void IRLinker::flushRAUWWorklist() {
1164 for (
const auto &Elem : RAUWWorklist) {
1167 std::tie(Old, New) = Elem;
1172 RAUWWorklist.clear();
1175void IRLinker::prepareCompileUnitsForImport() {
1176 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata(
"llvm.dbg.cu");
1177 if (!SrcCompileUnits)
1183 auto *
CU = cast<DICompileUnit>(SrcCompileUnits->
getOperand(
I));
1184 assert(
CU &&
"Expected valid compile unit");
1188 CU->replaceEnumTypes(
nullptr);
1189 CU->replaceMacros(
nullptr);
1190 CU->replaceRetainedTypes(
nullptr);
1201 CU->replaceGlobalVariables(
nullptr);
1216 bool ReplaceImportedEntities =
false;
1217 for (
auto *IE :
CU->getImportedEntities()) {
1219 assert(Scope &&
"Invalid Scope encoding!");
1220 if (isa<DILocalScope>(Scope))
1223 ReplaceImportedEntities =
true;
1225 if (ReplaceImportedEntities) {
1226 if (!AllImportedModules.
empty())
1230 AllImportedModules.
end())));
1234 CU->replaceImportedEntities(
nullptr);
1240void IRLinker::linkNamedMDNodes() {
1241 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1242 for (
const NamedMDNode &NMD : SrcM->named_metadata()) {
1244 if (&NMD == SrcModFlags)
1250 emitWarning(
"Pseudo-probe ignored: source module '" +
1251 SrcM->getModuleIdentifier() +
1252 "' is compiled with -fpseudo-probe-for-profiling while "
1253 "destination module '" +
1259 if (IsPerformingImport && NMD.getName() ==
"llvm.stats")
1270Error IRLinker::linkModuleFlagsMetadata() {
1272 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1297 mdconst::extract<ConstantInt>(
Op->getOperand(0))->getZExtValue();
1301 Requirements.
insert(cast<MDNode>(
Op->getOperand(2)));
1314 mdconst::extract<ConstantInt>(
SrcOp->getOperand(0));
1319 unsigned SrcBehaviorValue = SrcBehavior->
getZExtValue();
1326 if (Requirements.
insert(cast<MDNode>(
SrcOp->getOperand(2)))) {
1345 mdconst::extract<ConstantInt>(
DstOp->getOperand(0));
1346 unsigned DstBehaviorValue = DstBehavior->
getZExtValue();
1348 auto overrideDstValue = [&]() {
1357 SrcOp->getOperand(2) !=
DstOp->getOperand(2))
1358 return stringErr(
"linking module flags '" +
ID->getString() +
1359 "': IDs have conflicting override values in '" +
1360 SrcM->getModuleIdentifier() +
"' and '" +
1370 if (SrcBehaviorValue != DstBehaviorValue) {
1371 bool MinAndWarn = (SrcBehaviorValue ==
Module::Min &&
1375 bool MaxAndWarn = (SrcBehaviorValue ==
Module::Max &&
1379 if (!(MaxAndWarn || MinAndWarn))
1380 return stringErr(
"linking module flags '" +
ID->getString() +
1381 "': IDs have conflicting behaviors in '" +
1382 SrcM->getModuleIdentifier() +
"' and '" +
1386 auto ensureDistinctOp = [&](
MDNode *DstValue) {
1387 assert(isa<MDTuple>(DstValue) &&
1388 "Expected MDTuple when appending module flags");
1389 if (DstValue->isDistinct())
1390 return dyn_cast<MDTuple>(DstValue);
1406 SrcOp->getOperand(2) !=
DstOp->getOperand(2)) {
1409 <<
"linking module flags '" <<
ID->getString()
1410 <<
"': IDs have conflicting values ('" << *
SrcOp->getOperand(2)
1411 <<
"' from " << SrcM->getModuleIdentifier() <<
" with '"
1420 mdconst::extract<ConstantInt>(
DstOp->getOperand(2));
1422 mdconst::extract<ConstantInt>(
SrcOp->getOperand(2));
1439 mdconst::extract<ConstantInt>(
DstOp->getOperand(2));
1441 mdconst::extract<ConstantInt>(
SrcOp->getOperand(2));
1456 switch (SrcBehaviorValue) {
1462 if (
SrcOp->getOperand(2) !=
DstOp->getOperand(2))
1463 return stringErr(
"linking module flags '" +
ID->getString() +
1464 "': IDs have conflicting values in '" +
1465 SrcM->getModuleIdentifier() +
"' and '" +
1476 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(
DstOp->getOperand(2)));
1477 MDNode *SrcValue = cast<MDNode>(
SrcOp->getOperand(2));
1478 for (
const auto &O : SrcValue->
operands())
1484 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(
DstOp->getOperand(2)));
1485 MDNode *SrcValue = cast<MDNode>(
SrcOp->getOperand(2));
1498 for (
auto Idx : Mins) {
1502 ConstantInt *V = mdconst::extract<ConstantInt>(
Op->getOperand(2));
1504 Op->getOperand(0),
ID,
1511 for (
unsigned I = 0,
E = Requirements.
size();
I !=
E; ++
I) {
1517 if (!Op ||
Op->getOperand(2) != ReqValue)
1518 return stringErr(
"linking module flags '" +
Flag->getString() +
1519 "': does not have the required value");
1530 return ".text\n.balign 2\n.thumb\n" +
InlineAsm;
1532 return ".text\n.balign 4\n.arm\n" +
InlineAsm;
1551 if (
auto *
F = dyn_cast<Function>(&GV)) {
1552 if (!
F->isIntrinsic())
1553 F->removeFnAttr(llvm::Attribute::NoCallback);
1558 if (
CallBase *CI = dyn_cast<CallBase>(&
I))
1559 CI->removeFnAttr(Attribute::NoCallback);
1563Error IRLinker::run() {
1565 if (SrcM->getMaterializer())
1566 if (
Error Err = SrcM->getMaterializer()->materializeMetadata())
1575 if (DstM.
getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1585 bool EnableDLWarning =
true;
1586 bool EnableTripleWarning =
true;
1587 if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
1588 std::string ModuleId = SrcM->getModuleIdentifier();
1590 bool SrcIsLibDevice =
1592 bool SrcHasLibDeviceDL =
1593 (SrcM->getDataLayoutStr().empty() ||
1594 SrcM->getDataLayoutStr() ==
"e-i64:64-v16:16-v32:32-n16:32:64");
1598 bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() ==
Triple::NVIDIA &&
1599 SrcTriple.getOSName() ==
"gpulibs") ||
1600 (SrcTriple.getVendorName() ==
"unknown" &&
1601 SrcTriple.getOSName() ==
"unknown");
1602 EnableTripleWarning = !(SrcIsLibDevice && SrcHasLibDeviceTriple);
1603 EnableDLWarning = !(SrcIsLibDevice && SrcHasLibDeviceDL);
1606 if (EnableDLWarning && (SrcM->getDataLayout() != DstM.
getDataLayout())) {
1607 emitWarning(
"Linking two modules of different data layouts: '" +
1608 SrcM->getModuleIdentifier() +
"' is '" +
1609 SrcM->getDataLayoutStr() +
"' whereas '" +
1614 if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
1615 !SrcTriple.isCompatibleWith(DstTriple))
1616 emitWarning(
"Linking two modules of different target triples: '" +
1617 SrcM->getModuleIdentifier() +
"' is '" +
1618 SrcM->getTargetTriple() +
"' whereas '" +
1625 computeTypeMapping();
1627 std::reverse(Worklist.begin(), Worklist.end());
1628 while (!Worklist.empty()) {
1630 Worklist.pop_back();
1634 IndirectSymbolValueMap.
find(GV) != IndirectSymbolValueMap.
end())
1640 return std::move(*FoundError);
1641 flushRAUWWorklist();
1646 DoneLinkingBodies =
true;
1654 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1658 }
else if (IsPerformingImport) {
1663 SmallString<256> S(
".symver ");
1667 DstM.appendModuleInlineAsm(S);
1682 Globals.
splice(Globals.end(), Globals, NewGV->getIterator());
1687 return linkModuleFlagsMetadata();
1691 : ETypes(
E), IsPacked(
P) {}
1694 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1704StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1708StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1712unsigned IRMover::StructTypeKeyInfo::getHashValue(
const KeyTy &Key) {
1717unsigned IRMover::StructTypeKeyInfo::getHashValue(
const StructType *ST) {
1718 return getHashValue(KeyTy(ST));
1721bool IRMover::StructTypeKeyInfo::isEqual(
const KeyTy &LHS,
1723 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1725 return LHS == KeyTy(RHS);
1728bool IRMover::StructTypeKeyInfo::isEqual(
const StructType *LHS,
1730 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1732 return KeyTy(LHS) == KeyTy(RHS);
1737 NonOpaqueStructTypes.insert(Ty);
1742 NonOpaqueStructTypes.insert(Ty);
1743 bool Removed = OpaqueStructTypes.erase(Ty);
1750 OpaqueStructTypes.insert(Ty);
1757 auto I = NonOpaqueStructTypes.find_as(Key);
1758 return I == NonOpaqueStructTypes.end() ? nullptr : *
I;
1763 return OpaqueStructTypes.count(Ty);
1764 auto I = NonOpaqueStructTypes.find(Ty);
1765 return I == NonOpaqueStructTypes.end() ?
false : *
I == Ty;
1770 StructTypes.
run(M,
false);
1781 SharedMDs[MD].reset(
const_cast<MDNode *
>(MD));
1788 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1789 std::move(Src), ValuesToLink, std::move(AddLazyFor),
1790 IsPerformingImport);
1791 Error E = TheIRLinker.run();
This header is deprecated in favour of llvm/TargetParser/Triple.h.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static void forceRenaming(GlobalValue *GV, StringRef Name)
The LLVM SymbolTable class autorenames globals that conflict in the symbol table.
static void getArrayElements(const Constant *C, SmallVectorImpl< Constant * > &Dest)
static std::string adjustInlineAsm(const std::string &InlineAsm, const Triple &Triple)
Return InlineAsm adjusted with target-specific directives if required.
static StringRef getTypeNamePrefix(StringRef Name)
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.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
LLVM Basic Block Representation.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setSelectionKind(SelectionKind Val)
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This is an important base class in LLVM.
Base class for scope-like contexts.
bool isDefault() const
Test if the DataLayout was constructed from an empty string.
bool erase(const KeyT &Val)
Implements a dense probed hash-table based set.
This is the base abstract class for diagnostic reporting in the backend.
Interface for custom diagnostic printing.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
StringRef getSection() const
Get the custom section of this global if it has one.
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
VisibilityTypes getVisibility() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
const Comdat * getComdat() const
bool hasExternalWeakLinkage() const
ThreadLocalMode getThreadLocalMode() const
void setLinkage(LinkageTypes LT)
bool isDeclarationForLinker() const
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
PointerType * getType() const
Global values are always pointers.
bool hasGlobalUnnamedAddr() const
bool hasAppendingLinkage() const
@ InternalLinkage
Rename collisions when linking (static functions).
@ ExternalLinkage
Externally visible function.
@ ExternalWeakLinkage
ExternalWeak linkage description.
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void addNonOpaque(StructType *Ty)
bool hasType(StructType *Ty)
void switchToNonOpaque(StructType *Ty)
void addOpaque(StructType *Ty)
StructType * findNonOpaque(ArrayRef< Type * > ETypes, bool IsPacked)
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
This is an important class for using LLVM in a threaded context.
LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg)
void print(DiagnosticPrinter &DP) const override
Print using the given DP a user-friendly message.
ArrayRef< MDOperand > operands() const
op_iterator op_end() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
op_iterator op_begin() const
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
A Module instance is used to store all the information related to an LLVM module.
@ AppendUnique
Appends the two values, which are required to be metadata nodes.
@ Override
Uses the specified value, regardless of the behavior or value of the other module.
@ Warning
Emits a warning if two values disagree.
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
@ Min
Takes the min of the two values, which are required to be integers.
@ Append
Appends the two values, which are required to be metadata nodes.
@ Max
Takes the max of the two values, which are required to be integers.
@ Require
Adds a requirement that another module flag be present and have a specified value after linking is pe...
LLVMContext & getContext() const
Get the global data context.
void dropTriviallyDeadConstantArrays()
Destroy ConstantArrays in LLVMContext if they are not used.
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
NamedMDNode * getOrInsertModuleFlagsMetadata()
Returns the NamedMDNode in the module that represents module-level flags.
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
void setDataLayout(StringRef Desc)
Set the data layout.
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
const std::string & getDataLayoutStr() const
Get the data layout string for the module's target platform.
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
void setTargetTriple(StringRef T)
Set the target triple.
void setOperand(unsigned I, MDNode *New)
MDNode * getOperand(unsigned i) const
unsigned getNumOperands() const
void addOperand(MDNode *M)
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.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
bool startswith(StringRef Prefix) const
bool endswith(StringRef Suffix) const
static constexpr size_t npos
Class to represent struct types.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
static StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
bool hasName() const
Return true if this is a named struct that has a non-empty name.
bool isLiteral() const
Return true if this type is uniqued by structural equivalence, false if it is a struct definition.
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
StringRef getName() const
Return the name for this struct type if it has an identity.
Triple - Helper class for working with autoconf configuration names.
ArchType getArch() const
Get the parsed architecture type of this triple.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
DenseSet< const MDNode * > & getVisitedMetadata()
void run(const Module &M, bool onlyNamed)
The instances of the Type class are immutable: once they are created, they are never changed.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
@ ScalableVectorTyID
Scalable SIMD vector type.
@ FixedVectorTyID
Fixed width SIMD vector type.
unsigned getNumContainedTypes() const
Return the number of types in the derived type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static IntegerType * getInt8Ty(LLVMContext &C)
bool isFunctionTy() const
True if this is an instance of FunctionType.
TypeID getTypeID() const
Return the type id for the type.
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
virtual Type * remapType(Type *SrcTy)=0
The client should implement this method if they want to remap types while mapping values.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
std::optional< MDMapT > & getMDMap()
iterator find(const KeyT &Val)
Context for (re-)mapping values (and metadata).
MDNode * mapMDNode(const MDNode &N)
void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver, unsigned MappingContextID=0)
void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
Value * mapValue(const Value &V)
void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
This is a class that can be implemented by clients to materialize Values on demand.
LLVM Value Representation.
void setName(const Twine &Name)
Change the name of the value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
LLVMContext & getContext() const
All values hold a context through their type.
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)
bool erase(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.
void splice(iterator where, iplist_impl &L2)
A raw_ostream that writes to an std::string.
unique_function is a type-erasing functor similar to std::function.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
AddressSpace getAddressSpace(T *V)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
std::optional< Function * > remangleIntrinsicFunction(Function *F)
Flag
These should be considered private to the implementation of the MCInstrDesc class.
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
@ RF_NullMapMissingGlobalValues
Any global values not in value map are mapped to null instead of mapping to self.
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
constexpr const char * PseudoProbeDescMetadataName
An information struct used to provide DenseMap with the various necessary components for a given valu...
KeyTy(ArrayRef< Type * > E, bool P)
bool operator==(const KeyTy &that) const
ArrayRef< Type * > ETypes
bool operator!=(const KeyTy &that) const