92 #define DEBUG_TYPE "wholeprogramdevirt" 95 "wholeprogramdevirt-summary-action",
96 cl::desc(
"What to do with the summary when running this pass"),
99 "Import typeid resolutions from summary and globals"),
101 "Export typeid resolutions to summary and globals")),
105 "wholeprogramdevirt-read-summary",
106 cl::desc(
"Read summary from given YAML file before running pass"),
110 "wholeprogramdevirt-write-summary",
111 cl::desc(
"Write summary to given YAML file after running pass"),
117 cl::desc(
"Maximum number of call targets per " 118 "call site to enable branch funnels"));
125 bool IsAfter, uint64_t
Size) {
127 uint64_t MinByte = 0;
155 std::vector<ArrayRef<uint8_t>> Used;
158 :
Target.TM->Bits->Before.BytesUsed;
159 uint64_t
Offset = IsAfter ? MinByte -
Target.minAfterBytes()
160 : MinByte -
Target.minBeforeBytes();
165 Used.push_back(VTUsed.
slice(Offset));
170 for (
unsigned I = 0;; ++
I) {
171 uint8_t BitsUsed = 0;
172 for (
auto &&
B : Used)
175 if (BitsUsed != 0xff)
176 return (MinByte +
I) * 8 +
182 for (
unsigned I = 0;; ++
I) {
183 for (
auto &&
B : Used) {
185 while ((
I + Byte) <
B.size() && Byte < (Size / 8)) {
191 return (MinByte +
I) * 8;
199 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
201 OffsetByte = -(AllocBefore / 8 + 1);
203 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
204 OffsetBit = AllocBefore % 8;
208 Target.setBeforeBit(AllocBefore);
210 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
216 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
218 OffsetByte = AllocAfter / 8;
220 OffsetByte = (AllocAfter + 7) / 8;
221 OffsetBit = AllocAfter % 8;
225 Target.setAfterBit(AllocAfter);
227 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
233 IsBigEndian(Fn->
getParent()->getDataLayout().isBigEndian()), WasDevirt(
false) {}
263 const VTableSlot &RHS) {
264 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
274 struct VirtualCallSite {
281 unsigned *NumUnsafeUses;
292 <<
NV(
"Optimization", OptName)
293 <<
": devirtualized a call to " 294 <<
NV(
"FunctionName", TargetName));
297 void replaceAndErase(
302 emitRemark(OptName, TargetName, OREGetter);
303 CS->replaceAllUsesWith(New);
306 II->getUnwindDest()->removePredecessor(II->getParent());
308 CS->eraseFromParent();
318 struct CallSiteInfo {
323 std::vector<VirtualCallSite> CallSites;
328 bool AllCallSitesDevirted =
true;
335 bool SummaryHasTypeTestAssumeUsers =
false;
344 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
346 bool isExported()
const {
347 return SummaryHasTypeTestAssumeUsers ||
348 !SummaryTypeCheckedLoadUsers.empty();
351 void markSummaryHasTypeTestAssumeUsers() {
352 SummaryHasTypeTestAssumeUsers =
true;
353 AllCallSitesDevirted =
false;
357 SummaryTypeCheckedLoadUsers.push_back(FS);
358 AllCallSitesDevirted =
false;
362 AllCallSitesDevirted =
true;
365 SummaryTypeCheckedLoadUsers.clear();
370 struct VTableSlotInfo {
377 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
379 void addCallSite(
Value *VTable,
CallSite CS,
unsigned *NumUnsafeUses);
382 CallSiteInfo &findCallSiteInfo(
CallSite CS);
385 CallSiteInfo &VTableSlotInfo::findCallSiteInfo(
CallSite CS) {
386 std::vector<uint64_t>
Args;
388 if (!CI || CI->getBitWidth() > 64 || CS.
arg_empty())
392 if (!CI || CI->getBitWidth() > 64)
394 Args.push_back(CI->getZExtValue());
396 return ConstCSInfo[
Args];
400 unsigned *NumUnsafeUses) {
401 auto &CSI = findCallSiteInfo(CS);
402 CSI.AllCallSitesDevirted =
false;
403 CSI.CallSites.push_back({VTable, CS, NumUnsafeUses});
406 struct DevirtModule {
432 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
438 : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
444 RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
445 assert(!(ExportSummary && ImportSummary));
448 bool areRemarksEnabled();
451 void scanTypeCheckedLoadUsers(
Function *TypeCheckedLoadFunc);
453 void buildTypeIdentifierMap(
454 std::vector<VTableBits> &
Bits,
458 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
459 const std::set<TypeMemberInfo> &TypeMemberInfos,
460 uint64_t ByteOffset);
462 void applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Constant *TheFn,
465 VTableSlotInfo &SlotInfo,
468 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
Constant *
JT,
471 VTableSlotInfo &SlotInfo,
474 bool tryEvaluateFunctionsWithArgs(
478 void applyUniformRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
481 CallSiteInfo &CSInfo,
489 bool shouldExportConstantsAsAbsoluteSymbols();
509 void applyUniqueRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
bool IsOne,
511 bool tryUniqueRetValOpt(
unsigned BitWidth,
513 CallSiteInfo &CSInfo,
517 void applyVirtualConstProp(CallSiteInfo &CSInfo,
StringRef FnName,
520 VTableSlotInfo &SlotInfo,
526 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
530 void removeRedundantTypeTests();
536 static bool runForTesting(
541 struct WholeProgramDevirt :
public ModulePass {
544 bool UseCommandLine =
false;
549 WholeProgramDevirt() :
ModulePass(ID), UseCommandLine(
true) {
555 :
ModulePass(ID), ExportSummary(ExportSummary),
556 ImportSummary(ImportSummary) {
560 bool runOnModule(
Module &M)
override {
569 std::unique_ptr<OptimizationRemarkEmitter> ORE;
571 ORE = make_unique<OptimizationRemarkEmitter>(
F);
576 return DevirtModule::runForTesting(M,
LegacyAARGetter(*
this), OREGetter);
578 return DevirtModule(M,
LegacyAARGetter(*
this), OREGetter, ExportSummary,
592 "Whole program devirtualization",
false,
false)
597 char WholeProgramDevirt::
ID = 0;
602 return new WholeProgramDevirt(ExportSummary, ImportSummary);
614 if (!DevirtModule(M, AARGetter, OREGetter, ExportSummary, ImportSummary)
620 bool DevirtModule::runForTesting(
630 auto ReadSummaryFile =
633 yaml::Input
In(ReadSummaryFile->getBuffer());
640 M, AARGetter, OREGetter,
652 yaml::Output Out(OS);
659 void DevirtModule::buildTypeIdentifierMap(
660 std::vector<VTableBits> &
Bits,
674 Bits.back().GV = &GV;
675 Bits.back().ObjectSize =
677 BitsPtr = &Bits.back();
685 cast<ConstantAsMetadata>(
Type->getOperand(0))->getValue())
688 TypeIdMap[
TypeID].insert({BitsPtr, Offset});
702 if (
auto *
C = dyn_cast<ConstantStruct>(I)) {
708 return getPointerAtOffset(cast<Constant>(I->
getOperand(Op)),
711 if (
auto *
C = dyn_cast<ConstantArray>(I)) {
715 unsigned Op = Offset / ElemSize;
719 return getPointerAtOffset(cast<Constant>(I->
getOperand(Op)),
725 bool DevirtModule::tryFindVirtualCallTargets(
726 std::vector<VirtualCallTarget> &TargetsForSlot,
727 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
743 if (
Fn->
getName() ==
"__cxa_pure_virtual")
746 TargetsForSlot.push_back({
Fn, &
TM});
750 return !TargetsForSlot.
empty();
753 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
754 Constant *TheFn,
bool &IsExported) {
755 auto Apply = [&](CallSiteInfo &CSInfo) {
756 for (
auto &&VCallSite : CSInfo.CallSites) {
758 VCallSite.emitRemark(
"single-impl", TheFn->
getName(), OREGetter);
760 TheFn, VCallSite.CS.getCalledValue()->
getType()));
762 if (VCallSite.NumUnsafeUses)
763 --*VCallSite.NumUnsafeUses;
765 if (CSInfo.isExported())
769 Apply(SlotInfo.CSInfo);
770 for (
auto &
P : SlotInfo.ConstCSInfo)
774 bool DevirtModule::trySingleImplDevirt(
779 Function *TheFn = TargetsForSlot[0].Fn;
780 for (
auto &&
Target : TargetsForSlot)
786 TargetsForSlot[0].WasDevirt =
true;
788 bool IsExported =
false;
789 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
797 std::string NewName = (TheFn->
getName() +
"$merged").str();
807 if (GO.getComdat() ==
C)
823 void DevirtModule::tryICallBranchFunnel(
833 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
835 for (
auto &
P : SlotInfo.ConstCSInfo)
836 if (!
P.second.AllCallSitesDevirted) {
847 if (isa<MDString>(Slot.TypeID)) {
849 getGlobalName(Slot, {},
"branch_funnel"), &M);
854 JT->addAttribute(1, Attribute::Nest);
856 std::vector<Value *> JTArgs;
857 JTArgs.push_back(JT->arg_begin());
858 for (
auto &
T : TargetsForSlot) {
859 JTArgs.push_back(getMemberAddr(
T.TM));
860 JTArgs.push_back(
T.Fn);
871 bool IsExported =
false;
872 applyICallBranchFunnel(SlotInfo, JT, IsExported);
877 void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
879 auto Apply = [&](CallSiteInfo &CSInfo) {
880 if (CSInfo.isExported())
882 if (CSInfo.AllCallSitesDevirted)
884 for (
auto &&VCallSite : CSInfo.CallSites) {
894 VCallSite.emitRemark(
"branch-funnel", JT->
getName(), OREGetter);
898 std::vector<Type *> NewArgs;
899 NewArgs.push_back(Int8PtrTy);
901 NewArgs.push_back(
T);
907 std::vector<Value *>
Args;
908 Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
914 NewCS = IRB.CreateCall(IRB.CreateBitCast(JT, NewFT),
Args);
916 NewCS = IRB.CreateInvoke(
917 IRB.CreateBitCast(JT, NewFT),
923 std::vector<AttributeSet> NewArgAttrs;
934 CS->eraseFromParent();
937 if (VCallSite.NumUnsafeUses)
938 --*VCallSite.NumUnsafeUses;
945 Apply(SlotInfo.CSInfo);
946 for (
auto &
P : SlotInfo.ConstCSInfo)
950 bool DevirtModule::tryEvaluateFunctionsWithArgs(
963 for (
unsigned I = 0; I != Args.
size(); ++
I) {
965 Target.Fn->getFunctionType()->getParamType(I + 1));
972 if (!Eval.EvaluateFunction(
Target.Fn, RetVal, EvalArgs) ||
973 !isa<ConstantInt>(
RetVal))
975 Target.RetVal = cast<ConstantInt>(
RetVal)->getZExtValue();
980 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
981 uint64_t TheRetVal) {
982 for (
auto Call : CSInfo.CallSites)
983 Call.replaceAndErase(
984 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
989 bool DevirtModule::tryUniformRetValOpt(
994 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
996 if (
Target.RetVal != TheRetVal)
999 if (CSInfo.isExported()) {
1001 Res->
Info = TheRetVal;
1004 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].
Fn->
getName(), TheRetVal);
1006 for (
auto &&
Target : TargetsForSlot)
1011 std::string DevirtModule::getGlobalName(VTableSlot Slot,
1014 std::string FullName =
"__typeid_";
1016 OS << cast<MDString>(Slot.TypeID)->getString() <<
'_' << Slot.ByteOffset;
1017 for (uint64_t
Arg : Args)
1023 bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1032 getGlobalName(Slot, Args, Name), C, &M);
1039 if (shouldExportConstantsAsAbsoluteSymbols()) {
1061 if (!shouldExportConstantsAsAbsoluteSymbols())
1064 Constant *C = importGlobal(Slot, Args, Name);
1073 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1080 if (AbsWidth == IntPtrTy->getBitWidth())
1081 SetAbsRange(~0ull, ~0ull);
1083 SetAbsRange(0, 1ull << AbsWidth);
1087 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
1090 for (
auto &&Call : CSInfo.CallSites) {
1094 B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
1095 Cmp =
B.CreateZExt(Cmp, Call.CS->getType());
1096 Call.replaceAndErase(
"unique-ret-val", FnName, RemarksEnabled, OREGetter,
1099 CSInfo.markDevirt();
1108 bool DevirtModule::tryUniqueRetValOpt(
1113 auto tryUniqueRetValOptFor = [&](
bool IsOne) {
1116 if (
Target.RetVal == (IsOne ? 1 : 0)) {
1119 UniqueMember =
Target.TM;
1127 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
1128 if (CSInfo.isExported()) {
1132 exportGlobal(Slot, Args,
"unique_member", UniqueMemberAddr);
1136 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].
Fn->
getName(), IsOne,
1141 for (
auto &&
Target : TargetsForSlot)
1147 if (BitWidth == 1) {
1148 if (tryUniqueRetValOptFor(
true))
1150 if (tryUniqueRetValOptFor(
false))
1156 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo,
StringRef FnName,
1158 for (
auto Call : CSInfo.CallSites) {
1159 auto *RetType = cast<IntegerType>(Call.CS.getType());
1162 B.CreateGEP(Int8Ty,
B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
1163 if (RetType->getBitWidth() == 1) {
1164 Value *Bits =
B.CreateLoad(Addr);
1165 Value *BitsAndBit =
B.CreateAnd(Bits, Bit);
1167 Call.replaceAndErase(
"virtual-const-prop-1-bit", FnName, RemarksEnabled,
1168 OREGetter, IsBitSet);
1170 Value *ValAddr =
B.CreateBitCast(Addr, RetType->getPointerTo());
1171 Value *Val =
B.CreateLoad(RetType, ValAddr);
1172 Call.replaceAndErase(
"virtual-const-prop", FnName, RemarksEnabled,
1176 CSInfo.markDevirt();
1179 bool DevirtModule::tryVirtualConstProp(
1186 unsigned BitWidth = RetType->getBitWidth();
1201 if (
Target.Fn->isDeclaration() ||
1204 Target.Fn->arg_empty() || !
Target.Fn->arg_begin()->use_empty() ||
1205 Target.Fn->getReturnType() != RetType)
1209 for (
auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
1210 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1215 ResByArg = &Res->
ResByArg[CSByConstantArg.first];
1217 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
1220 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1221 ResByArg, Slot, CSByConstantArg.first))
1226 uint64_t AllocBefore =
1228 uint64_t AllocAfter =
1233 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1234 for (
auto &&
Target : TargetsForSlot) {
1235 TotalPaddingBefore += std::max<int64_t>(
1236 (AllocBefore + 7) / 8 -
Target.allocatedBeforeBytes() - 1, 0);
1237 TotalPaddingAfter += std::max<int64_t>(
1238 (AllocAfter + 7) / 8 -
Target.allocatedAfterBytes() - 1, 0);
1243 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1250 if (TotalPaddingBefore <= TotalPaddingAfter)
1258 for (
auto &&
Target : TargetsForSlot)
1262 if (CSByConstantArg.second.isExported()) {
1264 exportConstant(Slot, CSByConstantArg.first,
"byte", OffsetByte,
1266 exportConstant(Slot, CSByConstantArg.first,
"bit", 1ULL << OffsetBit,
1273 applyVirtualConstProp(CSByConstantArg.second,
1274 TargetsForSlot[0].Fn->
getName(), ByteConst, BitConst);
1284 unsigned PointerSize = M.getDataLayout().getPointerSize();
1313 NewInit->getType(), NewGV,
1318 Alias->takeName(B.
GV);
1324 bool DevirtModule::areRemarksEnabled() {
1325 const auto &FL = M.getFunctionList();
1337 void DevirtModule::scanTypeTestUsers(
Function *TypeTestFunc,
1360 if (!Assumes.
empty()) {
1362 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1363 Value *
Ptr = CI->getArgOperand(0)->stripPointerCasts();
1364 if (SeenPtrs.
insert(Ptr).second) {
1366 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
nullptr);
1372 for (
auto Assume : Assumes)
1373 Assume->eraseFromParent();
1376 if (CI->use_empty())
1377 CI->eraseFromParent();
1381 void DevirtModule::scanTypeCheckedLoadUsers(
Function *TypeCheckedLoadFunc) {
1384 for (
auto I = TypeCheckedLoadFunc->
use_begin(),
1385 E = TypeCheckedLoadFunc->
use_end();
1393 Value *Offset = CI->getArgOperand(1);
1394 Value *TypeIdValue = CI->getArgOperand(2);
1395 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1400 bool HasNonCallUses =
false;
1402 HasNonCallUses, CI);
1411 (LoadedPtrs.
size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1418 LoadedPtr->eraseFromParent();
1422 IRBuilder<> CallB((Preds.
size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1427 Pred->eraseFromParent();
1434 if (!CI->use_empty()) {
1437 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1438 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1443 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1444 NumUnsafeUses = DevirtCalls.
size();
1452 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1456 CI->eraseFromParent();
1460 void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
1462 ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
1465 auto ResI = TidSummary->
WPDRes.find(Slot.ByteOffset);
1466 if (ResI == TidSummary->
WPDRes.end())
1473 auto *SingleImpl = M.getOrInsertFunction(
1477 bool IsExported =
false;
1478 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1482 for (
auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1483 auto I = Res.
ResByArg.find(CSByConstantArg.first);
1486 auto &ResByArg = I->second;
1491 switch (ResByArg.TheKind) {
1493 applyUniformRetValOpt(CSByConstantArg.second,
"", ResByArg.Info);
1497 importGlobal(Slot, CSByConstantArg.first,
"unique_member");
1498 applyUniqueRetValOpt(CSByConstantArg.second,
"", ResByArg.Info,
1503 Constant *Byte = importConstant(Slot, CSByConstantArg.first,
"byte",
1505 Constant *Bit = importConstant(Slot, CSByConstantArg.first,
"bit", Int8Ty,
1507 applyVirtualConstProp(CSByConstantArg.second,
"", Byte, Bit);
1516 auto *JT = M.getOrInsertFunction(getGlobalName(Slot, {},
"branch_funnel"),
1518 bool IsExported =
false;
1519 applyICallBranchFunnel(SlotInfo, JT, IsExported);
1524 void DevirtModule::removeRedundantTypeTests() {
1526 for (
auto &&U : NumUnsafeUsesForTypeTest) {
1527 if (U.second == 0) {
1529 U.first->eraseFromParent();
1534 bool DevirtModule::run() {
1544 if (!ExportSummary &&
1545 (!TypeTestFunc || TypeTestFunc->
use_empty() || !AssumeFunc ||
1547 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->
use_empty()))
1550 if (TypeTestFunc && AssumeFunc)
1551 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1553 if (TypeCheckedLoadFunc)
1554 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
1556 if (ImportSummary) {
1557 for (
auto &S : CallSlots)
1558 importResolution(S.first, S.second);
1560 removeRedundantTypeTests();
1568 std::vector<VTableBits>
Bits;
1570 buildTypeIdentifierMap(Bits, TypeIdMap);
1571 if (TypeIdMap.
empty())
1575 if (ExportSummary) {
1577 for (
auto &
P : TypeIdMap) {
1578 if (
auto *TypeId = dyn_cast<MDString>(
P.first))
1583 for (
auto &
P : *ExportSummary) {
1584 for (
auto &S :
P.second.SummaryList) {
1590 for (
Metadata *MD : MetadataByGUID[VF.GUID]) {
1591 CallSlots[{MD, VF.Offset}]
1592 .CSInfo.markSummaryHasTypeTestAssumeUsers();
1596 for (
Metadata *MD : MetadataByGUID[VF.GUID]) {
1597 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
1601 FS->type_test_assume_const_vcalls()) {
1602 for (
Metadata *MD : MetadataByGUID[
VC.VFunc.GUID]) {
1603 CallSlots[{MD,
VC.VFunc.Offset}]
1604 .ConstCSInfo[
VC.Args]
1605 .markSummaryHasTypeTestAssumeUsers();
1609 FS->type_checked_load_const_vcalls()) {
1610 for (
Metadata *MD : MetadataByGUID[
VC.VFunc.GUID]) {
1611 CallSlots[{MD,
VC.VFunc.Offset}]
1612 .ConstCSInfo[
VC.Args]
1613 .addSummaryTypeCheckedLoadUser(FS);
1621 bool DidVirtualConstProp =
false;
1622 std::map<std::string, Function*> DevirtTargets;
1623 for (
auto &S : CallSlots) {
1627 std::vector<VirtualCallTarget> TargetsForSlot;
1628 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1629 S.first.ByteOffset)) {
1631 if (ExportSummary && isa<MDString>(S.first.TypeID))
1632 Res = &ExportSummary
1633 ->getOrInsertTypeIdSummary(
1634 cast<MDString>(S.first.TypeID)->getString())
1635 .WPDRes[S.first.ByteOffset];
1637 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res)) {
1638 DidVirtualConstProp |=
1639 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
1641 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
1646 for (
const auto &
T : TargetsForSlot)
1648 DevirtTargets[
T.Fn->getName()] =
T.Fn;
1655 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
1658 for (
auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1659 FS->addTypeTest(GUID);
1660 for (
auto &CCS : S.second.ConstCSInfo)
1661 for (
auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1662 FS->addTypeTest(GUID);
1666 if (RemarksEnabled) {
1668 for (
const auto &DT : DevirtTargets) {
1671 using namespace ore;
1678 removeRedundantTypeTests();
1682 if (DidVirtualConstProp)
void setVisibility(VisibilityTypes V)
StringRef getSection() const
Get the custom section of this global if it has one.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
bool hasLocalLinkage() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
DiagnosticInfoOptimizationBase::Argument NV
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
Whole program devirtualization
static unsigned getHashValue(const VTableSlot &I)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Compute iterated dominance frontiers using a linear time algorithm.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
Helper for check-and-exit error handling.
void initializeWholeProgramDevirtPass(PassRegistry &)
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
An efficient, type-erasing, non-owning reference to a callable.
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
uint64_t Info
Additional information for the resolution:
Like Internal, but omit from symbol table.
Externally visible function.
static cl::opt< unsigned > ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden, cl::init(10), cl::ZeroOrMore, cl::desc("Maximum number of call targets per " "call site to enable branch funnels"))
This class implements a map that also provides access to all stored values in a deterministic order...
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
static IntegerType * getInt64Ty(LLVMContext &C)
MemoryAccessKind computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
Virtual constant propagation.
void setAfterReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocAfter, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair...
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Export information to summary.
const char * getName() const
getName - Get the target name.
iterator_range< global_object_iterator > global_objects()
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
void setBeforeReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocBefore, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
void findDevirtualizableCallsForTypeTest(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< CallInst *> &Assumes, const CallInst *CI)
Given a call to the intrinsic @llvm.type.test, find all devirtualizable call sites based on the call ...
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
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.
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module...
LLVMContext & getContext() const
Get the global data context.
The returned value is undefined.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This class is a functor to be used in legacy module or SCC passes for computing AA results for a func...
No attributes have been set.
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
InstrTy * getInstruction() const
void setName(const Twine &Name)
Change the name of the value.
static bool isEqual(const VTableSlot &LHS, const VTableSlot &RHS)
enum llvm::WholeProgramDevirtResolution::Kind TheKind
Uniform return value optimization.
static VTableSlot getTombstoneKey()
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
ValTy * getArgOperand(unsigned i) const
Class to represent array types.
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
LinkageTypes getLinkage() const
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
Class to represent pointers.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
bool isCall() const
Return true if a CallInst is enclosed.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of converting the string to 'bool' fo...
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)
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
initializer< Ty > init(const Ty &Val)
unsigned getNumOperands() const
bool hasAttribute(AttrKind Val) const
Return true if the attribute is present.
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.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
std::size_t 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...
VisibilityTypes getVisibility() const
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Import information from summary.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
A call site that could be devirtualized.
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
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 ...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt", "Whole program devirtualization", false, false) INITIALIZE_PASS_END(WholeProgramDevirt
ArrayRef< Type * > params() const
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again...
Class to represent integer types.
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Constant * stripPointerCasts() const
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
unsigned getNumArgOperands() const
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Triple - Helper class for working with autoconf configuration names.
An "identifier" for a virtual function.
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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.
void setSelectionKind(SelectionKind Val)
void findDevirtualizableCallsForTypeCheckedLoad(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< Instruction *> &LoadedPtrs, SmallVectorImpl< Instruction *> &Preds, bool &HasNonCallUses, const CallInst *CI)
Given a call to the intrinsic @llvm.type.checked.load, find all devirtualizable call sites based on t...
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.
Single implementation devirtualization.
Type * getReturnType() const
uint64_t getSizeInBytes() 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)
static ConstantInt * getTrue(LLVMContext &Context)
BBTy * getParent() const
Get the basic block containing the call site.
void setLinkage(LinkageTypes LT)
std::string SingleImplName
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Target - Wrapper for Target specific information.
unsigned getNumAttrSets() const
A specification for a virtual function call with all constant integer arguments.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
amdgpu Simplify well known AMD library false Value Value * Arg
const Comdat * getComdat() const
ModulePass * createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
This pass implements whole-program devirtualization using type metadata.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::vector< uint8_t > Bytes
FunTy * getCaller() const
Return the caller function for this call site.
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument, "this"), where the key is the argument vector.
A raw_ostream that writes to a file descriptor.
uint64_t getElementOffset(unsigned Idx) const
static IntegerType * getInt32Ty(LLVMContext &C)
uint64_t findLowestOffset(ArrayRef< VirtualCallTarget > Targets, bool IsAfter, uint64_t Size)
LLVM_NODISCARD bool empty() const
StringRef getValueAsString() const
Return the attribute's value as a string.
StringRef getName() const
Return a constant reference to the value's name.
static VTableSlot getEmptyKey()
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
Rename collisions when linking (static functions).
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
Provides passes for computing function attributes based on interprocedural analyses.
Function summary information to aid decisions and implementation of importing.
LLVM_NODISCARD bool empty() const
Type * getType() const
Return the type of the instruction that generated this call site.
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.
static cl::opt< PassSummaryAction > ClSummaryAction("wholeprogramdevirt-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)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
A raw_ostream that writes to an std::string.
LLVM Value Representation.
FunctionType * getFunctionType() const
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static const Function * getParent(const Value *V)
AttributeSet getFnAttributes() const
The function attributes are returned.
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.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
const TypeMemberInfo * TM
Type * getElementType() const
iterator_range< global_iterator > globals()
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
static cl::opt< std::string > ClReadSummary("wholeprogramdevirt-read-summary", cl::desc("Read summary from given YAML file before running pass"), cl::Hidden)
static cl::opt< std::string > ClWriteSummary("wholeprogramdevirt-write-summary", cl::desc("Write summary to given YAML file after running pass"), cl::Hidden)
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
AttributeList getAttributes() const
Get the parameter attributes of the call.
static IntegerType * getInt8Ty(LLVMContext &C)
void setSection(StringRef S)
Change the section for this global.
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...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
Unique return value optimization.
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...