93 #define DEBUG_TYPE "wholeprogramdevirt"
96 "wholeprogramdevirt-summary-action",
97 cl::desc(
"What to do with the summary when running this pass"),
100 "Import typeid resolutions from summary and globals"),
102 "Export typeid resolutions to summary and globals")),
106 "wholeprogramdevirt-read-summary",
107 cl::desc(
"Read summary from given YAML file before running pass"),
111 "wholeprogramdevirt-write-summary",
112 cl::desc(
"Write summary to given YAML file after running pass"),
120 bool IsAfter, uint64_t
Size) {
122 uint64_t MinByte = 0;
150 std::vector<ArrayRef<uint8_t>> Used;
153 :
Target.TM->Bits->Before.BytesUsed;
154 uint64_t
Offset = IsAfter ? MinByte -
Target.minAfterBytes()
155 : MinByte -
Target.minBeforeBytes();
160 Used.push_back(VTUsed.
slice(Offset));
165 for (
unsigned I = 0;; ++
I) {
166 uint8_t BitsUsed = 0;
167 for (
auto &&
B : Used)
170 if (BitsUsed != 0xff)
171 return (MinByte +
I) * 8 +
177 for (
unsigned I = 0;; ++
I) {
178 for (
auto &&
B : Used) {
180 while ((
I + Byte) <
B.size() && Byte < (Size / 8)) {
186 return (MinByte +
I) * 8;
194 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
196 OffsetByte = -(AllocBefore / 8 + 1);
198 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
199 OffsetBit = AllocBefore % 8;
203 Target.setBeforeBit(AllocBefore);
205 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
211 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
213 OffsetByte = AllocAfter / 8;
215 OffsetByte = (AllocAfter + 7) / 8;
216 OffsetBit = AllocAfter % 8;
220 Target.setAfterBit(AllocAfter);
222 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
228 IsBigEndian(Fn->
getParent()->getDataLayout().isBigEndian()), WasDevirt(
false) {}
258 const VTableSlot &RHS) {
259 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
269 struct VirtualCallSite {
276 unsigned *NumUnsafeUses;
278 void emitRemark(
const Twine &OptName,
const Twine &TargetName) {
282 CS.getInstruction()->getDebugLoc(),
283 OptName +
": devirtualized a call to " + TargetName);
286 void replaceAndErase(
const Twine &OptName,
const Twine &TargetName,
287 bool RemarksEnabled,
Value *New) {
289 emitRemark(OptName, TargetName);
290 CS->replaceAllUsesWith(New);
291 if (
auto II = dyn_cast<InvokeInst>(
CS.getInstruction())) {
293 II->getUnwindDest()->removePredecessor(II->getParent());
295 CS->eraseFromParent();
305 struct CallSiteInfo {
310 std::vector<VirtualCallSite> CallSites;
317 bool SummaryHasTypeTestAssumeUsers;
326 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
328 bool isExported()
const {
329 return SummaryHasTypeTestAssumeUsers ||
330 !SummaryTypeCheckedLoadUsers.empty();
334 void markDevirt() { SummaryTypeCheckedLoadUsers.clear(); }
338 struct VTableSlotInfo {
345 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
347 void addCallSite(
Value *VTable,
CallSite CS,
unsigned *NumUnsafeUses);
350 CallSiteInfo &findCallSiteInfo(
CallSite CS);
353 CallSiteInfo &VTableSlotInfo::findCallSiteInfo(
CallSite CS) {
354 std::vector<uint64_t>
Args;
356 if (!CI || CI->getBitWidth() > 64 || CS.
arg_empty())
360 if (!CI || CI->getBitWidth() > 64)
362 Args.push_back(CI->getZExtValue());
364 return ConstCSInfo[
Args];
368 unsigned *NumUnsafeUses) {
369 findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
372 struct DevirtModule {
397 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
402 : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
403 ImportSummary(ImportSummary), Int8Ty(
Type::getInt8Ty(M.getContext())),
404 Int8PtrTy(
Type::getInt8PtrTy(M.getContext())),
406 Int64Ty(
Type::getInt64Ty(M.getContext())),
407 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
408 RemarksEnabled(areRemarksEnabled()) {
409 assert(!(ExportSummary && ImportSummary));
412 bool areRemarksEnabled();
415 void scanTypeCheckedLoadUsers(
Function *TypeCheckedLoadFunc);
417 void buildTypeIdentifierMap(
418 std::vector<VTableBits> &
Bits,
422 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
423 const std::set<TypeMemberInfo> &TypeMemberInfos,
424 uint64_t ByteOffset);
426 void applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Constant *TheFn,
429 VTableSlotInfo &SlotInfo,
432 bool tryEvaluateFunctionsWithArgs(
436 void applyUniformRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
439 CallSiteInfo &CSInfo,
458 void applyUniqueRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
bool IsOne,
460 bool tryUniqueRetValOpt(
unsigned BitWidth,
462 CallSiteInfo &CSInfo,
466 void applyVirtualConstProp(CallSiteInfo &CSInfo,
StringRef FnName,
469 VTableSlotInfo &SlotInfo,
475 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
479 void removeRedundantTypeTests();
485 static bool runForTesting(
Module &M,
489 struct WholeProgramDevirt :
public ModulePass {
492 bool UseCommandLine =
false;
504 ImportSummary(ImportSummary) {
508 bool runOnModule(
Module &M)
override {
513 return DevirtModule(M,
LegacyAARGetter(*
this), ExportSummary, ImportSummary)
526 "Whole program devirtualization",
false,
false)
531 char WholeProgramDevirt::
ID = 0;
536 return new WholeProgramDevirt(ExportSummary, ImportSummary);
545 if (!DevirtModule(M, AARGetter,
nullptr,
nullptr).run())
550 bool DevirtModule::runForTesting(
559 auto ReadSummaryFile =
588 void DevirtModule::buildTypeIdentifierMap(
589 std::vector<VTableBits> &
Bits,
603 Bits.back().GV = &GV;
604 Bits.back().ObjectSize =
606 BitsPtr = &Bits.back();
614 cast<ConstantAsMetadata>(
Type->getOperand(0))->getValue())
617 TypeIdMap[
TypeID].insert({BitsPtr, Offset});
631 if (
auto *
C = dyn_cast<ConstantStruct>(I)) {
637 return getPointerAtOffset(cast<Constant>(I->
getOperand(Op)),
640 if (
auto *
C = dyn_cast<ConstantArray>(I)) {
644 unsigned Op = Offset / ElemSize;
645 if (Op >=
C->getNumOperands())
648 return getPointerAtOffset(cast<Constant>(I->
getOperand(Op)),
654 bool DevirtModule::tryFindVirtualCallTargets(
655 std::vector<VirtualCallTarget> &TargetsForSlot,
656 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
658 if (!
TM.Bits->GV->isConstant())
661 Constant *
Ptr = getPointerAtOffset(
TM.Bits->GV->getInitializer(),
662 TM.Offset + ByteOffset);
672 if (Fn->getName() ==
"__cxa_pure_virtual")
675 TargetsForSlot.push_back({Fn, &
TM});
679 return !TargetsForSlot.
empty();
682 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
683 Constant *TheFn,
bool &IsExported) {
684 auto Apply = [&](CallSiteInfo &CSInfo) {
685 for (
auto &&VCallSite : CSInfo.CallSites) {
687 VCallSite.emitRemark(
"single-impl", TheFn->
getName());
689 TheFn, VCallSite.CS.getCalledValue()->
getType()));
691 if (VCallSite.NumUnsafeUses)
692 --*VCallSite.NumUnsafeUses;
694 if (CSInfo.isExported()) {
699 Apply(SlotInfo.CSInfo);
700 for (
auto &
P : SlotInfo.ConstCSInfo)
704 bool DevirtModule::trySingleImplDevirt(
709 Function *TheFn = TargetsForSlot[0].Fn;
710 for (
auto &&
Target : TargetsForSlot)
716 TargetsForSlot[0].WasDevirt =
true;
718 bool IsExported =
false;
719 applySingleImplDevirt(SlotInfo, TheFn, IsExported);
738 bool DevirtModule::tryEvaluateFunctionsWithArgs(
751 for (
unsigned I = 0; I != Args.
size(); ++
I) {
753 Target.Fn->getFunctionType()->getParamType(I + 1));
760 if (!Eval.EvaluateFunction(
Target.Fn, RetVal, EvalArgs) ||
761 !isa<ConstantInt>(RetVal))
763 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
768 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
769 uint64_t TheRetVal) {
770 for (
auto Call : CSInfo.CallSites)
771 Call.replaceAndErase(
772 "uniform-ret-val", FnName, RemarksEnabled,
777 bool DevirtModule::tryUniformRetValOpt(
782 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
784 if (
Target.RetVal != TheRetVal)
787 if (CSInfo.isExported()) {
789 Res->
Info = TheRetVal;
792 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
794 for (
auto &&
Target : TargetsForSlot)
799 std::string DevirtModule::getGlobalName(VTableSlot Slot,
802 std::string FullName =
"__typeid_";
804 OS << cast<MDString>(Slot.TypeID)->getString() <<
'_' << Slot.ByteOffset;
805 for (uint64_t Arg : Args)
814 getGlobalName(Slot, Args, Name), C, &M);
828 auto SetAbsRange = [&](uint64_t
Min, uint64_t
Max) {
834 if (AbsWidth == IntPtrTy->getBitWidth())
835 SetAbsRange(~0ull, ~0ull);
837 SetAbsRange(0, 1ull << AbsWidth);
841 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo,
StringRef FnName,
844 for (
auto &&Call : CSInfo.CallSites) {
847 Call.VTable, UniqueMemberAddr);
848 Cmp =
B.CreateZExt(Cmp,
Call.CS->getType());
849 Call.replaceAndErase(
"unique-ret-val", FnName, RemarksEnabled, Cmp);
854 bool DevirtModule::tryUniqueRetValOpt(
859 auto tryUniqueRetValOptFor = [&](
bool IsOne) {
862 if (
Target.RetVal == (IsOne ? 1 : 0)) {
876 Int8Ty, UniqueMemberAddr,
879 if (CSInfo.isExported()) {
883 exportGlobal(Slot, Args,
"unique_member", UniqueMemberAddr);
887 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
892 for (
auto &&
Target : TargetsForSlot)
899 if (tryUniqueRetValOptFor(
true))
901 if (tryUniqueRetValOptFor(
false))
907 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo,
StringRef FnName,
909 for (
auto Call : CSInfo.CallSites) {
910 auto *RetType = cast<IntegerType>(
Call.CS.getType());
912 Value *Addr =
B.CreateGEP(Int8Ty,
Call.VTable, Byte);
913 if (RetType->getBitWidth() == 1) {
914 Value *Bits =
B.CreateLoad(Addr);
915 Value *BitsAndBit =
B.CreateAnd(Bits, Bit);
917 Call.replaceAndErase(
"virtual-const-prop-1-bit", FnName, RemarksEnabled,
920 Value *ValAddr =
B.CreateBitCast(Addr, RetType->getPointerTo());
921 Value *Val =
B.CreateLoad(RetType, ValAddr);
922 Call.replaceAndErase(
"virtual-const-prop", FnName, RemarksEnabled, Val);
928 bool DevirtModule::tryVirtualConstProp(
935 unsigned BitWidth = RetType->getBitWidth();
950 if (
Target.Fn->isDeclaration() ||
953 Target.Fn->arg_empty() || !
Target.Fn->arg_begin()->use_empty() ||
954 Target.Fn->getReturnType() != RetType)
958 for (
auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
959 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
964 ResByArg = &Res->
ResByArg[CSByConstantArg.first];
966 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
969 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
970 ResByArg, Slot, CSByConstantArg.first))
975 uint64_t AllocBefore =
977 uint64_t AllocAfter =
982 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
983 for (
auto &&
Target : TargetsForSlot) {
984 TotalPaddingBefore += std::max<int64_t>(
985 (AllocBefore + 7) / 8 -
Target.allocatedBeforeBytes() - 1, 0);
986 TotalPaddingAfter += std::max<int64_t>(
987 (AllocAfter + 7) / 8 -
Target.allocatedAfterBytes() - 1, 0);
992 if (
std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
999 if (TotalPaddingBefore <= TotalPaddingAfter)
1007 for (
auto &&
Target : TargetsForSlot)
1013 if (CSByConstantArg.second.isExported()) {
1015 exportGlobal(Slot, CSByConstantArg.first,
"byte",
1017 exportGlobal(Slot, CSByConstantArg.first,
"bit",
1022 applyVirtualConstProp(CSByConstantArg.second,
1023 TargetsForSlot[0].Fn->
getName(), ByteConst, BitConst);
1062 NewInit->getType(), NewGV,
1067 Alias->takeName(B.
GV);
1073 bool DevirtModule::areRemarksEnabled() {
1083 return DI.isEnabled();
1086 void DevirtModule::scanTypeTestUsers(
Function *TypeTestFunc,
1109 if (!Assumes.
empty()) {
1111 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1113 if (SeenPtrs.
insert(Ptr).second) {
1115 CallSlots[{TypeId,
Call.Offset}].addCallSite(CI->getArgOperand(0),
1122 for (
auto Assume : Assumes)
1123 Assume->eraseFromParent();
1126 if (CI->use_empty())
1127 CI->eraseFromParent();
1131 void DevirtModule::scanTypeCheckedLoadUsers(
Function *TypeCheckedLoadFunc) {
1134 for (
auto I = TypeCheckedLoadFunc->
use_begin(),
1135 E = TypeCheckedLoadFunc->
use_end();
1142 Value *Ptr = CI->getArgOperand(0);
1143 Value *Offset = CI->getArgOperand(1);
1144 Value *TypeIdValue = CI->getArgOperand(2);
1145 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1150 bool HasNonCallUses =
false;
1152 HasNonCallUses, CI);
1161 (LoadedPtrs.
size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1162 Value *
GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1164 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1168 LoadedPtr->eraseFromParent();
1172 IRBuilder<> CallB((Preds.
size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1173 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {
Ptr, TypeIdValue});
1177 Pred->eraseFromParent();
1184 if (!CI->use_empty()) {
1187 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1188 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1189 CI->replaceAllUsesWith(Pair);
1193 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1194 NumUnsafeUses = DevirtCalls.
size();
1202 CallSlots[{TypeId,
Call.Offset}].addCallSite(Ptr,
Call.CS,
1206 CI->eraseFromParent();
1210 void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
1215 auto ResI = TidSummary->
WPDRes.find(Slot.ByteOffset);
1216 if (ResI == TidSummary->
WPDRes.end())
1227 bool IsExported =
false;
1228 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1232 for (
auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1233 auto I = Res.
ResByArg.find(CSByConstantArg.first);
1236 auto &ResByArg = I->second;
1243 applyUniformRetValOpt(CSByConstantArg.second,
"", ResByArg.
Info);
1247 importGlobal(Slot, CSByConstantArg.first,
"unique_member");
1248 applyUniqueRetValOpt(CSByConstantArg.second,
"", ResByArg.
Info,
1253 Constant *Byte = importGlobal(Slot, CSByConstantArg.first,
"byte", 32);
1255 Constant *Bit = importGlobal(Slot, CSByConstantArg.first,
"bit", 8);
1257 applyVirtualConstProp(CSByConstantArg.second,
"", Byte, Bit);
1265 void DevirtModule::removeRedundantTypeTests() {
1267 for (
auto &&U : NumUnsafeUsesForTypeTest) {
1268 if (U.second == 0) {
1270 U.first->eraseFromParent();
1275 bool DevirtModule::run() {
1285 if (!ExportSummary &&
1286 (!TypeTestFunc || TypeTestFunc->
use_empty() || !AssumeFunc ||
1288 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->
use_empty()))
1291 if (TypeTestFunc && AssumeFunc)
1292 scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1294 if (TypeCheckedLoadFunc)
1295 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
1297 if (ImportSummary) {
1298 for (
auto &S : CallSlots)
1299 importResolution(S.first, S.second);
1301 removeRedundantTypeTests();
1309 std::vector<VTableBits>
Bits;
1311 buildTypeIdentifierMap(Bits, TypeIdMap);
1312 if (TypeIdMap.
empty())
1316 if (ExportSummary) {
1318 for (
auto &
P : TypeIdMap) {
1319 if (
auto *TypeId = dyn_cast<MDString>(
P.first))
1324 for (
auto &
P : *ExportSummary) {
1325 for (
auto &S :
P.second.SummaryList) {
1331 for (
Metadata *MD : MetadataByGUID[VF.GUID]) {
1332 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1337 for (
Metadata *MD : MetadataByGUID[VF.GUID]) {
1338 CallSlots[{MD, VF.Offset}]
1339 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
1343 FS->type_test_assume_const_vcalls()) {
1344 for (
Metadata *MD : MetadataByGUID[
VC.VFunc.GUID]) {
1345 CallSlots[{MD,
VC.VFunc.Offset}]
1346 .ConstCSInfo[
VC.Args]
1347 .SummaryHasTypeTestAssumeUsers =
true;
1351 FS->type_checked_load_const_vcalls()) {
1352 for (
Metadata *MD : MetadataByGUID[
VC.VFunc.GUID]) {
1353 CallSlots[{MD,
VC.VFunc.Offset}]
1354 .ConstCSInfo[
VC.Args]
1355 .SummaryTypeCheckedLoadUsers.push_back(FS);
1363 bool DidVirtualConstProp =
false;
1364 std::map<std::string, Function*> DevirtTargets;
1365 for (
auto &S : CallSlots) {
1369 std::vector<VirtualCallTarget> TargetsForSlot;
1370 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1371 S.first.ByteOffset)) {
1373 if (ExportSummary && isa<MDString>(S.first.TypeID))
1374 Res = &ExportSummary
1375 ->getOrInsertTypeIdSummary(
1376 cast<MDString>(S.first.TypeID)->getString())
1377 .WPDRes[S.first.ByteOffset];
1379 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
1380 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first))
1381 DidVirtualConstProp =
true;
1385 for (
const auto &
T : TargetsForSlot)
1387 DevirtTargets[
T.Fn->getName()] =
T.Fn;
1394 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
1397 for (
auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1398 FS->addTypeTest(GUID);
1399 for (
auto &CCS : S.second.ConstCSInfo)
1400 for (
auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1401 FS->addTypeTest(GUID);
1405 if (RemarksEnabled) {
1407 for (
const auto &DT : DevirtTargets) {
1411 Twine(
"devirtualized ") + F->getName());
1415 removeRedundantTypeTests();
1419 if (DidVirtualConstProp)
void setVisibility(VisibilityTypes V)
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
LinkageTypes getLinkage() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
VisibilityTypes getVisibility() const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Whole program devirtualization
static unsigned getHashValue(const VTableSlot &I)
const char * getName() const
getName - Get the target name.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
void findDevirtualizableCallsForTypeTest(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< CallInst * > &Assumes, const CallInst *CI)
Given a call to the intrinsic .type.test, find all devirtualizable call sites based on the call and r...
A Module instance is used to store all the information related to an LLVM module. ...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
const GlobalListType & getGlobalList() const
Get the Module's list of global variables (constant).
void findDevirtualizableCallsForTypeCheckedLoad(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< Instruction * > &LoadedPtrs, SmallVectorImpl< Instruction * > &Preds, bool &HasNonCallUses, const CallInst *CI)
Given a call to the intrinsic .type.checked.load, find all devirtualizable call sites based on the ca...
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.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
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.
This class implements a map that also provides access to all stored values in a deterministic order...
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 Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
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...
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
Export information to summary.
void setBeforeReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocBefore, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
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...
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".
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
static Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with array type with an element count and element type matchin...
const Constant * stripPointerCasts() const
The returned value is undefined.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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...
TypeID
Definitions of all of the base types for the Type system.
void setName(const Twine &Name)
Change the name of the value.
static bool isEqual(const VTableSlot &LHS, const VTableSlot &RHS)
LLVM_NODISCARD bool empty() const
enum llvm::WholeProgramDevirtResolution::Kind TheKind
Uniform return value optimization.
static VTableSlot getTombstoneKey()
Class to represent array types.
StringRef getSection() const
Get the custom section of this global if it has one.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Type * getElementType() const
size_t size() const
size - Get the array size.
Class to represent pointers.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
uint64_t getElementOffset(unsigned Idx) const
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
void emitOptimizationRemark(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization-applied message.
INITIALIZE_PASS_BEGIN(WholeProgramDevirt,"wholeprogramdevirt","Whole program devirtualization", false, false) INITIALIZE_PASS_END(WholeProgramDevirt
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
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...
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Import information from summary.
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.
const Comdat * getComdat() const
This is an important base class in LLVM.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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...
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)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * getOperand(unsigned i) const
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 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)
The Output class is used to generate a yaml document from in-memory structs and vectors.
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getType() const
Return the type of the instruction that generated this call site.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
An "identifier" for a virtual function.
This class evaluates LLVM IR, producing the Constant representing each SSA instruction.
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
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.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
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.
Type * getType() const
All values are typed, get the type of this value.
Single implementation devirtualization.
uint64_t getSizeInBytes() const
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 ...
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
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)
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.
A specification for a virtual function call with all constant integer arguments.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
DISubprogram * getSubprogram() const
Get the attached subprogram.
The file should be opened in text mode on platforms that make this distinction.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
ModulePass * createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
This pass implements whole-program devirtualization using type metadata.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
std::vector< uint8_t > Bytes
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 findLowestOffset(ArrayRef< VirtualCallTarget > Targets, bool IsAfter, uint64_t Size)
static VTableSlot getEmptyKey()
static Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
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)
Provides passes for computing function attributes based on interprocedural analyses.
Function summary information to aid decisions and implementation of importing.
bool hasLocalLinkage() const
LLVM_NODISCARD bool empty() const
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.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
A raw_ostream that writes to an std::string.
LLVM Value Representation.
static const Function * getParent(const Value *V)
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.
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
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...
Unique return value optimization.
LLVMContext & getContext() const
Get the global data context.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...