96#include <system_error>
103#define DEBUG_TYPE "lowertypetests"
106STATISTIC(ByteArraySizeBytes,
"Byte array size in bytes");
107STATISTIC(NumByteArraysCreated,
"Number of byte arrays created");
108STATISTIC(NumTypeTestCallsLowered,
"Number of type test calls lowered");
109STATISTIC(NumTypeIdDisjointSets,
"Number of disjoint sets of type identifiers");
135 for (uint64_t
B :
Bits)
178 assert(Fragments.front().empty() &&
"Cannot add fragments after build()");
181 Fragments.emplace_back();
182 std::vector<uint64_t> &
Fragment = Fragments.back();
183 uint64_t FragmentIndex = Fragments.size() - 1;
185 std::vector<std::vector<uint64_t>> SubFragments;
186 for (
auto ObjIndex :
F) {
187 uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
188 if (OldFragmentIndex == 0) {
191 SubFragments.push_back({ObjIndex});
192 }
else if (!Fragments[OldFragmentIndex].empty()) {
198 SubFragments.push_back(std::move(Fragments[OldFragmentIndex]));
204 const std::vector<uint64_t> &
B) {
205 return Less(
A.back(),
B.back());
209 for (
auto &SF : SubFragments)
214 FragmentMap[ObjIndex] = FragmentIndex;
223 [](
const std::vector<uint64_t> &
F) {
return F.empty(); });
225 const std::vector<uint64_t> &FB) {
226 return Less(FA.back(), FB.back());
230 std::vector<uint64_t> Layout;
231 Layout.reserve(FragmentMap.size());
232 for (
auto &&
F : Fragments)
235 Fragments.push_back(std::move(Layout));
236 return Fragments.front();
240 uint64_t BitSize, uint64_t &AllocByteOffset,
251 unsigned ReqSize = AllocByteOffset + BitSize;
253 if (
Bytes.size() < ReqSize)
254 Bytes.resize(ReqSize);
257 AllocMask = 1 << Bit;
258 for (uint64_t
B : Bits)
259 Bytes[AllocByteOffset +
B] |= AllocMask;
263 if (
F->isDeclarationForLinker())
266 F->getParent()->getModuleFlag(
"CFI Canonical Jump Tables"));
267 if (!CI || !CI->isZero())
269 return F->hasFnAttribute(
"cfi-canonical-jump-table");
276 if (AssocGO->hasMetadata(LLVMContext::MD_type))
286 for (
auto &
A : M.aliases())
303 if (
C->getBitWidth() != 64)
314 GO.getMetadata(LLVMContext::MD_type, Types);
317 TypeIds.
insert(TypeId->getZExtValue());
320 if (
NamedMDNode *CfiFunctionsMD = M.getNamedMetadata(
"cfi.functions")) {
321 for (
auto *Func : CfiFunctionsMD->operands()) {
322 assert(Func->getNumOperands() >= 3);
324 for (
unsigned I = 3;
I < Func->getNumOperands(); ++
I)
327 TypeIds.
insert(TypeId->getZExtValue());
336enum class CfiFunctionLinkage :
uint8_t {
343class CfiFunctionHotness {
356 CfiFunctionHotness() =
default;
365 static CfiFunctionHotness
366 fromFunction(
Function &
F, ProfileSummaryInfo &PSI,
367 function_ref<
const BlockFrequencyInfo &(
Function &)> BFIGetter) {
368 if (
F.isDeclaration())
369 return Kind::Unknown;
372 const BlockFrequencyInfo &BFI = BFIGetter(
F);
373 if (
F.hasFnAttribute(Attribute::Hot) ||
379 F.hasFnAttribute(Attribute::Cold)) {
388 static CfiFunctionHotness fromUint6(uint8_t
V) {
389 return CfiFunctionHotness(
static_cast<Kind>(
V & 0x3));
392 uint8_t asUint6()
const {
return static_cast<uint8_t
>(
Type) & 0x3; }
399 auto Rank = [](
Kind K) ->
int {
400 return (K == Kind::Cold) ? -1 :
static_cast<int>(
K);
409 return static_cast<CfiFunctionLinkage
>(Encoded & 0x3);
413 return CfiFunctionHotness::fromUint6(Encoded >> 2);
417 CfiFunctionHotness Hotness) {
432 for (
auto *
V : CfiFunctions) {
435 F.getMetadata(LLVMContext::MD_type, Types);
439 CfiFunctionLinkage
Linkage = CfiFunctionLinkage::Declaration;
441 Linkage = CfiFunctionLinkage::Definition;
442 else if (
F.hasExternalWeakLinkage())
443 Linkage = CfiFunctionLinkage::WeakDeclaration;
445 CfiFunctionHotness Hotness =
446 Opts.reorder_cfi_jump_tables_profiles
447 ? CfiFunctionHotness::fromFunction(
F, PSI, BFIGetter)
448 : CfiFunctionHotness();
461 if (!CfiFunctionMDs.
empty()) {
463 for (
auto *MD : CfiFunctionMDs)
471 for (
const auto &
A : SrcM.
aliases()) {
476 FunctionAliases[
F].push_back(&
A);
479 if (!FunctionAliases.
empty()) {
481 for (
auto &Alias : FunctionAliases) {
484 for (
auto *
A : Alias.second)
497 if (!
F ||
F->use_empty())
504 if (!Symvers.
empty()) {
506 for (
auto *MD : Symvers)
522struct ByteArrayInfo {
523 std::set<uint64_t> Bits;
535class GlobalTypeMember final :
TrailingObjects<GlobalTypeMember, MDNode *> {
546 bool IsJumpTableCanonical;
554 bool IsJumpTableCanonical,
bool IsExported,
556 auto *GTM =
static_cast<GlobalTypeMember *
>(Alloc.Allocate(
557 totalSizeToAlloc<MDNode *>(Types.size()),
alignof(GlobalTypeMember)));
559 GTM->NTypes = Types.size();
560 GTM->IsJumpTableCanonical = IsJumpTableCanonical;
561 GTM->IsExported = IsExported;
566 GlobalObject *getGlobal()
const {
571 return IsJumpTableCanonical;
574 bool isExported()
const {
581struct ICallBranchFunnel final
582 : TrailingObjects<ICallBranchFunnel, GlobalTypeMember *> {
586 auto *
Call =
static_cast<ICallBranchFunnel *
>(
587 Alloc.Allocate(totalSizeToAlloc<GlobalTypeMember *>(Targets.
size()),
588 alignof(ICallBranchFunnel)));
590 Call->UniqueId = UniqueId;
598 return getTrailingObjects(NTargets);
607struct ScopedSaveAliaseesAndUsed {
610 std::vector<std::pair<GlobalAlias *, Function *>> FunctionAliases;
611 std::vector<std::pair<GlobalIFunc *, Function *>> ResolverIFuncs;
616 void collectAndEraseUsedFunctions(
Module &M,
617 SmallVectorImpl<GlobalValue *> &Vec,
625 GV->eraseFromParent();
627 std::stable_partition(Vec.
begin(), Vec.
end(), [](GlobalValue *GV) {
628 return isa<Function>(GV);
637 ScopedSaveAliaseesAndUsed(
Module &M) :
M(
M) {
650 collectAndEraseUsedFunctions(M, Used,
false);
651 collectAndEraseUsedFunctions(M, CompilerUsed,
true);
653 for (
auto &GA :
M.aliases()) {
657 FunctionAliases.push_back({&GA,
F});
660 for (
auto &GI :
M.ifuncs())
662 ResolverIFuncs.push_back({&GI,
F});
665 ~ScopedSaveAliaseesAndUsed() {
669 for (
auto P : FunctionAliases)
670 P.first->setAliasee(
P.second);
672 for (
auto P : ResolverIFuncs) {
676 P.first->setResolver(
P.second);
681class LowerTypeTestsModule {
682 const IPOOptions &Opts;
685 ModuleSummaryIndex *ExportSummary;
686 const ModuleSummaryIndex *ImportSummary;
694 bool CanUseArmJumpTable =
false, CanUseThumbBWJumpTable =
false;
697 int HasBranchTargetEnforcement = -1;
700 DenseMap<const Function *, CfiFunctionHotness> FunctionSummaryHotness;
702 IntegerType *Int1Ty = Type::getInt1Ty(
M.getContext());
703 IntegerType *Int8Ty = Type::getInt8Ty(
M.getContext());
704 PointerType *PtrTy = PointerType::getUnqual(
M.getContext());
705 ArrayType *Int8Arr0Ty = ArrayType::get(Type::getInt8Ty(
M.getContext()), 0);
706 IntegerType *Int32Ty = Type::getInt32Ty(
M.getContext());
707 IntegerType *Int64Ty = Type::getInt64Ty(
M.getContext());
708 IntegerType *
IntPtrTy =
M.getDataLayout().getIntPtrType(
M.getContext(), 0);
716 struct TypeIdUserInfo {
717 std::vector<CallInst *> CallSites;
718 bool IsExported =
false;
720 DenseMap<Metadata *, TypeIdUserInfo> TypeIdUsers;
726 struct TypeIdLowering {
751 std::vector<ByteArrayInfo> ByteArrayInfos;
753 Function *WeakInitializerFn =
nullptr;
755 GlobalVariable *GlobalAnnotation;
756 DenseSet<Value *> FunctionAnnotations;
760 bool CrossDsoCfi =
M.getModuleFlag(
"Cross-DSO CFI") !=
nullptr;
762 std::optional<DIBuilder> JumpTableDIB;
763 DICompileUnit *JumpTableCU =
nullptr;
764 DIFile *JumpTableFile =
nullptr;
765 DISubroutineType *JumpTableFnTy =
nullptr;
767 bool shouldExportConstantsAsAbsoluteSymbols();
768 uint8_t *exportTypeId(StringRef TypeId,
const TypeIdLowering &TIL);
769 TypeIdLowering importTypeId(StringRef TypeId);
770 void importTypeTest(CallInst *CI);
773 ByteArrayInfo *createByteArray(
const BitSetInfo &BSI);
774 void allocateByteArrays();
777 void lowerTypeTestCalls(
779 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
781 const TypeIdLowering &TIL);
787 bool hasBranchTargetEnforcement();
790 void verifyTypeMDNode(GlobalObject *GO, MDNode *
Type);
802 void replaceWeakDeclarationWithJumpTablePtr(
Function *
F, Constant *JT,
803 bool IsJumpTableCanonical);
804 void moveInitializerToModuleConstructor(GlobalVariable *GV);
805 void findGlobalVariableUsersOf(Constant *
C,
806 SmallSetVector<GlobalVariable *, 8> &Out);
817 void replaceCfiUses(
Function *Old,
Value *New,
bool IsJumpTableCanonical);
821 void replaceDirectCalls(
Value *Old,
Value *New);
823 bool isFunctionAnnotation(
Value *
V)
const {
827 void maybeReplaceComdat(
Function *
F, StringRef OriginalName);
831 ModuleSummaryIndex *ExportSummary,
832 const ModuleSummaryIndex *ImportSummary);
833 ~LowerTypeTestsModule() {
835 JumpTableDIB->finalize();
858 unsigned BitWidth = BitsType->getBitWidth();
860 BitOffset =
B.CreateZExtOrTrunc(BitOffset, BitsType);
862 B.CreateAnd(BitOffset, ConstantInt::get(BitsType,
BitWidth - 1));
863 Value *BitMask =
B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
864 Value *MaskedBits =
B.CreateAnd(Bits, BitMask);
865 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
868ByteArrayInfo *LowerTypeTestsModule::createByteArray(
const BitSetInfo &BSI) {
872 auto ByteArrayGlobal =
new GlobalVariable(
874 auto MaskGlobal =
new GlobalVariable(M, Int8Ty,
true,
877 ByteArrayInfos.emplace_back();
878 ByteArrayInfo *BAI = &ByteArrayInfos.back();
880 BAI->Bits = BSI.
Bits;
882 BAI->ByteArray = ByteArrayGlobal;
883 BAI->MaskGlobal = MaskGlobal;
887void LowerTypeTestsModule::allocateByteArrays() {
889 [](
const ByteArrayInfo &BAI1,
const ByteArrayInfo &BAI2) {
890 return BAI1.BitSize > BAI2.BitSize;
893 std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
896 for (
unsigned I = 0;
I != ByteArrayInfos.size(); ++
I) {
897 ByteArrayInfo *BAI = &ByteArrayInfos[
I];
900 BAB.
allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[
I], Mask);
906 *BAI->MaskPtr =
Mask;
911 new GlobalVariable(M, ByteArrayConst->
getType(),
true,
914 for (
unsigned I = 0;
I != ByteArrayInfos.size(); ++
I) {
915 ByteArrayInfo *BAI = &ByteArrayInfos[
I];
917 ByteArray, ConstantInt::get(
IntPtrTy, ByteArrayOffsets[
I]));
931 ByteArraySizeBytes = BAB.
Bytes.size();
937 const TypeIdLowering &TIL,
945 if (Opts.lowertypetests_avoid_reuse && !ImportSummary) {
951 "bits_use", ByteArray, &M);
954 Value *ByteAddr =
B.CreateGEP(Int8Ty, ByteArray, BitOffset);
959 return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
967 GV->getMetadata(LLVMContext::MD_type, Types);
969 if (
Type->getOperand(1) != TypeId)
982 APInt APOffset(
DL.getIndexSizeInBits(0), 0);
983 bool Result =
GEP->accumulateConstantOffset(
DL, APOffset);
991 if (
Op->getOpcode() == Instruction::BitCast)
994 if (
Op->getOpcode() == Instruction::Select)
1004Value *LowerTypeTestsModule::lowerTypeTestCall(
Metadata *TypeId, CallInst *CI,
1005 const TypeIdLowering &TIL) {
1013 const DataLayout &
DL =
M.getDataLayout();
1026 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
1032 Value *PtrOffset =
B.CreateSub(OffsetedGlobalAsInt, PtrAsInt);
1043 {PtrOffset, PtrOffset, TIL.AlignLog2});
1045 Value *OffsetInRange =
B.CreateICmpULE(BitOffset, TIL.SizeM1);
1049 return OffsetInRange;
1062 Br->getMetadata(LLVMContext::MD_prof));
1066 for (
auto &Phi :
Else->phis())
1067 Phi.addIncoming(
Phi.getIncomingValueForBlock(Then), InitialBB);
1070 return createBitSetTest(ThenB, TIL, BitOffset);
1073 MDBuilder MDB(
M.getContext());
1075 OffsetInRange, CI,
false,
1077 : MDB.createLikelyBranchWeights()));
1081 Value *
Bit = createBitSetTest(ThenB, TIL, BitOffset);
1086 B.SetInsertPoint(CI);
1087 PHINode *
P =
B.CreatePHI(Int1Ty, 2);
1088 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
1089 P->addIncoming(Bit, ThenB.GetInsertBlock());
1095void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
1102 std::vector<Constant *> GlobalInits;
1103 const DataLayout &
DL =
M.getDataLayout();
1104 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
1108 for (GlobalTypeMember *
G : Globals) {
1111 DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType());
1112 MaxAlign = std::max(MaxAlign, Alignment);
1114 GlobalLayout[
G] = GVOffset;
1115 if (GVOffset != 0) {
1117 GlobalInits.push_back(
1121 GlobalInits.push_back(GV->getInitializer());
1123 CurOffset = GVOffset + InitSize;
1126 DesiredPadding =
NextPowerOf2(InitSize - 1) - InitSize;
1132 if (DesiredPadding > 32)
1133 DesiredPadding =
alignTo(InitSize, 32) - InitSize;
1137 auto *CombinedGlobal =
1138 new GlobalVariable(M, NewInit->
getType(),
true,
1140 CombinedGlobal->setAlignment(MaxAlign);
1143 lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
1148 for (
unsigned I = 0;
I != Globals.size(); ++
I) {
1152 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
1153 ConstantInt::get(Int32Ty,
I * 2)};
1155 DL, NewInit->
getType(), CombinedGlobal, CombinedGlobalIdxs,
1158 GlobalAlias *GAlias =
1160 "", CombinedGlobalElemPtr, &M);
1168bool LowerTypeTestsModule::shouldExportConstantsAsAbsoluteSymbols() {
1181uint8_t *LowerTypeTestsModule::exportTypeId(StringRef TypeId,
1182 const TypeIdLowering &TIL) {
1183 TypeTestResolution &TTRes =
1190 "__typeid_" + TypeId +
"_" + Name,
C, &M);
1195 if (shouldExportConstantsAsAbsoluteSymbols())
1202 ExportGlobal(
"global_addr", TIL.OffsetedGlobal);
1207 ExportConstant(
"align", TTRes.
AlignLog2, TIL.AlignLog2);
1208 ExportConstant(
"size_m1", TTRes.
SizeM1, TIL.SizeM1);
1218 ExportGlobal(
"byte_array", TIL.TheByteArray);
1219 if (shouldExportConstantsAsAbsoluteSymbols())
1220 ExportGlobal(
"bit_mask", TIL.BitMask);
1226 ExportConstant(
"inline_bits", TTRes.
InlineBits, TIL.InlineBits);
1231LowerTypeTestsModule::TypeIdLowering
1232LowerTypeTestsModule::importTypeId(StringRef TypeId) {
1236 const TypeTestResolution &TTRes = TidSummary->
TTRes;
1241 auto ImportGlobal = [&](StringRef
Name) {
1244 GlobalVariable *GV =
M.getOrInsertGlobal(
1245 (
"__typeid_" + TypeId +
"_" + Name).str(), Int8Arr0Ty);
1252 if (!shouldExportConstantsAsAbsoluteSymbols()) {
1264 if (GV->
getMetadata(LLVMContext::MD_absolute_symbol))
1273 if (AbsWidth ==
IntPtrTy->getBitWidth()) {
1277 SetAbsRange(0, 1ull << AbsWidth);
1283 auto *GV = ImportGlobal(
"global_addr");
1296 TIL.OffsetedGlobal = GV;
1308 TIL.TheByteArray = ImportGlobal(
"byte_array");
1309 TIL.BitMask = ImportConstant(
"bit_mask", TTRes.
BitMask, 8, PtrTy);
1313 TIL.InlineBits = ImportConstant(
1320void LowerTypeTestsModule::importTypeTest(CallInst *CI) {
1332 TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
1333 Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
1340void LowerTypeTestsModule::maybeReplaceComdat(
Function *
F,
1341 StringRef OriginalName) {
1347 F->getComdat()->getName() == OriginalName) {
1348 Comdat *OldComdat =
F->getComdat();
1349 Comdat *NewComdat =
M.getOrInsertComdat(
F->getName());
1350 for (GlobalObject &GO :
M.global_objects()) {
1359void LowerTypeTestsModule::importFunction(
Function *
F,
1361 assert(
F->getType()->getAddressSpace() == 0);
1364 std::string
Name = std::string(
F->getName());
1369 if (!
F->isDSOLocal())
1371 if (
F->isDeclaration()) {
1376 F->getAddressSpace(),
1379 replaceDirectCalls(
F, RealF);
1396 F->getAddressSpace(), Name +
".cfi_jt", &M);
1399 F->setName(Name +
".cfi");
1400 maybeReplaceComdat(
F, Name);
1402 F->getAddressSpace(), Name, &M);
1410 for (
auto &U :
F->uses()) {
1419 std::string AliasName =
A->getName().str() +
".cfi";
1422 F->getAddressSpace(),
"", &M);
1424 A->replaceAllUsesWith(AliasDecl);
1425 A->setName(AliasName);
1431 if (
F->hasExternalWeakLinkage())
1438 F->setVisibility(Visibility);
1447 OffsetsByTypeID[TypeId];
1448 for (
const auto &[Mem, MemOff] : GlobalLayout) {
1450 auto It = OffsetsByTypeID.
find(
Type->getOperand(1));
1451 if (It == OffsetsByTypeID.
end())
1457 It->second.push_back(MemOff +
Offset);
1467 dbgs() << MDS->getString() <<
": ";
1469 dbgs() <<
"<unnamed>: ";
1470 BitSets.
back().second.print(
dbgs());
1477void LowerTypeTestsModule::lowerTypeTestCalls(
1479 const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
1481 for (
const auto &[TypeId, BSI] :
buildBitSets(TypeIds, GlobalLayout)) {
1482 ByteArrayInfo *BAI =
nullptr;
1488 CombinedGlobalAddr, ConstantInt::get(
IntPtrTy, GlobalOffset)),
1493 : TypeTestResolution::
AllOnes;
1497 for (
auto Bit : BSI.
Bits)
1499 if (InlineBits == 0)
1502 TIL.InlineBits = ConstantInt::get(
1503 (BSI.
BitSize <= 32) ? Int32Ty : Int64Ty, InlineBits);
1506 ++NumByteArraysCreated;
1507 BAI = createByteArray(BSI);
1508 TIL.TheByteArray = BAI->ByteArray;
1509 TIL.BitMask = BAI->MaskGlobal;
1512 TypeIdUserInfo &TIUI = TypeIdUsers[TypeId];
1514 if (TIUI.IsExported) {
1515 uint8_t *MaskPtr = exportTypeId(
cast<MDString>(TypeId)->getString(), TIL);
1517 BAI->MaskPtr = MaskPtr;
1521 for (CallInst *CI : TIUI.CallSites) {
1522 ++NumTypeTestCallsLowered;
1523 Value *Lowered = lowerTypeTestCall(TypeId, CI, TIL);
1532void LowerTypeTestsModule::verifyTypeMDNode(GlobalObject *GO, MDNode *
Type) {
1533 if (
Type->getNumOperands() != 2)
1540 "A member of a type identifier may not have an explicit section");
1563bool LowerTypeTestsModule::hasBranchTargetEnforcement() {
1564 if (HasBranchTargetEnforcement == -1) {
1568 M.getModuleFlag(
"branch-target-enforcement")))
1569 HasBranchTargetEnforcement = !BTE->isZero();
1571 HasBranchTargetEnforcement = 0;
1573 return HasBranchTargetEnforcement;
1577LowerTypeTestsModule::getJumpTableEntrySize(
Triple::ArchType JumpTableArch) {
1578 switch (JumpTableArch) {
1582 M.getModuleFlag(
"cf-protection-branch")))
1583 if (MD->getZExtValue())
1589 if (CanUseThumbBWJumpTable) {
1590 if (hasBranchTargetEnforcement())
1597 if (hasBranchTargetEnforcement())
1616LowerTypeTestsModule::createJumpTableEntryAsm(
Triple::ArchType JumpTableArch) {
1618 raw_string_ostream AsmOS(Asm);
1623 M.getModuleFlag(
"cf-protection-branch")))
1624 Endbr = !MD->isZero();
1626 AsmOS << (JumpTableArch ==
Triple::x86 ?
"endbr32\n" :
"endbr64\n");
1627 AsmOS <<
"jmp ${0:c}@plt\n";
1629 AsmOS <<
".balign 16, 0xcc\n";
1631 AsmOS <<
"int3\nint3\nint3\n";
1635 if (hasBranchTargetEnforcement())
1639 if (!CanUseThumbBWJumpTable) {
1655 AsmOS <<
"push {r0,r1}\n"
1657 <<
"0: add r0, r0, pc\n"
1658 <<
"str r0, [sp, #4]\n"
1661 <<
"1: .word $0 - (0b + 4)\n";
1663 if (hasBranchTargetEnforcement())
1665 AsmOS <<
"b.w $0\n";
1669 AsmOS <<
"tail $0@plt\n";
1671 AsmOS <<
"pcalau12i $$t0, %pc_hi20($0)\n"
1672 <<
"jirl $$r0, $$t0, %pc_lo12($0)\n";
1674 AsmOS <<
"jump $0\n";
1687void LowerTypeTestsModule::buildBitSetsFromFunctions(
1693 buildBitSetsFromFunctionsNative(TypeIds, Functions);
1695 buildBitSetsFromFunctionsWASM(TypeIds, Functions);
1700void LowerTypeTestsModule::moveInitializerToModuleConstructor(
1701 GlobalVariable *GV) {
1702 if (WeakInitializerFn ==
nullptr) {
1707 M.getDataLayout().getProgramAddressSpace(),
1708 "__cfi_global_var_init", &M);
1714 ?
"__TEXT,__StaticInit,regular,pure_instructions"
1727void LowerTypeTestsModule::findGlobalVariableUsersOf(
1728 Constant *
C, SmallSetVector<GlobalVariable *, 8> &Out) {
1729 for (
auto *U :
C->users()){
1733 findGlobalVariableUsersOf(C2, Out);
1738void LowerTypeTestsModule::replaceWeakDeclarationWithJumpTablePtr(
1739 Function *
F, Constant *JT,
bool IsJumpTableCanonical) {
1742 SmallSetVector<GlobalVariable *, 8> GlobalVarUsers;
1743 findGlobalVariableUsersOf(
F, GlobalVarUsers);
1744 for (
auto *GV : GlobalVarUsers) {
1745 if (GV == GlobalAnnotation)
1747 moveInitializerToModuleConstructor(GV);
1754 F->getAddressSpace(),
"", &M);
1755 replaceCfiUses(
F, PlaceholderFn, IsJumpTableCanonical);
1762 assert(
InsertPt &&
"Non-instruction users should have been eliminated");
1765 InsertPt = PN->getIncomingBlock(U)->getTerminator();
1785 Attribute TFAttr =
F->getFnAttribute(
"target-features");
1790 if (Feature ==
"-thumb-mode")
1792 else if (Feature ==
"+thumb-mode")
1808 if (!CanUseThumbBWJumpTable && CanUseArmJumpTable) {
1816 unsigned ArmCount = 0, ThumbCount = 0;
1817 for (
const auto GTM : Functions) {
1818 if (!GTM->isJumpTableCanonical()) {
1837 if (!JumpTableDIB) {
1838 auto CUs =
M.debug_compile_units();
1840 JumpTableCU = *CUs.begin();
1841 JumpTableDIB.emplace(M,
true, JumpTableCU);
1842 JumpTableFile = JumpTableDIB->createFile(
"ubsan_interface.h",
"sanitizer");
1846 JumpTableCU = JumpTableDIB->createCompileUnit(
1847 DISourceLanguageName(dwarf::DW_LANG_C), JumpTableFile,
"llvm",
true,
1850 JumpTableFnTy = JumpTableDIB->createSubroutineType(
nullptr);
1853 DISubprogram *UbsanSP = JumpTableDIB->createFunction(
1854 JumpTableCU,
"__ubsan_check_cfi_icall_jt", {}, JumpTableFile, 0,
1855 JumpTableFnTy, 0, DINode::FlagArtificial, DISubprogram::SPFlagDefinition);
1857 F->setSubprogram(UbsanSP);
1864 for (
auto *Func : Functions) {
1865 StringRef FuncName =
Func->getGlobal()->getName();
1867 DISubprogram *JumpSP = JumpTableDIB->createFunction(
1868 JumpTableCU, (FuncName +
".cfi_jt").str(), {}, JumpTableFile, 0,
1869 JumpTableFnTy, 0, DINode::FlagArtificial,
1870 DISubprogram::SPFlagDefinition);
1872 DILocation *EntryLoc =
1881void LowerTypeTestsModule::createJumpTable(
1890 F->setMetadata(LLVMContext::MD_elf_section_properties,
1893 ConstantAsMetadata::get(ConstantInt::get(
1894 Int64Ty, ELF::SHT_LLVM_CFI_JUMP_TABLE)),
1895 ConstantAsMetadata::get(ConstantInt::get(
1896 Int64Ty, JumpTableEntrySize))}));
1902 if (
M.getDwarfVersion() != 0 && Opts.lowertypetests_jump_table_debug_info)
1903 Locations = createJumpTableDebugInfo(
F, Functions);
1905 InlineAsm *JumpTableAsm = createJumpTableEntryAsm(JumpTableArch);
1911 bool areAllEntriesNounwind =
true;
1913 for (
auto [GTM, Loc] :
zip_longest(Functions, Locations)) {
1914 if (Loc.has_value())
1915 IRB.SetCurrentDebugLocation(*Loc);
1917 ->hasFnAttribute(Attribute::NoUnwind)) {
1918 areAllEntriesNounwind =
false;
1920 IRB.CreateCall(JumpTableAsm, (*GTM)->getGlobal());
1922 IRB.CreateUnreachable();
1925 F->setPreferredAlignment(
Align(JumpTableEntrySize));
1926 F->addFnAttr(Attribute::Naked);
1928 F->addFnAttr(
"target-features",
"-thumb-mode");
1930 if (hasBranchTargetEnforcement()) {
1933 F->addFnAttr(
"target-features",
"+thumb-mode,+pacbti");
1935 F->addFnAttr(
"target-features",
"+thumb-mode");
1936 if (CanUseThumbBWJumpTable) {
1939 F->addFnAttr(
"target-cpu",
"cortex-a8");
1947 if (
F->hasFnAttribute(
"branch-target-enforcement"))
1948 F->removeFnAttr(
"branch-target-enforcement");
1949 if (
F->hasFnAttribute(
"sign-return-address"))
1950 F->removeFnAttr(
"sign-return-address");
1955 F->addFnAttr(
"target-features",
"-c,-relax");
1961 F->addFnAttr(Attribute::NoCfCheck);
1964 if (areAllEntriesNounwind)
1965 F->addFnAttr(Attribute::NoUnwind);
1968 F->addFnAttr(Attribute::NoInline);
1973void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
2058 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
2059 unsigned EntrySize = getJumpTableEntrySize(JumpTableArch);
2060 for (
unsigned I = 0;
I != Functions.
size(); ++
I)
2061 GlobalLayout[Functions[
I]] =
I * EntrySize;
2067 M.getDataLayout().getProgramAddressSpace(),
2068 ".cfi.jumptable", &M);
2075 lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout);
2081 for (
unsigned I = 0;
I != Functions.
size(); ++
I) {
2083 bool IsJumpTableCanonical = Functions[
I]->isJumpTableCanonical();
2086 F->getDataLayout(), JumpTableType, JumpTable,
2087 {ConstantInt::get(IntPtrTy, 0), ConstantInt::get(IntPtrTy, I)},
2090 const bool IsExported = Functions[
I]->isExported();
2091 if (!IsJumpTableCanonical) {
2095 F->getName() +
".cfi_jt",
2096 CombinedGlobalElemPtr, &M);
2105 if (IsJumpTableCanonical)
2113 if (!IsJumpTableCanonical) {
2114 if (
F->hasExternalWeakLinkage())
2115 replaceWeakDeclarationWithJumpTablePtr(
F, CombinedGlobalElemPtr,
2116 IsJumpTableCanonical);
2118 replaceCfiUses(
F, CombinedGlobalElemPtr, IsJumpTableCanonical);
2120 assert(
F->getType()->getAddressSpace() == 0);
2122 GlobalAlias *FAlias =
2124 CombinedGlobalElemPtr, &M);
2129 F->setName(FAlias->
getName() +
".cfi");
2130 maybeReplaceComdat(
F, FAlias->
getName());
2132 replaceCfiUses(
F, FAlias, IsJumpTableCanonical);
2133 if (!
F->hasLocalLinkage())
2138 if (!UsedJtAliases.
empty())
2141 createJumpTable(JumpTableFn, Functions, JumpTableArch);
2150void LowerTypeTestsModule::buildBitSetsFromFunctionsWASM(
2155 DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
2157 for (GlobalTypeMember *GTM : Functions) {
2161 if (!
F->hasAddressTaken())
2167 ConstantInt::get(Int64Ty, IndirectIndex))));
2168 F->setMetadata(
"wasm.index", MD);
2171 GlobalLayout[GTM] = IndirectIndex++;
2180void LowerTypeTestsModule::buildBitSetsFromDisjointSet(
2183 DenseMap<Metadata *, uint64_t> TypeIdIndices;
2184 for (
unsigned I = 0;
I != TypeIds.
size(); ++
I)
2185 TypeIdIndices[TypeIds[
I]] =
I;
2189 std::vector<std::set<uint64_t>> TypeMembers(TypeIds.
size());
2190 unsigned GlobalIndex = 0;
2191 DenseMap<GlobalTypeMember *, uint64_t> GlobalIndices;
2192 for (GlobalTypeMember *GTM : Globals) {
2193 for (MDNode *
Type : GTM->types()) {
2195 auto I = TypeIdIndices.
find(
Type->getOperand(1));
2196 if (
I != TypeIdIndices.
end())
2197 TypeMembers[
I->second].insert(GlobalIndex);
2199 GlobalIndices[GTM] = GlobalIndex;
2203 for (ICallBranchFunnel *JT : ICallBranchFunnels) {
2204 TypeMembers.emplace_back();
2205 std::set<uint64_t> &TMSet = TypeMembers.back();
2206 for (GlobalTypeMember *
T : JT->targets())
2207 TMSet.insert(GlobalIndices[
T]);
2213 const std::set<uint64_t> &
O2) {
2214 return O1.size() <
O2.size();
2221 if (!IsGlobalSet && !FunctionSummaryHotness.
empty() &&
2222 Opts.reorder_cfi_jump_tables_profiles) {
2224 std::vector<CfiFunctionHotness> GTMHotness;
2225 GTMHotness.reserve(Globals.size());
2226 for (GlobalTypeMember *GTM : Globals) {
2227 GTMHotness.push_back(
2244 return GTMHotness[
A] < GTMHotness[
B];
2252 for (
auto &&MemSet : TypeMembers)
2253 GLB.addFragment(MemSet);
2256 std::vector<GlobalTypeMember *> OrderedGTMs(Globals.size());
2257 auto OGTMI = OrderedGTMs.begin();
2261 "variables and functions");
2262 *OGTMI++ = Globals[
Offset];
2267 buildBitSetsFromGlobalVariables(TypeIds, OrderedGTMs);
2269 buildBitSetsFromFunctions(TypeIds, OrderedGTMs);
2273LowerTypeTestsModule::LowerTypeTestsModule(
2275 const ModuleSummaryIndex *ImportSummary)
2277 ImportSummary(ImportSummary) {
2278 assert(!(ExportSummary && ImportSummary));
2279 Triple TargetTriple(M.getTargetTriple());
2280 Arch = TargetTriple.getArch();
2284 CanUseArmJumpTable =
true;
2288 if (
F.isDeclaration())
2291 if (
TTI.hasArmWideBranch(
false))
2292 CanUseArmJumpTable =
true;
2293 if (
TTI.hasArmWideBranch(
true))
2294 CanUseThumbBWJumpTable =
true;
2297 ObjectFormat = TargetTriple.getObjectFormat();
2301 GlobalAnnotation = M.getGlobalVariable(
"llvm.global.annotations");
2311 StringRef ReadSummary = Opts.lowertypetests_read_summary;
2312 StringRef WriteSummary = Opts.lowertypetests_write_summary;
2314 std::unique_ptr<ModuleSummaryIndex>
Summary;
2318 if (!ReadSummary.
empty()) {
2319 ExitOnError ExitOnErr(
2320 (
"-lowertypetests-read-summary: " + ReadSummary +
": ").str());
2321 auto ReadSummaryFile = ExitOnErr(
2325 if (ReadSummaryFile->getBuffer().starts_with(
"---")) {
2326 Summary = std::make_unique<ModuleSummaryIndex>(
false);
2327 yaml::Input
In(ReadSummaryFile->getBuffer());
2340 Summary = std::make_unique<ModuleSummaryIndex>(
false);
2344 LowerTypeTestsModule(
2346 SummaryAction == PassSummaryAction::Export ?
Summary.get() :
nullptr,
2347 SummaryAction == PassSummaryAction::Import ?
Summary.get() :
nullptr)
2350 if (!WriteSummary.
empty()) {
2351 ExitOnError ExitOnErr(
2352 (
"-lowertypetests-write-summary: " + WriteSummary +
": ").str());
2357 yaml::Output
Out(OS);
2366 return Usr && Usr->isCallee(&U);
2369void LowerTypeTestsModule::replaceCfiUses(
Function *Old,
Value *New,
2370 bool IsJumpTableCanonical) {
2371 SmallSetVector<Constant *, 4>
Constants;
2383 if (isFunctionAnnotation(
U.getUser()))
2401 for (
auto *
C : Constants)
2402 C->handleOperandChange(Old, New);
2405void LowerTypeTestsModule::replaceDirectCalls(
Value *Old,
Value *New) {
2422 Value *Ptr =
I->getOperand(0);
2424 Type *PtrTy =
I->getType()->getStructElementType(0);
2429 Intrinsic::load_relative, {
Offset->getType()}, {Ptr,
Offset},
2430 nullptr,
"rel_load");
2439 I->replaceAllUsesWith(Replacement);
2441 if (ModifiedFunctions)
2442 ModifiedFunctions->
insert(
I->getFunction());
2445 I->eraseFromParent();
2464 Assume->eraseFromParent();
2473 return isa<PHINode>(U) || isa<SelectInst>(U);
2486 dropTypeTests(M, *TypeTestFunc, ShouldDropAll, ModifiedFunctions);
2490 bool DroppedCheckedLoads =
false;
2491 if (ShouldDropAll) {
2495 M, *
F,
false, &ModifiedFunctions);
2497 &M, Intrinsic::type_checked_load_relative))
2499 M, *
F,
true, &ModifiedFunctions);
2506 if (PublicTypeTestFunc)
2507 dropTypeTests(M, *PublicTypeTestFunc, ShouldDropAll, ModifiedFunctions);
2508 bool Changed = TypeTestFunc || PublicTypeTestFunc || DroppedCheckedLoads;
2509 if (
Changed || ShouldDropAll) {
2519bool LowerTypeTestsModule::lower() {
2533 if ((!TypeTestFunc || TypeTestFunc->
use_empty()) &&
2534 (!ICallBranchFunnelFunc || ICallBranchFunnelFunc->
use_empty()) &&
2535 !ExportSummary && !ImportSummary)
2538 if (ImportSummary) {
2543 if (ICallBranchFunnelFunc && !ICallBranchFunnelFunc->
use_empty())
2545 "unexpected call to llvm.icall.branch.funnel during import phase");
2552 if (
A.hasLocalLinkage())
2557 if (
F->hasExternalLinkage()) {
2572 A.replaceAllUsesWith(
F);
2574 A.eraseFromParent();
2584 if (
F.hasLocalLinkage())
2593 ScopedSaveAliaseesAndUsed S(M);
2594 for (
auto *
F : Defs)
2595 importFunction(
F,
true);
2596 for (
auto *
F : Decls)
2597 importFunction(
F,
false);
2600 for (
auto &[
F, Name] : PromotedFuncs)
2609 using GlobalClassesTy = EquivalenceClasses<
2610 PointerUnion<GlobalTypeMember *, Metadata *, ICallBranchFunnel *>>;
2611 GlobalClassesTy GlobalClasses;
2623 std::vector<GlobalTypeMember *> RefGlobals;
2625 DenseMap<Metadata *, TIInfo> TypeIdInfo;
2626 unsigned CurUniqueId = 0;
2629 struct ExportedFunctionInfo {
2633 MapVector<StringRef, ExportedFunctionInfo> ExportedFunctions;
2634 if (ExportSummary) {
2635 NamedMDNode *CfiFunctionsMD =
M.getNamedMetadata(
"cfi.functions");
2636 if (CfiFunctionsMD) {
2638 DenseSet<GlobalValue::GUID> AddressTaken;
2639 for (
auto &
I : *ExportSummary)
2640 for (
auto &GVS :
I.second.getSummaryList())
2642 for (
const auto &
Ref : GVS->refs()) {
2644 for (
auto &RefGVS :
Ref.getSummaryList())
2646 AddressTaken.
insert(Alias->getAliaseeGUID());
2649 if (AddressTaken.
count(GUID))
2651 auto VI = ExportSummary->getValueInfo(GUID);
2654 for (
auto &
I :
VI.getSummaryList())
2656 if (AddressTaken.
count(Alias->getAliaseeGUID()))
2660 for (
auto *FuncMD : CfiFunctionsMD->
operands()) {
2661 assert(FuncMD->getNumOperands() >= 2);
2662 StringRef FunctionName =
2667 ->getUniqueInteger()
2672 ->getUniqueInteger()
2676 if (!ExportSummary->isGUIDLive(GUID))
2679 if (!CrossDsoCfi ||
Linkage != CfiFunctionLinkage::Definition)
2683 if (
auto VI = ExportSummary->getValueInfo(GUID))
2684 for (
const auto &GVS :
VI.getSummaryList())
2691 auto P = ExportedFunctions.
insert({FunctionName, {
Linkage, FuncMD}});
2693 P.first->second.Linkage != CfiFunctionLinkage::Definition)
2694 P.first->second = {
Linkage, FuncMD};
2697 for (
const auto &
P : ExportedFunctions) {
2698 StringRef FunctionName =
P.first;
2699 CfiFunctionLinkage
Linkage =
P.second.Linkage;
2700 MDNode *FuncMD =
P.second.FuncMD;
2702 if (
F &&
F->hasLocalLinkage()) {
2709 F->setName(
F->getName() +
".1");
2715 FunctionType::get(Type::getVoidTy(
M.getContext()),
false),
2716 GlobalVariable::ExternalLinkage,
2717 M.getDataLayout().getProgramAddressSpace(), FunctionName, &M);
2719 LLVMContext::MD_guid,
2720 MDTuple::get(
M.getContext(), {FuncMD->getOperand(2).get()}));
2721 if (ExportSummary) {
2725 ->getUniqueInteger()
2727 if (
auto VI = ExportSummary->getValueInfo(GUID))
2729 VI.isDSOLocal(ExportSummary->withDSOLocalPropagation()));
2737 if (
F->hasAvailableExternallyLinkage()) {
2739 auto *OrigGUIDMD =
F->getMetadata(LLVMContext::MD_guid);
2742 F->setComdat(
nullptr);
2744 F->setMetadata(LLVMContext::MD_guid, OrigGUIDMD);
2749 if (
Linkage == CfiFunctionLinkage::Definition &&
2750 F->hasExternalWeakLinkage())
2757 if (
F->isDeclaration()) {
2758 if (
Linkage == CfiFunctionLinkage::WeakDeclaration)
2761 F->eraseMetadata(LLVMContext::MD_type);
2763 F->addMetadata(LLVMContext::MD_type,
2768 ->getUniqueInteger()
2776 struct AliasToCreate {
2778 std::string TargetName;
2780 std::vector<AliasToCreate> AliasesToCreate;
2784 if (ExportSummary) {
2785 if (NamedMDNode *AliasesMD =
M.getNamedMetadata(
"aliases")) {
2786 for (
auto *AliasMD : AliasesMD->operands()) {
2789 StringRef AliasName = MDS->getString();
2790 if (!ExportedFunctions.count(AliasName))
2792 auto *AliasF =
M.getFunction(AliasName);
2797 if (Aliases.
empty())
2800 for (
unsigned I = 1;
I != Aliases.
size(); ++
I) {
2801 auto *AliasF = Aliases[
I];
2802 ExportedFunctions.
erase(AliasF->getName());
2803 AliasesToCreate.push_back(
2804 {AliasF, std::string(Aliases[0]->
getName())});
2810 DenseMap<GlobalObject *, GlobalTypeMember *> GlobalTypeMembers;
2811 for (GlobalObject &GO :
M.global_objects()) {
2818 bool IsJumpTableCanonical =
false;
2819 bool IsExported =
false;
2822 if (
auto It = ExportedFunctions.find(
F->getName());
2823 It != ExportedFunctions.end()) {
2824 IsJumpTableCanonical |=
2825 It->second.Linkage == CfiFunctionLinkage::Definition;
2831 }
else if (!
F->hasAddressTaken()) {
2832 if (!CrossDsoCfi || !IsJumpTableCanonical ||
F->hasLocalLinkage())
2841 auto *GTM = GlobalTypeMember::create(
Alloc, &GO, IsJumpTableCanonical,
2843 GlobalTypeMembers[&GO] = GTM;
2844 for (MDNode *
Type : Types) {
2845 verifyTypeMDNode(&GO,
Type);
2846 auto &
Info = TypeIdInfo[
Type->getOperand(1)];
2847 Info.UniqueId = ++CurUniqueId;
2848 Info.RefGlobals.push_back(GTM);
2852 auto AddTypeIdUse = [&](
Metadata *TypeId) -> TypeIdUserInfo & {
2857 auto Ins = TypeIdUsers.
insert({TypeId, {}});
2860 auto &GCI = GlobalClasses.insert(TypeId);
2861 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
2864 for (GlobalTypeMember *GTM : TypeIdInfo[TypeId].RefGlobals)
2865 CurSet = GlobalClasses.unionSets(
2866 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(GTM)));
2869 return Ins.first->second;
2873 for (
const Use &U : TypeTestFunc->
uses()) {
2882 for (Instruction *CIU : CI->
users()) {
2885 OnlyAssumeUses =
false;
2894 auto TypeId = TypeIdMDVal->getMetadata();
2895 AddTypeIdUse(TypeId).CallSites.push_back(CI);
2899 if (ICallBranchFunnelFunc) {
2900 for (
const Use &U : ICallBranchFunnelFunc->
uses()) {
2903 "llvm.icall.branch.funnel not supported on this target");
2907 std::vector<GlobalTypeMember *> Targets;
2911 GlobalClassesTy::member_iterator CurSet;
2912 for (
unsigned I = 1;
I != CI->
arg_size();
I += 2) {
2918 "Expected branch funnel operand to be global value");
2920 auto It = GlobalTypeMembers.
find(
Base);
2921 if (It == GlobalTypeMembers.
end())
2923 "defined global value with type metadata");
2924 GlobalTypeMember *GTM = It->second;
2925 Targets.push_back(GTM);
2926 GlobalClassesTy::member_iterator NewSet =
2927 GlobalClasses.findLeader(GlobalClasses.insert(GTM));
2931 CurSet = GlobalClasses.unionSets(CurSet, NewSet);
2934 GlobalClasses.unionSets(
2935 CurSet, GlobalClasses.findLeader(
2936 GlobalClasses.insert(ICallBranchFunnel::create(
2937 Alloc, CI, Targets, ++CurUniqueId))));
2941 if (ExportSummary) {
2942 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
2943 for (
auto &
P : TypeIdInfo) {
2946 TypeId->getString())]
2950 for (
auto &
P : *ExportSummary) {
2951 for (
auto &S :
P.second.getSummaryList()) {
2952 if (!ExportSummary->isGlobalValueLive(S.get()))
2957 AddTypeIdUse(MD).IsExported =
true;
2962 if (GlobalClasses.empty())
2966 ScopedSaveAliaseesAndUsed S(M);
2968 for (
const auto &
C : GlobalClasses) {
2972 ++NumTypeIdDisjointSets;
2974 std::vector<Metadata *> TypeIds;
2975 std::vector<GlobalTypeMember *> Globals;
2976 std::vector<ICallBranchFunnel *> ICallBranchFunnels;
2977 for (
auto M : GlobalClasses.members(*
C)) {
2990 return TypeIdInfo[
M1].UniqueId < TypeIdInfo[M2].UniqueId;
2995 [&](ICallBranchFunnel *F1, ICallBranchFunnel *F2) {
2996 return F1->UniqueId < F2->UniqueId;
3000 buildBitSetsFromDisjointSet(TypeIds, Globals, ICallBranchFunnels);
3004 allocateByteArrays();
3006 for (
auto A : AliasesToCreate) {
3007 auto *
Target =
M.getNamedValue(
A.TargetName);
3011 AliasGA->setVisibility(
A.Alias->getVisibility());
3012 AliasGA->setLinkage(
A.Alias->getLinkage());
3013 AliasGA->setDSOLocal(
A.Alias->isDSOLocal());
3014 AliasGA->takeName(
A.Alias);
3015 A.Alias->replaceAllUsesWith(AliasGA);
3016 A.Alias->eraseFromParent();
3020 if (ExportSummary) {
3021 if (NamedMDNode *SymversMD =
M.getNamedMetadata(
"symvers")) {
3022 for (
auto *Symver : SymversMD->operands()) {
3023 assert(Symver->getNumOperands() >= 2);
3026 StringRef Alias =
cast<MDString>(Symver->getOperand(1))->getString();
3028 if (!ExportedFunctions.count(SymbolName))
3031 M.appendModuleInlineAsm(
3032 (llvm::Twine(
".symver ") + SymbolName +
", " + Alias).str());
3044 Changed = LowerTypeTestsModule::runForTesting(M, AM);
3046 Changed = LowerTypeTestsModule(M, AM, ExportSummary, ImportSummary).lower();
3054 static_cast<PassInfoMixin<DropTypeTestsPass> *
>(
this)->
printPipeline(
3055 OS, MapClassName2PassName);
3058 case DropTestKind::Assume:
3061 case DropTestKind::All:
3069 bool ShouldDropAll = Kind == DropTestKind::All;
3075 if (ShouldDropAll) {
3077 Intrinsic::type_checked_load_relative}) {
3079 FAM.clear(*
F,
F->getName());
3090 FAM.invalidate(*
F, FuncPA);
3101 bool ReplacedConstant =
false;
3121 for (
auto &GV : M.globals()) {
3128 auto MaySimplifyPtr = [&](
Value *Ptr) {
3130 if (
auto *CFIGV = M.getNamedValue((GV->
getName() +
".cfi").str()))
3134 auto MaySimplifyInt = [&](
Value *
Op) {
3136 if (!PtrAsInt || PtrAsInt->getOpcode() != Instruction::PtrToInt)
3138 return MaySimplifyPtr(PtrAsInt->getOperand(0));
3155 if (!CE || CE->getOpcode() != Instruction::PtrToInt)
3159 if (U.getOperandNo() == 0 && CE &&
3160 CE->getOpcode() == Instruction::Sub &&
3161 MaySimplifyInt(CE->getOperand(1))) {
3167 CE->replaceAllUsesWith(ConstantInt::get(CE->getType(), 0));
3168 ReplacedConstant =
true;
3172 if (U.getOperandNo() == 1 && CI &&
3194 FAM.invalidate(*
F, FuncPA);
3199 if (ReplacedConstant)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static const unsigned kARMJumpTableEntrySize
static const unsigned kLOONGARCH64JumpTableEntrySize
static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL, Value *V, uint64_t COffset)
static const unsigned kX86IBTJumpTableEntrySize
static ConstantInt * extractNumericTypeId(MDNode &MD)
Extracts a numeric type identifier from an MDNode containing type metadata.
static const unsigned kRISCVJumpTableEntrySize
static auto buildBitSets(ArrayRef< Metadata * > TypeIds, const DenseMap< GlobalTypeMember *, uint64_t > &GlobalLayout)
static Value * createMaskedBitTest(IRBuilder<> &B, Value *Bits, Value *BitOffset)
Build a test that bit BitOffset mod sizeof(Bits)*8 is set in Bits.
static bool isThumbFunction(Function *F, Triple::ArchType ModuleArch)
static const unsigned kX86JumpTableEntrySize
static void createCfiSymversMetadata(Module &DestM, const Module &SrcM)
static void dropTypeTests(Module &M, Function &TypeTestFunc, bool ShouldDropAll, SmallSetVector< Function *, 8 > &ModifiedFunctions)
static const unsigned kARMBTIJumpTableEntrySize
static CfiFunctionLinkage decodeCfiFunctionLinkage(uint8_t Encoded)
static void createCfiFunctionsMetadata(Module &DestM, ArrayRef< GlobalValue * > CfiFunctions, ProfileSummaryInfo &PSI, function_ref< const BlockFrequencyInfo &(Function &)> BFIGetter)
static BitSetInfo buildBitSet(ArrayRef< uint64_t > Offsets)
Build a bit set for list of offsets.
static const unsigned kARMv6MJumpTableEntrySize
static uint8_t encodeCfiFunctionLinkage(CfiFunctionLinkage Linkage, CfiFunctionHotness Hotness)
static CfiFunctionHotness decodeCfiFunctionHotness(uint8_t Encoded)
static const unsigned kHexagonJumpTableEntrySize
static void createCfiAliasesMetadata(Module &DestM, const Module &SrcM)
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
FunctionAnalysisManager FAM
This file defines the PointerUnion class, which is a discriminated union of pointer types.
This file contains the declarations for profiling metadata utility functions.
static StringRef getName(Value *V)
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
This header defines support for implementing classes that have some trailing object (or arrays of obj...
static bool isDirectCall(const MCInst &Inst)
Class for arbitrary precision integers.
uint64_t getZExtValue() const
Get zero extended value.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Represents analyses that only rely on functions' control flow.
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
bool contains(StringRef Name) const
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
ConstantArray - Constant Array Declarations.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP Constant * getInBoundsPtrAdd(Constant *Ptr, Constant *Offset)
Create a getelementptr inbounds i8, ptr, offset constant expression.
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const BasicBlock & getEntryBlock() const
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
static GEPNoWrapFlags inBounds()
static LLVM_ABI 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...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
const Comdat * getComdat() const
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasSection() const
Check if this global has a custom object file section.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
VisibilityTypes getVisibility() const
static bool isLocalLinkage(LinkageTypes Linkage)
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool isDeclarationForLinker() const
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ HiddenVisibility
The GV is hidden.
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ 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.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
bool hasInitializer() const
Definitions have initializers, declarations don't.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Value * CreatePtrAddWithSExtOrTrunc(Value *Ptr, Value *Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd where the offset is sign-extended or truncated to the index type.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const MDOperand & getOperand(unsigned I) const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
unsigned getNumOperands() const
Return number of MDNode operands.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
This class implements a map that also provides access to all stored values in a deterministic order.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
const TypeIdSummary * getTypeIdSummary(StringRef TypeId) const
This returns either a pointer to the type id summary (if present in the summary map) or null (if not ...
CfiFunctionIndex & cfiFunctionDecls()
bool partiallySplitLTOUnits() const
CfiFunctionIndex & cfiFunctionDefs()
static LLVM_ABI 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.
LLVMContext & getContext() const
Get the global data context.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
iterator_range< alias_iterator > aliases()
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
iterator_range< op_iterator > operands()
LLVM_ABI void addOperand(MDNode *M)
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Analysis providing profile information.
bool isFunctionColdInCallGraph(const FuncT *F, BFIT &BFI) const
Returns true if F contains only cold code.
LLVM_ABI bool isFunctionHotnessUnknown(const Function &F) const
Returns true if the hotness of F is unknown.
bool isFunctionHotInCallGraph(const FuncT *F, BFIT &BFI) const
Returns true if F contains hot code.
LLVM_ABI bool hasPartialSampleProfile() const
Returns true if module M has partial-profile sample profile.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
LLVM_ABI void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true, bool ShowLocation=true) const
A vector that has set insertion semantics.
bool insert(const value_type &X)
Insert a new element into the SetVector.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
A SetVector that performs no allocations if smaller than a certain size.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
std::string str() const
Get the contents as an std::string.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Type * getElementType(unsigned N) const
Analysis pass providing the TargetTransformInfo.
See the file comment for details on the usage of the TrailingObjects type.
Triple - Helper class for working with autoconf configuration names.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVM_ABI bool replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class implements a layout algorithm for globals referenced by bit sets that tries to keep member...
LLVM_ABI const std::vector< uint64_t > & build()
Flatten fragments into a single layout and return it.
LLVM_ABI void addFragment(const std::set< uint64_t > &F)
Add F to the layout while trying to keep its indices contiguous.
This class implements an extremely fast bulk output stream that can only output to a stream.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI SetVector< uint64_t > findCfiTypeIds(const Module &M)
Finds all 64-bit numeric type identifiers in M used for cross-DSO CFI.
LLVM_ABI void createCfiMetadata(Module &DestM, const Module &SrcM, ArrayRef< GlobalValue * > CfiFunctions, ProfileSummaryInfo &PSI, function_ref< const BlockFrequencyInfo &(Function &)> BFIGetter)
Creates cfi.functions, aliases, and symvers named metadata in DestM for CFI functions in CfiFunctions...
LLVM_ABI bool isJumpTableCanonical(Function *F)
LLVM_ABI bool cleanUpTypeCheckedLoad(Module &M, Function &CheckedLoadFn, bool IsRelative, SmallSetVector< Function *, 8 > *ModifiedFunctions=nullptr)
Lower @llvm.type.checked.load[.relative] calls to the guarded load with the check assumed true,...
LLVM_ABI bool hasTypeMetadata(const GlobalObject &GO)
Returns whether a global or its associated global has attached type metadata.
LLVM_ABI SetVector< GlobalValue * > findCfiFunctions(Module &M)
Finds all functions and aliases in M that may need CFI jump table entries.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
SmallVector< unsigned char, 0 > ByteArray
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
NodeAddr< FuncNode * > Func
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
bool operator<(int64_t V1, const APSInt &V2)
void stable_sort(R &&Range)
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
detail::zip_longest_range< T, U, Args... > zip_longest(T &&t, U &&u, Args &&... args)
Iterate over two or more iterators at the same time.
@ Unknown
Not known to have no common set bits.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
@ Load
The value being inserted comes from a load (InsertElement only).
PassSummaryAction
What to do with the summary when running passes that operate on it.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
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...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
unsigned M1(unsigned Val)
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
auto dyn_cast_or_null(const Y &Val)
LLVM_ABI bool convertUsersOfConstantsToInstructions(ArrayRef< Constant * > Consts, Function *RestrictToFunc=nullptr, bool RemoveDeadConstants=true, bool IncludeSelf=false)
Replace constant expressions users of the given constants with instructions.
const IPOOptions & getIPOOptions(const LLVMContext &C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
DWARFExpression::Operation Op
bool isMemProfClone(const GlobalValue &GV)
Returns true if GV is a MemProf context-disambiguated clone.
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
constexpr unsigned BitWidth
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > parseSummaryIndexAssembly(MemoryBufferRef F, SMDiagnostic &Err)
Parse LLVM Assembly for summary index from a MemoryBuffer.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Kind
Specifies which kind of type check we should emit for this byte array.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
LLVM_ABI BitSetInfo build()
SmallVector< uint64_t, 16 > Offsets
LLVM_ABI bool containsGlobalOffset(uint64_t Offset) const
LLVM_ABI void print(raw_ostream &OS) const
std::set< uint64_t > Bits
This class is used to build a byte array containing overlapping bit sets.
uint64_t BitAllocs[BitsPerByte]
The number of bytes allocated so far for each of the bits.
std::vector< uint8_t > Bytes
The byte array built so far.
LLVM_ABI void allocate(const std::set< uint64_t > &Bits, uint64_t BitSize, uint64_t &AllocByteOffset, uint8_t &AllocMask)
Allocate BitSize bits in the byte array where Bits contains the bits to set.