80 #include <system_error> 85 using namespace lowertypetests;
87 #define DEBUG_TYPE "lowertypetests" 89 STATISTIC(ByteArraySizeBits,
"Byte array size in bits");
90 STATISTIC(ByteArraySizeBytes,
"Byte array size in bytes");
91 STATISTIC(NumByteArraysCreated,
"Number of byte arrays created");
92 STATISTIC(NumTypeTestCallsLowered,
"Number of type test calls lowered");
93 STATISTIC(NumTypeIdDisjointSets,
"Number of disjoint sets of type identifiers");
96 "lowertypetests-avoid-reuse",
97 cl::desc(
"Try to avoid reuse of byte array addresses using aliases"),
101 "lowertypetests-summary-action",
102 cl::desc(
"What to do with the summary when running this pass"),
105 "Import typeid resolutions from summary and globals"),
107 "Export typeid resolutions to summary and globals")),
111 "lowertypetests-read-summary",
112 cl::desc(
"Read summary from given YAML file before running pass"),
116 "lowertypetests-write-summary",
117 cl::desc(
"Write summary to given YAML file after running pass"),
131 return Bits.count(BitOffset);
144 for (uint64_t
B :
Bits)
174 for (uint64_t
Offset : Offsets) {
184 Fragments.emplace_back();
185 std::vector<uint64_t> &Fragment = Fragments.back();
186 uint64_t FragmentIndex = Fragments.size() - 1;
188 for (
auto ObjIndex : F) {
189 uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
190 if (OldFragmentIndex == 0) {
193 Fragment.push_back(ObjIndex);
200 std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
201 Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
207 for (uint64_t ObjIndex : Fragment)
208 FragmentMap[ObjIndex] = FragmentIndex;
212 uint64_t
BitSize, uint64_t &AllocByteOffset,
213 uint8_t &AllocMask) {
216 for (
unsigned I = 1;
I != BitsPerByte; ++
I)
217 if (BitAllocs[
I] < BitAllocs[Bit])
220 AllocByteOffset = BitAllocs[
Bit];
223 unsigned ReqSize = AllocByteOffset +
BitSize;
224 BitAllocs[
Bit] = ReqSize;
225 if (Bytes.size() < ReqSize)
226 Bytes.resize(ReqSize);
229 AllocMask = 1 <<
Bit;
230 for (uint64_t
B : Bits)
231 Bytes[AllocByteOffset +
B] |= AllocMask;
237 auto *CI = mdconst::extract_or_null<ConstantInt>(
239 if (!CI || CI->getZExtValue() != 0)
246 struct ByteArrayInfo {
247 std::set<uint64_t>
Bits;
251 uint8_t *MaskPtr =
nullptr;
259 class GlobalTypeMember final :
TrailingObjects<GlobalTypeMember, MDNode *> {
270 bool IsJumpTableCanonical;
276 size_t numTrailingObjects(OverloadToken<MDNode *>)
const {
return NTypes; }
280 bool IsJumpTableCanonical,
bool IsExported,
282 auto *GTM =
static_cast<GlobalTypeMember *
>(Alloc.
Allocate(
283 totalSizeToAlloc<MDNode *>(Types.
size()),
alignof(GlobalTypeMember)));
285 GTM->NTypes = Types.
size();
286 GTM->IsJumpTableCanonical = IsJumpTableCanonical;
287 GTM->IsExported = IsExported;
288 std::uninitialized_copy(Types.
begin(), Types.
end(),
289 GTM->getTrailingObjects<
MDNode *>());
298 return IsJumpTableCanonical;
301 bool isExported()
const {
306 return makeArrayRef(getTrailingObjects<MDNode *>(), NTypes);
310 struct ICallBranchFunnel final
315 auto *Call =
static_cast<ICallBranchFunnel *
>(
316 Alloc.
Allocate(totalSizeToAlloc<GlobalTypeMember *>(Targets.
size()),
317 alignof(ICallBranchFunnel)));
319 Call->UniqueId = UniqueId;
320 Call->NTargets = Targets.
size();
321 std::uninitialized_copy(Targets.
begin(), Targets.
end(),
322 Call->getTrailingObjects<GlobalTypeMember *>());
328 return makeArrayRef(getTrailingObjects<GlobalTypeMember *>(), NTargets);
337 struct ScopedSaveAliaseesAndUsed {
340 std::vector<std::pair<GlobalIndirectSymbol *, Function *>> FunctionAliases;
342 ScopedSaveAliaseesAndUsed(
Module &M) : M(M) {
356 GV->eraseFromParent();
358 GV->eraseFromParent();
360 for (
auto &GIS : concat<GlobalIndirectSymbol>(M.
aliases(), M.
ifuncs())) {
364 dyn_cast<Function>(GIS.getIndirectSymbol()->stripPointerCasts()))
365 FunctionAliases.push_back({&GIS,
F});
369 ~ScopedSaveAliaseesAndUsed() {
372 CompilerUsed.
end()));
374 for (
auto P : FunctionAliases)
375 P.first->setIndirectSymbol(
380 class LowerTypeTestsModule {
400 uint64_t IndirectIndex = 1;
405 struct TypeIdUserInfo {
406 std::vector<CallInst *> CallSites;
407 bool IsExported =
false;
415 struct TypeIdLowering {
439 std::vector<ByteArrayInfo> ByteArrayInfos;
441 Function *WeakInitializerFn =
nullptr;
443 bool shouldExportConstantsAsAbsoluteSymbols();
444 uint8_t *exportTypeId(
StringRef TypeId,
const TypeIdLowering &TIL);
445 TypeIdLowering importTypeId(
StringRef TypeId);
448 std::vector<GlobalAlias *> &AliasesToErase);
453 ByteArrayInfo *createByteArray(
BitSetInfo &BSI);
454 void allocateByteArrays();
457 void lowerTypeTestCalls(
461 const TypeIdLowering &TIL);
465 unsigned getJumpTableEntrySize();
466 Type *getJumpTableEntryType();
483 bool IsJumpTableCanonical);
485 void findGlobalVariableUsersOf(
Constant *
C,
495 void replaceCfiUses(
Function *Old,
Value *New,
bool IsJumpTableCanonical);
499 void replaceDirectCalls(
Value *Old,
Value *New);
509 static bool runForTesting(
Module &M);
515 bool UseCommandLine =
false;
520 LowerTypeTests() :
ModulePass(ID), UseCommandLine(
true) {
526 :
ModulePass(ID), ExportSummary(ExportSummary),
527 ImportSummary(ImportSummary) {
531 bool runOnModule(
Module &M)
override {
533 return LowerTypeTestsModule::runForTesting(M);
534 return LowerTypeTestsModule(M, ExportSummary, ImportSummary).lower();
548 return new LowerTypeTests(ExportSummary, ImportSummary);
560 for (
auto &GlobalAndOffset : GlobalLayout) {
561 for (
MDNode *
Type : GlobalAndOffset.first->types()) {
562 if (
Type->getOperand(1) != TypeId)
566 cast<ConstantAsMetadata>(
Type->getOperand(0))->getValue())
568 BSB.
addOffset(GlobalAndOffset.second + Offset);
579 auto BitsType = cast<IntegerType>(Bits->
getType());
580 unsigned BitWidth = BitsType->getBitWidth();
590 ByteArrayInfo *LowerTypeTestsModule::createByteArray(
BitSetInfo &BSI) {
599 ByteArrayInfos.emplace_back();
600 ByteArrayInfo *BAI = &ByteArrayInfos.back();
602 BAI->Bits = BSI.
Bits;
604 BAI->ByteArray = ByteArrayGlobal;
605 BAI->MaskGlobal = MaskGlobal;
609 void LowerTypeTestsModule::allocateByteArrays() {
611 [](
const ByteArrayInfo &BAI1,
const ByteArrayInfo &BAI2) {
612 return BAI1.BitSize > BAI2.BitSize;
615 std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
618 for (
unsigned I = 0;
I != ByteArrayInfos.size(); ++
I) {
619 ByteArrayInfo *BAI = &ByteArrayInfos[
I];
622 BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[
I], Mask);
624 BAI->MaskGlobal->replaceAllUsesWith(
626 BAI->MaskGlobal->eraseFromParent();
628 *BAI->MaskPtr =
Mask;
636 for (
unsigned I = 0;
I != ByteArrayInfos.size(); ++
I) {
637 ByteArrayInfo *BAI = &ByteArrayInfos[
I];
642 ByteArrayConst->
getType(), ByteArray, Idxs);
649 BAI->ByteArray->replaceAllUsesWith(Alias);
650 BAI->ByteArray->eraseFromParent();
653 ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
654 BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
655 BAB.BitAllocs[6] + BAB.BitAllocs[7];
656 ByteArraySizeBytes = BAB.Bytes.size();
662 const TypeIdLowering &TIL,
669 Constant *ByteArray = TIL.TheByteArray;
676 "bits_use", ByteArray, &M);
689 Value *V, uint64_t COffset) {
690 if (
auto GV = dyn_cast<GlobalObject>(V)) {
692 GV->getMetadata(LLVMContext::MD_type, Types);
694 if (
Type->getOperand(1) != TypeId)
698 cast<ConstantAsMetadata>(
Type->getOperand(0))->getValue())
700 if (COffset == Offset)
706 if (
auto GEP = dyn_cast<GEPOperator>(V)) {
708 bool Result =
GEP->accumulateConstantOffset(DL, APOffset);
711 COffset += APOffset.getZExtValue();
715 if (
auto Op = dyn_cast<Operator>(V)) {
716 if (
Op->getOpcode() == Instruction::BitCast)
730 const TypeIdLowering &TIL) {
774 return OffsetInRange;
781 if (
auto *Br = dyn_cast<BranchInst>(*CI->
user_begin()))
787 Br->getMetadata(LLVMContext::MD_prof));
791 for (
auto &Phi : Else->
phis())
792 Phi.addIncoming(Phi.getIncomingValueForBlock(Then), InitialBB);
795 return createBitSetTest(ThenB, TIL, BitOffset);
802 Value *
Bit = createBitSetTest(ThenB, TIL, BitOffset);
816 void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
823 std::vector<Constant *> GlobalInits;
827 uint64_t CurOffset = 0;
828 uint64_t DesiredPadding = 0;
829 for (GlobalTypeMember *
G : Globals) {
830 auto *GV = cast<GlobalVariable>(
G->getGlobal());
834 MaxAlign =
std::max(MaxAlign, *Alignment);
835 uint64_t GVOffset =
alignTo(CurOffset + DesiredPadding, *Alignment);
836 GlobalLayout[
G] = GVOffset;
838 uint64_t Padding = GVOffset - CurOffset;
839 GlobalInits.push_back(
843 GlobalInits.push_back(GV->getInitializer());
845 CurOffset = GVOffset + InitSize;
854 if (DesiredPadding > 32)
855 DesiredPadding =
alignTo(InitSize, 32) - InitSize;
859 auto *CombinedGlobal =
865 lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
870 for (
unsigned I = 0;
I != Globals.size(); ++
I) {
877 NewInit->
getType(), CombinedGlobal, CombinedGlobalIdxs);
881 "", CombinedGlobalElemPtr, &M);
883 GAlias->takeName(GV);
889 bool LowerTypeTestsModule::shouldExportConstantsAsAbsoluteSymbols() {
902 uint8_t *LowerTypeTestsModule::exportTypeId(
StringRef TypeId,
903 const TypeIdLowering &TIL) {
905 ExportSummary->getOrInsertTypeIdSummary(TypeId).TTRes;
911 "__typeid_" + TypeId +
"_" + Name,
C, &M);
916 if (shouldExportConstantsAsAbsoluteSymbols())
919 Storage = cast<ConstantInt>(
C)->getZExtValue();
923 ExportGlobal(
"global_addr", TIL.OffsetedGlobal);
928 ExportConstant(
"align", TTRes.
AlignLog2, TIL.AlignLog2);
929 ExportConstant(
"size_m1", TTRes.
SizeM1, TIL.SizeM1);
931 uint64_t
BitSize = cast<ConstantInt>(TIL.SizeM1)->getZExtValue() + 1;
939 ExportGlobal(
"byte_array", TIL.TheByteArray);
940 if (shouldExportConstantsAsAbsoluteSymbols())
941 ExportGlobal(
"bit_mask", TIL.BitMask);
947 ExportConstant(
"inline_bits", TTRes.
InlineBits, TIL.InlineBits);
952 LowerTypeTestsModule::TypeIdLowering
953 LowerTypeTestsModule::importTypeId(
StringRef TypeId) {
954 const TypeIdSummary *TidSummary = ImportSummary->getTypeIdSummary(TypeId);
965 Constant *
C = M.getOrInsertGlobal((
"__typeid_" + TypeId +
"_" +
Name).str(),
967 if (
auto *GV = dyn_cast<GlobalVariable>(C))
973 auto ImportConstant = [&](
StringRef Name, uint64_t Const,
unsigned AbsWidth,
975 if (!shouldExportConstantsAsAbsoluteSymbols()) {
978 if (!isa<IntegerType>(Ty))
985 if (isa<IntegerType>(Ty))
987 if (GV->getMetadata(LLVMContext::MD_absolute_symbol))
990 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
993 GV->setMetadata(LLVMContext::MD_absolute_symbol,
996 if (AbsWidth == IntPtrTy->getBitWidth())
997 SetAbsRange(~0ull, ~0ull);
999 SetAbsRange(0, 1ull << AbsWidth);
1004 TIL.OffsetedGlobal = ImportGlobal(
"global_addr");
1009 TIL.AlignLog2 = ImportConstant(
"align", TTRes.
AlignLog2, 8, Int8Ty);
1015 TIL.TheByteArray = ImportGlobal(
"byte_array");
1016 TIL.BitMask = ImportConstant(
"bit_mask", TTRes.
BitMask, 8, Int8PtrTy);
1020 TIL.InlineBits = ImportConstant(
1027 void LowerTypeTestsModule::importTypeTest(
CallInst *CI) {
1035 "Second argument of llvm.type.test must be a metadata string");
1037 TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
1038 Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
1045 void LowerTypeTestsModule::importFunction(
1047 std::vector<GlobalAlias *> &AliasesToErase) {
1062 replaceDirectCalls(F, RealF);
1068 if (!isJumpTableCanonical) {
1085 for (
auto &U : F->
uses()) {
1086 if (
auto *A = dyn_cast<GlobalAlias>(U.getUser())) {
1091 A->replaceAllUsesWith(AliasDecl);
1092 AliasesToErase.push_back(A);
1098 replaceWeakDeclarationWithJumpTablePtr(F, FDecl, isJumpTableCanonical);
1100 replaceCfiUses(F, FDecl, isJumpTableCanonical);
1107 void LowerTypeTestsModule::lowerTypeTestCalls(
1115 BitSetInfo BSI = buildBitSet(TypeId, GlobalLayout);
1117 if (
auto MDS = dyn_cast<MDString>(TypeId))
1118 dbgs() << MDS->getString() <<
": ";
1120 dbgs() <<
"<unnamed>: ";
1124 ByteArrayInfo *BAI =
nullptr;
1133 }
else if (BSI.
BitSize <= 64) {
1135 uint64_t InlineBits = 0;
1137 InlineBits |= uint64_t(1) <<
Bit;
1138 if (InlineBits == 0)
1145 ++NumByteArraysCreated;
1146 BAI = createByteArray(BSI);
1147 TIL.TheByteArray = BAI->ByteArray;
1148 TIL.BitMask = BAI->MaskGlobal;
1151 TypeIdUserInfo &TIUI = TypeIdUsers[TypeId];
1153 if (TIUI.IsExported) {
1154 uint8_t *MaskPtr = exportTypeId(cast<MDString>(TypeId)->getString(), TIL);
1156 BAI->MaskPtr = MaskPtr;
1160 for (
CallInst *CI : TIUI.CallSites) {
1161 ++NumTypeTestCallsLowered;
1162 Value *Lowered = lowerTypeTestCall(TypeId, CI, TIL);
1175 if (isa<GlobalVariable>(GO) && GO->
hasSection())
1177 "A member of a type identifier may not have an explicit section");
1194 unsigned LowerTypeTestsModule::getJumpTableEntrySize() {
1211 void LowerTypeTestsModule::createJumpTableEntry(
1215 unsigned ArgIndex = AsmArgs.
size();
1218 AsmOS <<
"jmp ${" << ArgIndex <<
":c}@plt\n";
1219 AsmOS <<
"int3\nint3\nint3\n";
1221 AsmOS <<
"b $" << ArgIndex <<
"\n";
1223 AsmOS <<
"b.w $" << ArgIndex <<
"\n";
1228 ConstraintOS << (ArgIndex > 0 ?
",s" :
"s");
1232 Type *LowerTypeTestsModule::getJumpTableEntryType() {
1238 void LowerTypeTestsModule::buildBitSetsFromFunctions(
1242 buildBitSetsFromFunctionsNative(TypeIds, Functions);
1244 buildBitSetsFromFunctionsWASM(TypeIds, Functions);
1249 void LowerTypeTestsModule::moveInitializerToModuleConstructor(
1251 if (WeakInitializerFn ==
nullptr) {
1256 M.getDataLayout().getProgramAddressSpace(),
1257 "__cfi_global_var_init", &M);
1261 WeakInitializerFn->setSection(
1263 ?
"__TEXT,__StaticInit,regular,pure_instructions" 1270 IRBuilder<> IRB(WeakInitializerFn->getEntryBlock().getTerminator());
1276 void LowerTypeTestsModule::findGlobalVariableUsersOf(
1278 for (
auto *U : C->
users()){
1279 if (
auto *GV = dyn_cast<GlobalVariable>(U))
1281 else if (
auto *C2 = dyn_cast<Constant>(U))
1282 findGlobalVariableUsersOf(C2, Out);
1287 void LowerTypeTestsModule::replaceWeakDeclarationWithJumpTablePtr(
1292 findGlobalVariableUsersOf(F, GlobalVarUsers);
1293 for (
auto GV : GlobalVarUsers)
1294 moveInitializerToModuleConstructor(GV);
1302 replaceCfiUses(F, PlaceholderFn, IsJumpTableCanonical);
1318 if (Feature ==
"-thumb-mode")
1320 else if (Feature ==
"+thumb-mode")
1337 unsigned ArmCount = 0, ThumbCount = 0;
1338 for (
const auto GTM : Functions) {
1339 if (!GTM->isJumpTableCanonical()) {
1346 Function *F = cast<Function>(GTM->getGlobal());
1353 void LowerTypeTestsModule::createJumpTable(
1355 std::string AsmStr, ConstraintStr;
1362 for (
unsigned I = 0;
I != Functions.
size(); ++
I)
1363 createJumpTableEntry(AsmOS, ConstraintOS, JumpTableArch, AsmArgs,
1364 cast<Function>(Functions[
I]->getGlobal()));
1375 F->
addFnAttr(
"target-features",
"-thumb-mode");
1377 F->
addFnAttr(
"target-features",
"+thumb-mode");
1380 F->
addFnAttr(
"target-cpu",
"cortex-a8");
1390 for (
const auto &
Arg : AsmArgs)
1394 AsmOS.str(), ConstraintOS.
str(),
1397 IRB.CreateCall(JumpTableAsm, AsmArgs);
1398 IRB.CreateUnreachable();
1403 void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
1485 unsigned EntrySize = getJumpTableEntrySize();
1486 for (
unsigned I = 0;
I != Functions.
size(); ++
I)
1487 GlobalLayout[Functions[
I]] =
I * EntrySize;
1493 M.getDataLayout().getProgramAddressSpace(),
1494 ".cfi.jumptable", &M);
1500 lowerTypeTestCalls(TypeIds, JumpTable, GlobalLayout);
1503 ScopedSaveAliaseesAndUsed S(M);
1507 for (
unsigned I = 0;
I != Functions.
size(); ++
I) {
1508 Function *F = cast<Function>(Functions[
I]->getGlobal());
1509 bool IsJumpTableCanonical = Functions[
I]->isJumpTableCanonical();
1513 JumpTableType, JumpTable,
1517 if (Functions[
I]->isExported()) {
1518 if (IsJumpTableCanonical) {
1519 ExportSummary->cfiFunctionDefs().insert(F->
getName());
1523 F->
getName() +
".cfi_jt", CombinedGlobalElemPtr, &M);
1525 ExportSummary->cfiFunctionDecls().insert(F->
getName());
1528 if (!IsJumpTableCanonical) {
1530 replaceWeakDeclarationWithJumpTablePtr(F, CombinedGlobalElemPtr,
1531 IsJumpTableCanonical);
1533 replaceCfiUses(F, CombinedGlobalElemPtr, IsJumpTableCanonical);
1539 CombinedGlobalElemPtr, &M);
1541 FAlias->takeName(F);
1542 if (FAlias->hasName())
1543 F->
setName(FAlias->getName() +
".cfi");
1544 replaceCfiUses(F, FAlias, IsJumpTableCanonical);
1551 createJumpTable(JumpTableFn, Functions);
1560 void LowerTypeTestsModule::buildBitSetsFromFunctionsWASM(
1567 for (GlobalTypeMember *GTM : Functions) {
1568 Function *F = cast<Function>(GTM->getGlobal());
1581 GlobalLayout[GTM] = IndirectIndex++;
1590 void LowerTypeTestsModule::buildBitSetsFromDisjointSet(
1594 for (
unsigned I = 0;
I != TypeIds.
size(); ++
I)
1595 TypeIdIndices[TypeIds[
I]] =
I;
1599 std::vector<std::set<uint64_t>> TypeMembers(TypeIds.
size());
1600 unsigned GlobalIndex = 0;
1602 for (GlobalTypeMember *GTM : Globals) {
1603 for (
MDNode *Type : GTM->types()) {
1606 if (
I != TypeIdIndices.
end())
1607 TypeMembers[
I->second].insert(GlobalIndex);
1609 GlobalIndices[GTM] = GlobalIndex;
1613 for (ICallBranchFunnel *JT : ICallBranchFunnels) {
1614 TypeMembers.emplace_back();
1615 std::set<uint64_t> &TMSet = TypeMembers.back();
1616 for (GlobalTypeMember *
T : JT->targets())
1617 TMSet.
insert(GlobalIndices[
T]);
1623 const std::set<uint64_t> &O2) {
1624 return O1.size() < O2.size();
1631 for (
auto &&MemSet : TypeMembers)
1636 Globals.empty() || isa<GlobalVariable>(Globals[0]->getGlobal());
1637 std::vector<GlobalTypeMember *> OrderedGTMs(Globals.size());
1638 auto OGTMI = OrderedGTMs.begin();
1639 for (
auto &&F : GLB.Fragments) {
1640 for (
auto &&
Offset : F) {
1641 if (IsGlobalSet != isa<GlobalVariable>(Globals[
Offset]->getGlobal()))
1643 "variables and functions");
1644 *OGTMI++ = Globals[
Offset];
1650 buildBitSetsFromGlobalVariables(TypeIds, OrderedGTMs);
1652 buildBitSetsFromFunctions(TypeIds, OrderedGTMs);
1656 LowerTypeTestsModule::LowerTypeTestsModule(
1659 : M(M), ExportSummary(ExportSummary), ImportSummary(ImportSummary) {
1660 assert(!(ExportSummary && ImportSummary));
1662 Arch = TargetTriple.
getArch();
1663 OS = TargetTriple.getOS();
1664 ObjectFormat = TargetTriple.getObjectFormat();
1667 bool LowerTypeTestsModule::runForTesting(
Module &M) {
1675 auto ReadSummaryFile =
1678 yaml::Input
In(ReadSummaryFile->getBuffer());
1684 LowerTypeTestsModule(
1696 yaml::Output Out(OS);
1713 void LowerTypeTestsModule::replaceCfiUses(
Function *Old,
Value *New,
1714 bool IsJumpTableCanonical) {
1722 if (isa<BlockAddress>(U.
getUser()))
1731 if (
auto *C = dyn_cast<Constant>(U.
getUser())) {
1732 if (!isa<GlobalValue>(C)) {
1744 for (
auto *C : Constants)
1748 void LowerTypeTestsModule::replaceDirectCalls(
Value *Old,
Value *New) {
1752 bool LowerTypeTestsModule::lower() {
1765 if ((!TypeTestFunc || TypeTestFunc->
use_empty()) &&
1766 (!ICallBranchFunnelFunc || ICallBranchFunnelFunc->
use_empty()) &&
1767 !ExportSummary && !ImportSummary)
1770 if (ImportSummary) {
1774 auto *CI = cast<CallInst>((*UI++).getUser());
1779 if (ICallBranchFunnelFunc && !ICallBranchFunnelFunc->
use_empty())
1781 "unexpected call to llvm.icall.branch.funnel during import phase");
1796 std::vector<GlobalAlias *> AliasesToErase;
1798 ScopedSaveAliaseesAndUsed S(M);
1800 importFunction(F,
true, AliasesToErase);
1801 for (
auto F : Decls)
1802 importFunction(F,
false, AliasesToErase);
1805 GA->eraseFromParent();
1815 GlobalClassesTy GlobalClasses;
1827 std::vector<GlobalTypeMember *> RefGlobals;
1830 unsigned CurUniqueId = 0;
1835 const bool CrossDsoCfi = M.
getModuleFlag(
"Cross-DSO CFI") !=
nullptr;
1837 struct ExportedFunctionInfo {
1842 if (ExportSummary) {
1845 for (
auto &
I : *ExportSummary)
1846 for (
auto &GVS :
I.second.SummaryList)
1848 for (
auto &
Ref : GVS->refs())
1852 if (CfiFunctionsMD) {
1853 for (
auto FuncMD : CfiFunctionsMD->
operands()) {
1854 assert(FuncMD->getNumOperands() >= 2);
1856 cast<MDString>(FuncMD->getOperand(0))->getString();
1858 cast<ConstantAsMetadata>(FuncMD->getOperand(1))
1860 ->getUniqueInteger()
1866 if (!ExportSummary->isGUIDLive(GUID))
1868 if (!AddressTaken.
count(GUID)) {
1872 bool Exported =
false;
1873 if (
auto VI = ExportSummary->getValueInfo(GUID))
1874 for (
auto &GVS :
VI.getSummaryList())
1881 auto P = ExportedFunctions.
insert({FunctionName, {
Linkage, FuncMD}});
1883 P.first->second = {
Linkage, FuncMD};
1886 for (
const auto &
P : ExportedFunctions) {
1889 MDNode *FuncMD =
P.second.FuncMD;
1950 bool IsJumpTableCanonical =
false;
1951 bool IsExported =
false;
1952 if (
Function *F = dyn_cast<Function>(&GO)) {
1955 IsJumpTableCanonical |=
1968 auto *GTM = GlobalTypeMember::create(Alloc, &GO, IsJumpTableCanonical,
1970 GlobalTypeMembers[&GO] = GTM;
1971 for (
MDNode *Type : Types) {
1972 verifyTypeMDNode(&GO, Type);
1974 Info.UniqueId = ++CurUniqueId;
1975 Info.RefGlobals.push_back(GTM);
1979 auto AddTypeIdUse = [&](
Metadata *TypeId) -> TypeIdUserInfo & {
1984 auto Ins = TypeIdUsers.insert({TypeId, {}});
1987 GlobalClassesTy::iterator GCI = GlobalClasses.insert(TypeId);
1988 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
1991 for (GlobalTypeMember *GTM : TypeIdInfo[TypeId].RefGlobals)
1992 CurSet = GlobalClasses.unionSets(
1993 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(GTM)));
1996 return Ins.first->second;
2000 for (
const Use &U : TypeTestFunc->
uses()) {
2001 auto CI = cast<CallInst>(U.getUser());
2006 auto TypeId = TypeIdMDVal->getMetadata();
2007 AddTypeIdUse(TypeId).CallSites.push_back(CI);
2011 if (ICallBranchFunnelFunc) {
2012 for (
const Use &U : ICallBranchFunnelFunc->
uses()) {
2015 "llvm.icall.branch.funnel not supported on this target");
2017 auto CI = cast<CallInst>(U.getUser());
2019 std::vector<GlobalTypeMember *> Targets;
2023 GlobalClassesTy::member_iterator CurSet;
2030 "Expected branch funnel operand to be global value");
2032 GlobalTypeMember *GTM = GlobalTypeMembers[
Base];
2033 Targets.push_back(GTM);
2034 GlobalClassesTy::member_iterator NewSet =
2035 GlobalClasses.findLeader(GlobalClasses.insert(GTM));
2039 CurSet = GlobalClasses.unionSets(CurSet, NewSet);
2042 GlobalClasses.unionSets(
2043 CurSet, GlobalClasses.findLeader(
2044 GlobalClasses.insert(ICallBranchFunnel::create(
2045 Alloc, CI, Targets, ++CurUniqueId))));
2049 if (ExportSummary) {
2051 for (
auto &
P : TypeIdInfo) {
2052 if (
auto *TypeId = dyn_cast<MDString>(
P.first))
2057 for (
auto &
P : *ExportSummary) {
2058 for (
auto &S :
P.second.SummaryList) {
2059 if (!ExportSummary->isGlobalValueLive(S.get()))
2061 if (
auto *
FS = dyn_cast<FunctionSummary>(S->getBaseObject()))
2064 AddTypeIdUse(MD).IsExported =
true;
2069 if (GlobalClasses.empty())
2074 std::vector<std::pair<GlobalClassesTy::iterator, unsigned>> Sets;
2075 for (GlobalClassesTy::iterator
I = GlobalClasses.begin(),
2076 E = GlobalClasses.end();
2080 ++NumTypeIdDisjointSets;
2082 unsigned MaxUniqueId = 0;
2083 for (GlobalClassesTy::member_iterator
MI = GlobalClasses.member_begin(
I);
2084 MI != GlobalClasses.member_end(); ++
MI) {
2086 MaxUniqueId =
std::max(MaxUniqueId, TypeIdInfo[MD].UniqueId);
2087 else if (
auto *BF =
MI->dyn_cast<ICallBranchFunnel *>())
2088 MaxUniqueId =
std::max(MaxUniqueId, BF->UniqueId);
2090 Sets.emplace_back(
I, MaxUniqueId);
2093 [](
const std::pair<GlobalClassesTy::iterator, unsigned> &S1,
2094 const std::pair<GlobalClassesTy::iterator, unsigned> &S2) {
2095 return S1.second < S2.second;
2099 for (
const auto &S : Sets) {
2101 std::vector<Metadata *> TypeIds;
2102 std::vector<GlobalTypeMember *> Globals;
2103 std::vector<ICallBranchFunnel *> ICallBranchFunnels;
2104 for (GlobalClassesTy::member_iterator
MI =
2105 GlobalClasses.member_begin(S.first);
2106 MI != GlobalClasses.member_end(); ++
MI) {
2109 else if (
MI->is<GlobalTypeMember *>())
2110 Globals.push_back(
MI->get<GlobalTypeMember *>());
2112 ICallBranchFunnels.push_back(
MI->get<ICallBranchFunnel *>());
2118 return TypeIdInfo[M1].UniqueId < TypeIdInfo[M2].UniqueId;
2123 [&](ICallBranchFunnel *F1, ICallBranchFunnel *F2) {
2124 return F1->UniqueId < F2->UniqueId;
2128 buildBitSetsFromDisjointSet(TypeIds, Globals, ICallBranchFunnels);
2131 allocateByteArrays();
2135 if (ExportSummary) {
2137 for (
auto AliasMD : AliasesMD->operands()) {
2138 assert(AliasMD->getNumOperands() >= 4);
2140 cast<MDString>(AliasMD->getOperand(0))->getString();
2141 StringRef Aliasee = cast<MDString>(AliasMD->getOperand(1))->getString();
2143 if (!ExportedFunctions.
count(Aliasee) ||
2150 cast<ConstantAsMetadata>(AliasMD->getOperand(2))
2152 ->getUniqueInteger()
2155 static_cast<bool>(cast<ConstantAsMetadata>(AliasMD->getOperand(3))
2157 ->getUniqueInteger()
2170 Alias->setName(AliasName);
2177 if (ExportSummary) {
2179 for (
auto Symver : SymversMD->operands()) {
2180 assert(Symver->getNumOperands() >= 2);
2182 cast<MDString>(Symver->getOperand(0))->getString();
2183 StringRef Alias = cast<MDString>(Symver->getOperand(1))->getString();
2185 if (!ExportedFunctions.
count(SymbolName))
2189 (
llvm::Twine(
".symver ") + SymbolName +
", " + Alias).str());
2199 bool Changed = LowerTypeTestsModule(M, ExportSummary, ImportSummary).lower();
void setVisibility(VisibilityTypes V)
bool isDeclarationForLinker() const
This class implements a layout algorithm for globals referenced by bit sets that tries to keep member...
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getAlignment() const
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static ConstantInt * getFalse(LLVMContext &Context)
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
iterator_range< use_iterator > uses()
This class is used to build a byte array containing overlapping bit sets.
static IntegerType * getInt1Ty(LLVMContext &C)
bool hasLocalLinkage() const
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...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
Type * getElementType(unsigned N) const
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
A Module instance is used to store all the information related to an LLVM module. ...
static cl::opt< bool > AvoidReuse("lowertypetests-avoid-reuse", cl::desc("Try to avoid reuse of byte array addresses using aliases"), cl::Hidden, cl::init(true))
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Unsatisfiable type (i.e. no global has this type metadata)
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
static ConstantAggregateZero * get(Type *Ty)
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.
Helper for check-and-exit error handling.
void print(raw_ostream &OS) const
This class represents a function call, abstracting a target machine's calling convention.
bool hasAvailableExternallyLinkage() const
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
CfiFunctionLinkage
The type of CFI jumptable needed for a function.
Like Internal, but omit from symbol table.
Externally visible function.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
void addOffset(uint64_t Offset)
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
STATISTIC(NumFunctions, "Total number of functions")
const MDOperand & getOperand(unsigned I) const
static IntegerType * getInt64Ty(LLVMContext &C)
bool hasExternalWeakLinkage() const
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Kind
Specifies which kind of type check we should emit for this byte array.
Value * CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name="")
This defines the Use class.
void reserve(size_type N)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
static bool isLocalLinkage(LinkageTypes Linkage)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
bool partiallySplitLTOUnits() const
Export information to summary.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
Value * getArgOperand(unsigned i) const
static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL, Value *V, uint64_t COffset)
unsigned countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
GlobalAlias * getNamedAlias(StringRef Name) const
Return the global alias in the module with the specified name, of arbitrary type. ...
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void initializeLowerTypeTestsPass(PassRegistry &)
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Class to represent struct types.
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
static const unsigned kX86JumpTableEntrySize
The returned value is undefined.
The access may reference the value stored in memory.
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
This file contains the simple types necessary to represent the attributes associated with functions a...
No attributes have been set.
void setName(const Twine &Name)
Change the name of the value.
This file implements a class to represent arbitrary precision integral constant values and operations...
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void appendToUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.used list.
static bool isThumbFunction(Function *F, Triple::ArchType ModuleArch)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
BasicBlock * GetInsertBlock() const
Class to represent array types.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
void setComdat(Comdat *C)
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
INITIALIZE_PASS(LowerTypeTests, "lowertypetests", "Lower type metadata", false, false) ModulePass *llvm
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool containsGlobalOffset(uint64_t Offset) const
static bool isDirectCall(Use &U)
void takeName(Value *V)
Transfer the name from V to this value.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static cl::opt< PassSummaryAction > ClSummaryAction("lowertypetests-summary-action", cl::desc("What to do with the summary when running this pass"), cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), clEnumValN(PassSummaryAction::Import, "import", "Import typeid resolutions from summary and globals"), clEnumValN(PassSummaryAction::Export, "export", "Export typeid resolutions to summary and globals")), cl::Hidden)
iterator_range< op_iterator > operands()
The file should be opened in text mode on platforms that make this distinction.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
void 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...
Value * getOperand(unsigned i) const
Analysis containing CSE Info
Class to represent pointers.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
iterator find(const_arg_type_t< KeyT > Val)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ExternalWeak linkage description.
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
initializer< Ty > init(const Ty &Val)
bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static Triple::ArchType selectJumpTableArmEncoding(ArrayRef< GlobalTypeMember *> Functions, Triple::ArchType ModuleArch)
VisibilityTypes getVisibility() const
Import information from summary.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Allocate memory in an ever growing pool, as if by bump-pointer.
Conditional or Unconditional Branch instruction.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
static ManagedStatic< std::map< const Function *, ExFunc > > ExportedFunctions
void deleteBody()
deleteBody - This method deletes the body of the function, and converts the linkage to external...
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const ValueT &V)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
static Type * getVoidTy(LLVMContext &C)
Single element (last example in "Short Inline Bit Vectors")
ModulePass * createLowerTypeTestsPass(ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
This pass lowers type metadata and the llvm.type.test intrinsic to bitsets.
See the file comment for details on the usage of the TrailingObjects type.
unsigned getAddressSpace() const
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
self_iterator getIterator()
Class to represent integer types.
void setConstant(bool Val)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
const Constant * stripPointerCasts() const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Triple - Helper class for working with autoconf configuration names.
void sort(IteratorTy Start, IteratorTy End)
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
A SetVector that performs no allocations if smaller than a certain size.
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallPtrSetImpl< GlobalValue *> &Set, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
bool hasSection() const
Check if this global has a custom object file section.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
unsigned getProgramAddressSpace() const
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.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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.
static ConstantInt * getTrue(LLVMContext &Context)
void handleOperandChange(Value *, Value *)
This method is a special form of User::replaceUsesOfWith (which does not work on constants) that does...
void setLinkage(LinkageTypes LT)
enum llvm::TypeTestResolution::Kind TheKind
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, Align Alignment)
Allocate space at the specified alignment.
iterator_range< user_iterator > users()
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
std::set< std::string > & cfiFunctionDefs()
Test a byte array (first example)
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
unsigned getNumArgOperands() const
void setAlignment(MaybeAlign Align)
A raw_ostream that writes to a file descriptor.
static IntegerType * getInt32Ty(LLVMContext &C)
Linkage
Describes symbol linkage.
StringRef getValueAsString() const
Return the attribute's value as a string.
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors") ...
StringRef getName() const
Return a constant reference to the value's name.
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList)
Create an "inbounds" getelementptr.
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
bool isJumpTableCanonical(Function *F)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
iterator_range< ifunc_iterator > ifuncs()
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Inlined bit vector ("Short Inline Bit Vectors")
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
static cl::opt< std::string > ClReadSummary("lowertypetests-read-summary", cl::desc("Read summary from given YAML file before running pass"), cl::Hidden)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
user_iterator user_begin()
static Value * createMaskedBitTest(IRBuilder<> &B, Value *Bits, Value *BitOffset)
Build a test that bit BitOffset mod sizeof(Bits)*8 is set in Bits.
void stable_sort(R &&Range)
void addFragment(const std::set< uint64_t > &F)
Add F to the layout while trying to keep its indices contiguous.
A raw_ostream that writes to an std::string.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
This header defines support for implementing classes that have some trailing object (or arrays of obj...
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
static Constant * getAnon(ArrayRef< Constant *> V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
This class implements an extremely fast bulk output stream that can only output to a stream...
static const unsigned kARMJumpTableEntrySize
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
bool hasOneUse() const
Return true if there is exactly one user of this value.
iterator_range< global_object_iterator > global_objects()
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
std::set< uint64_t > Bits
This header defines various interfaces for pass management in LLVM.
static cl::opt< std::string > ClWriteSummary("lowertypetests-write-summary", cl::desc("Write summary to given YAML file after running pass"), cl::Hidden)
unsigned getNumOperands() const
Return number of MDNode operands.
static IntegerType * getInt8Ty(LLVMContext &C)
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...
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
PointerType * getType() const
Global values are always pointers.
bool empty() const
empty - Check if the array is empty.
const BasicBlock * getParent() const
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
iterator_range< alias_iterator > aliases()