#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/TypeMetadataUtils.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSummaryIndexYAML.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/PassRegistry.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/GlobPattern.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/FunctionAttrs.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/CallPromotionUtils.h"
#include "llvm/Transforms/Utils/Evaluator.h"
#include <algorithm>
#include <cstddef>
#include <map>
#include <set>
#include <string>
using namespace llvm;
using namespace wholeprogramdevirt;
#define DEBUG_TYPE "wholeprogramdevirt"
STATISTIC(NumDevirtTargets, "Number of whole program devirtualization targets");
STATISTIC(NumSingleImpl, "Number of single implementation devirtualizations");
STATISTIC(NumBranchFunnel, "Number of branch funnels");
STATISTIC(NumUniformRetVal, "Number of uniform return value optimizations");
STATISTIC(NumUniqueRetVal, "Number of unique return value optimizations");
STATISTIC(NumVirtConstProp1Bit,
"Number of 1 bit virtual constant propagations");
STATISTIC(NumVirtConstProp, "Number of virtual constant propagations");
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);
static cl::opt<std::string> ClReadSummary(
"wholeprogramdevirt-read-summary",
cl::desc(
"Read summary from given bitcode or YAML file before running pass"),
cl::Hidden);
static cl::opt<std::string> ClWriteSummary(
"wholeprogramdevirt-write-summary",
cl::desc("Write summary to given bitcode or YAML file after running pass. "
"Output file format is deduced from extension: *.bc means writing "
"bitcode, otherwise YAML"),
cl::Hidden);
static cl::opt<unsigned>
ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
cl::init(10),
cl::desc("Maximum number of call targets per "
"call site to enable branch funnels"));
static cl::opt<bool>
PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden,
cl::desc("Print index-based devirtualization messages"));
static cl::opt<bool>
WholeProgramVisibility("whole-program-visibility", cl::Hidden,
cl::desc("Enable whole program visibility"));
static cl::opt<bool> DisableWholeProgramVisibility(
"disable-whole-program-visibility", cl::Hidden,
cl::desc("Disable whole program visibility (overrides enabling options)"));
static cl::list<std::string>
SkipFunctionNames("wholeprogramdevirt-skip",
cl::desc("Prevent function(s) from being devirtualized"),
cl::Hidden, cl::CommaSeparated);
enum WPDCheckMode { None, Trap, Fallback };
static cl::opt<WPDCheckMode> DevirtCheckMode(
"wholeprogramdevirt-check", cl::Hidden,
cl::desc("Type of checking for incorrect devirtualizations"),
cl::values(clEnumValN(WPDCheckMode::None, "none", "No checking"),
clEnumValN(WPDCheckMode::Trap, "trap", "Trap when incorrect"),
clEnumValN(WPDCheckMode::Fallback, "fallback",
"Fallback to indirect when incorrect")));
namespace {
struct PatternList {
std::vector<GlobPattern> Patterns;
template <class T> void init(const T &StringList) {
for (const auto &S : StringList)
if (Expected<GlobPattern> Pat = GlobPattern::create(S))
Patterns.push_back(std::move(*Pat));
}
bool match(StringRef S) {
for (const GlobPattern &P : Patterns)
if (P.match(S))
return true;
return false;
}
};
}
uint64_t
wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
bool IsAfter, uint64_t Size) {
uint64_t MinByte = 0;
for (const VirtualCallTarget &Target : Targets) {
if (IsAfter)
MinByte = std::max(MinByte, Target.minAfterBytes());
else
MinByte = std::max(MinByte, Target.minBeforeBytes());
}
std::vector<ArrayRef<uint8_t>> Used;
for (const VirtualCallTarget &Target : Targets) {
ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
: Target.TM->Bits->Before.BytesUsed;
uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
: MinByte - Target.minBeforeBytes();
if (VTUsed.size() > Offset)
Used.push_back(VTUsed.slice(Offset));
}
if (Size == 1) {
for (unsigned I = 0;; ++I) {
uint8_t BitsUsed = 0;
for (auto &&B : Used)
if (I < B.size())
BitsUsed |= B[I];
if (BitsUsed != 0xff)
return (MinByte + I) * 8 +
countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
}
} else {
for (unsigned I = 0;; ++I) {
for (auto &&B : Used) {
unsigned Byte = 0;
while ((I + Byte) < B.size() && Byte < (Size / 8)) {
if (B[I + Byte])
goto NextI;
++Byte;
}
}
return (MinByte + I) * 8;
NextI:;
}
}
}
void wholeprogramdevirt::setBeforeReturnValues(
MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
if (BitWidth == 1)
OffsetByte = -(AllocBefore / 8 + 1);
else
OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
OffsetBit = AllocBefore % 8;
for (VirtualCallTarget &Target : Targets) {
if (BitWidth == 1)
Target.setBeforeBit(AllocBefore);
else
Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
}
}
void wholeprogramdevirt::setAfterReturnValues(
MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
if (BitWidth == 1)
OffsetByte = AllocAfter / 8;
else
OffsetByte = (AllocAfter + 7) / 8;
OffsetBit = AllocAfter % 8;
for (VirtualCallTarget &Target : Targets) {
if (BitWidth == 1)
Target.setAfterBit(AllocAfter);
else
Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
}
}
VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
: Fn(Fn), TM(TM),
IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
namespace {
struct VTableSlot {
Metadata *TypeID;
uint64_t ByteOffset;
};
}
namespace llvm {
template <> struct DenseMapInfo<VTableSlot> {
static VTableSlot getEmptyKey() {
return {DenseMapInfo<Metadata *>::getEmptyKey(),
DenseMapInfo<uint64_t>::getEmptyKey()};
}
static VTableSlot getTombstoneKey() {
return {DenseMapInfo<Metadata *>::getTombstoneKey(),
DenseMapInfo<uint64_t>::getTombstoneKey()};
}
static unsigned getHashValue(const VTableSlot &I) {
return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
}
static bool isEqual(const VTableSlot &LHS,
const VTableSlot &RHS) {
return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
}
};
template <> struct DenseMapInfo<VTableSlotSummary> {
static VTableSlotSummary getEmptyKey() {
return {DenseMapInfo<StringRef>::getEmptyKey(),
DenseMapInfo<uint64_t>::getEmptyKey()};
}
static VTableSlotSummary getTombstoneKey() {
return {DenseMapInfo<StringRef>::getTombstoneKey(),
DenseMapInfo<uint64_t>::getTombstoneKey()};
}
static unsigned getHashValue(const VTableSlotSummary &I) {
return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^
DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
}
static bool isEqual(const VTableSlotSummary &LHS,
const VTableSlotSummary &RHS) {
return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
}
};
}
namespace {
bool mustBeUnreachableFunction(ValueInfo TheFnVI) {
if ((!TheFnVI) || TheFnVI.getSummaryList().empty()) {
return false;
}
for (auto &Summary : TheFnVI.getSummaryList()) {
if (!Summary->isLive())
return false;
if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) {
if (!FS->fflags().MustBeUnreachable)
return false;
}
}
return true;
}
struct VirtualCallSite {
Value *VTable = nullptr;
CallBase &CB;
unsigned *NumUnsafeUses = nullptr;
void
emitRemark(const StringRef OptName, const StringRef TargetName,
function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
Function *F = CB.getCaller();
DebugLoc DLoc = CB.getDebugLoc();
BasicBlock *Block = CB.getParent();
using namespace ore;
OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
<< NV("Optimization", OptName)
<< ": devirtualized a call to "
<< NV("FunctionName", TargetName));
}
void replaceAndErase(
const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
Value *New) {
if (RemarksEnabled)
emitRemark(OptName, TargetName, OREGetter);
CB.replaceAllUsesWith(New);
if (auto *II = dyn_cast<InvokeInst>(&CB)) {
BranchInst::Create(II->getNormalDest(), &CB);
II->getUnwindDest()->removePredecessor(II->getParent());
}
CB.eraseFromParent();
if (NumUnsafeUses)
--*NumUnsafeUses;
}
};
struct CallSiteInfo {
std::vector<VirtualCallSite> CallSites;
bool AllCallSitesDevirted = true;
bool SummaryHasTypeTestAssumeUsers = false;
std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
bool isExported() const {
return SummaryHasTypeTestAssumeUsers ||
!SummaryTypeCheckedLoadUsers.empty();
}
void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
SummaryTypeCheckedLoadUsers.push_back(FS);
AllCallSitesDevirted = false;
}
void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
SummaryTypeTestAssumeUsers.push_back(FS);
SummaryHasTypeTestAssumeUsers = true;
AllCallSitesDevirted = false;
}
void markDevirt() {
AllCallSitesDevirted = true;
SummaryTypeCheckedLoadUsers.clear();
}
};
struct VTableSlotInfo {
CallSiteInfo CSInfo;
std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses);
private:
CallSiteInfo &findCallSiteInfo(CallBase &CB);
};
CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) {
std::vector<uint64_t> Args;
auto *CBType = dyn_cast<IntegerType>(CB.getType());
if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty())
return CSInfo;
for (auto &&Arg : drop_begin(CB.args())) {
auto *CI = dyn_cast<ConstantInt>(Arg);
if (!CI || CI->getBitWidth() > 64)
return CSInfo;
Args.push_back(CI->getZExtValue());
}
return ConstCSInfo[Args];
}
void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB,
unsigned *NumUnsafeUses) {
auto &CSI = findCallSiteInfo(CB);
CSI.AllCallSitesDevirted = false;
CSI.CallSites.push_back({VTable, CB, NumUnsafeUses});
}
struct DevirtModule {
Module &M;
function_ref<AAResults &(Function &)> AARGetter;
function_ref<DominatorTree &(Function &)> LookupDomTree;
ModuleSummaryIndex *ExportSummary;
const ModuleSummaryIndex *ImportSummary;
IntegerType *Int8Ty;
PointerType *Int8PtrTy;
IntegerType *Int32Ty;
IntegerType *Int64Ty;
IntegerType *IntPtrTy;
ArrayType *Int8Arr0Ty;
bool RemarksEnabled;
function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
MapVector<VTableSlot, VTableSlotInfo> CallSlots;
SmallPtrSet<CallBase *, 8> OptimizedCalls;
std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
PatternList FunctionsToSkip;
DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
function_ref<DominatorTree &(Function &)> LookupDomTree,
ModuleSummaryIndex *ExportSummary,
const ModuleSummaryIndex *ImportSummary)
: M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree),
ExportSummary(ExportSummary), ImportSummary(ImportSummary),
Int8Ty(Type::getInt8Ty(M.getContext())),
Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
Int32Ty(Type::getInt32Ty(M.getContext())),
Int64Ty(Type::getInt64Ty(M.getContext())),
IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)),
RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
assert(!(ExportSummary && ImportSummary));
FunctionsToSkip.init(SkipFunctionNames);
}
bool areRemarksEnabled();
void
scanTypeTestUsers(Function *TypeTestFunc,
DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
void buildTypeIdentifierMap(
std::vector<VTableBits> &Bits,
DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
bool
tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
const std::set<TypeMemberInfo> &TypeMemberInfos,
uint64_t ByteOffset,
ModuleSummaryIndex *ExportSummary);
void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
bool &IsExported);
bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
MutableArrayRef<VirtualCallTarget> TargetsForSlot,
VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res);
void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
bool &IsExported);
void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res, VTableSlot Slot);
bool tryEvaluateFunctionsWithArgs(
MutableArrayRef<VirtualCallTarget> TargetsForSlot,
ArrayRef<uint64_t> Args);
void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
uint64_t TheRetVal);
bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
CallSiteInfo &CSInfo,
WholeProgramDevirtResolution::ByArg *Res);
std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
StringRef Name);
bool shouldExportConstantsAsAbsoluteSymbols();
void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
Constant *C);
void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
uint32_t Const, uint32_t &Storage);
Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
StringRef Name);
Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
StringRef Name, IntegerType *IntTy,
uint32_t Storage);
Constant *getMemberAddr(const TypeMemberInfo *M);
void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
Constant *UniqueMemberAddr);
bool tryUniqueRetValOpt(unsigned BitWidth,
MutableArrayRef<VirtualCallTarget> TargetsForSlot,
CallSiteInfo &CSInfo,
WholeProgramDevirtResolution::ByArg *Res,
VTableSlot Slot, ArrayRef<uint64_t> Args);
void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
Constant *Byte, Constant *Bit);
bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res, VTableSlot Slot);
void rebuildGlobal(VTableBits &B);
void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
void removeRedundantTypeTests();
bool run();
static ValueInfo lookUpFunctionValueInfo(Function *TheFn,
ModuleSummaryIndex *ExportSummary);
static bool mustBeUnreachableFunction(Function *const F,
ModuleSummaryIndex *ExportSummary);
static bool
runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter,
function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
function_ref<DominatorTree &(Function &)> LookupDomTree);
};
struct DevirtIndex {
ModuleSummaryIndex &ExportSummary;
std::set<GlobalValue::GUID> &ExportedGUIDs;
std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
PatternList FunctionsToSkip;
DevirtIndex(
ModuleSummaryIndex &ExportSummary,
std::set<GlobalValue::GUID> &ExportedGUIDs,
std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap)
: ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
LocalWPDTargetsMap(LocalWPDTargetsMap) {
FunctionsToSkip.init(SkipFunctionNames);
}
bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
const TypeIdCompatibleVtableInfo TIdInfo,
uint64_t ByteOffset);
bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
VTableSlotSummary &SlotSummary,
VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res,
std::set<ValueInfo> &DevirtTargets);
void run();
};
}
PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
ModuleAnalysisManager &AM) {
auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
auto AARGetter = [&](Function &F) -> AAResults & {
return FAM.getResult<AAManager>(F);
};
auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
};
auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {
return FAM.getResult<DominatorTreeAnalysis>(F);
};
if (UseCommandLine) {
if (DevirtModule::runForTesting(M, AARGetter, OREGetter, LookupDomTree))
return PreservedAnalyses::all();
return PreservedAnalyses::none();
}
if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary,
ImportSummary)
.run())
return PreservedAnalyses::all();
return PreservedAnalyses::none();
}
namespace llvm {
bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) {
return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) &&
!DisableWholeProgramVisibility;
}
void updateVCallVisibilityInModule(
Module &M, bool WholeProgramVisibilityEnabledInLTO,
const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) {
if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
return;
for (GlobalVariable &GV : M.globals()) {
if (GV.hasMetadata(LLVMContext::MD_type) &&
GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic &&
!DynamicExportSymbols.count(GV.getGUID()))
GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit);
}
}
void updatePublicTypeTestCalls(Module &M,
bool WholeProgramVisibilityEnabledInLTO) {
Function *PublicTypeTestFunc =
M.getFunction(Intrinsic::getName(Intrinsic::public_type_test));
if (!PublicTypeTestFunc)
return;
if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO)) {
Function *TypeTestFunc =
Intrinsic::getDeclaration(&M, Intrinsic::type_test);
for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
auto *CI = cast<CallInst>(U.getUser());
auto *NewCI = CallInst::Create(
TypeTestFunc, {CI->getArgOperand(0), CI->getArgOperand(1)}, None, "",
CI);
CI->replaceAllUsesWith(NewCI);
CI->eraseFromParent();
}
} else {
auto *True = ConstantInt::getTrue(M.getContext());
for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
auto *CI = cast<CallInst>(U.getUser());
CI->replaceAllUsesWith(True);
CI->eraseFromParent();
}
}
}
void updateVCallVisibilityInIndex(
ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO,
const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) {
if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
return;
for (auto &P : Index) {
if (DynamicExportSymbols.count(P.first))
continue;
for (auto &S : P.second.SummaryList) {
auto *GVar = dyn_cast<GlobalVarSummary>(S.get());
if (!GVar ||
GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic)
continue;
GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit);
}
}
}
void runWholeProgramDevirtOnIndex(
ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run();
}
void updateIndexWPDForExports(
ModuleSummaryIndex &Summary,
function_ref<bool(StringRef, ValueInfo)> isExported,
std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
for (auto &T : LocalWPDTargetsMap) {
auto &VI = T.first;
assert(VI.getSummaryList().size() == 1 &&
"Devirt of local target has more than one copy");
auto &S = VI.getSummaryList()[0];
if (!isExported(S->modulePath(), VI))
continue;
for (auto &SlotSummary : T.second) {
auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
assert(TIdSum);
auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
assert(WPDRes != TIdSum->WPDRes.end());
WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
WPDRes->second.SingleImplName,
Summary.getModuleHash(S->modulePath()));
}
}
}
}
static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) {
const auto &ModPaths = Summary->modulePaths();
if (ClSummaryAction != PassSummaryAction::Import &&
ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) ==
ModPaths.end())
return createStringError(
errc::invalid_argument,
"combined summary should contain Regular LTO module");
return ErrorSuccess();
}
bool DevirtModule::runForTesting(
Module &M, function_ref<AAResults &(Function &)> AARGetter,
function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
function_ref<DominatorTree &(Function &)> LookupDomTree) {
std::unique_ptr<ModuleSummaryIndex> Summary =
std::make_unique<ModuleSummaryIndex>(false);
if (!ClReadSummary.empty()) {
ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
": ");
auto ReadSummaryFile =
ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
getModuleSummaryIndex(*ReadSummaryFile)) {
Summary = std::move(*SummaryOrErr);
ExitOnErr(checkCombinedSummaryForTesting(Summary.get()));
} else {
consumeError(SummaryOrErr.takeError());
yaml::Input In(ReadSummaryFile->getBuffer());
In >> *Summary;
ExitOnErr(errorCodeToError(In.error()));
}
}
bool Changed =
DevirtModule(M, AARGetter, OREGetter, LookupDomTree,
ClSummaryAction == PassSummaryAction::Export ? Summary.get()
: nullptr,
ClSummaryAction == PassSummaryAction::Import ? Summary.get()
: nullptr)
.run();
if (!ClWriteSummary.empty()) {
ExitOnError ExitOnErr(
"-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
std::error_code EC;
if (StringRef(ClWriteSummary).endswith(".bc")) {
raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None);
ExitOnErr(errorCodeToError(EC));
writeIndexToFile(*Summary, OS);
} else {
raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_TextWithCRLF);
ExitOnErr(errorCodeToError(EC));
yaml::Output Out(OS);
Out << *Summary;
}
}
return Changed;
}
void DevirtModule::buildTypeIdentifierMap(
std::vector<VTableBits> &Bits,
DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
DenseMap<GlobalVariable *, VTableBits *> GVToBits;
Bits.reserve(M.getGlobalList().size());
SmallVector<MDNode *, 2> Types;
for (GlobalVariable &GV : M.globals()) {
Types.clear();
GV.getMetadata(LLVMContext::MD_type, Types);
if (GV.isDeclaration() || Types.empty())
continue;
VTableBits *&BitsPtr = GVToBits[&GV];
if (!BitsPtr) {
Bits.emplace_back();
Bits.back().GV = &GV;
Bits.back().ObjectSize =
M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
BitsPtr = &Bits.back();
}
for (MDNode *Type : Types) {
auto TypeID = Type->getOperand(1).get();
uint64_t Offset =
cast<ConstantInt>(
cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
->getZExtValue();
TypeIdMap[TypeID].insert({BitsPtr, Offset});
}
}
}
bool DevirtModule::tryFindVirtualCallTargets(
std::vector<VirtualCallTarget> &TargetsForSlot,
const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset,
ModuleSummaryIndex *ExportSummary) {
for (const TypeMemberInfo &TM : TypeMemberInfos) {
if (!TM.Bits->GV->isConstant())
return false;
if (TM.Bits->GV->getVCallVisibility() ==
GlobalObject::VCallVisibilityPublic)
return false;
Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
TM.Offset + ByteOffset, M);
if (!Ptr)
return false;
auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
if (!Fn)
return false;
if (FunctionsToSkip.match(Fn->getName()))
return false;
if (Fn->getName() == "__cxa_pure_virtual")
continue;
if (mustBeUnreachableFunction(Fn, ExportSummary))
continue;
TargetsForSlot.push_back({Fn, &TM});
}
return !TargetsForSlot.empty();
}
bool DevirtIndex::tryFindVirtualCallTargets(
std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo,
uint64_t ByteOffset) {
for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
const GlobalVarSummary *VS = nullptr;
bool LocalFound = false;
for (auto &S : P.VTableVI.getSummaryList()) {
if (GlobalValue::isLocalLinkage(S->linkage())) {
if (LocalFound)
return false;
LocalFound = true;
}
auto *CurVS = cast<GlobalVarSummary>(S->getBaseObject());
if (!CurVS->vTableFuncs().empty() ||
!GlobalValue::isAvailableExternallyLinkage(S->linkage())) {
VS = CurVS;
if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
return false;
}
}
if (!VS)
return false;
if (!VS->isLive())
continue;
for (auto VTP : VS->vTableFuncs()) {
if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
continue;
if (mustBeUnreachableFunction(VTP.FuncVI))
continue;
TargetsForSlot.push_back(VTP.FuncVI);
}
}
return !TargetsForSlot.empty();
}
void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
Constant *TheFn, bool &IsExported) {
if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName()))
return;
auto Apply = [&](CallSiteInfo &CSInfo) {
for (auto &&VCallSite : CSInfo.CallSites) {
if (!OptimizedCalls.insert(&VCallSite.CB).second)
continue;
if (RemarksEnabled)
VCallSite.emitRemark("single-impl",
TheFn->stripPointerCasts()->getName(), OREGetter);
NumSingleImpl++;
auto &CB = VCallSite.CB;
assert(!CB.getCalledFunction() && "devirtualizing direct call?");
IRBuilder<> Builder(&CB);
Value *Callee =
Builder.CreateBitCast(TheFn, CB.getCalledOperand()->getType());
if (DevirtCheckMode == WPDCheckMode::Trap) {
auto *Cond = Builder.CreateICmpNE(CB.getCalledOperand(), Callee);
Instruction *ThenTerm =
SplitBlockAndInsertIfThen(Cond, &CB, false);
Builder.SetInsertPoint(ThenTerm);
Function *TrapFn = Intrinsic::getDeclaration(&M, Intrinsic::debugtrap);
auto *CallTrap = Builder.CreateCall(TrapFn);
CallTrap->setDebugLoc(CB.getDebugLoc());
}
if (DevirtCheckMode == WPDCheckMode::Fallback) {
MDNode *Weights =
MDBuilder(M.getContext()).createBranchWeights((1U << 20) - 1, 1);
CallBase &NewInst = versionCallSite(CB, Callee, Weights);
NewInst.setCalledOperand(Callee);
NewInst.setMetadata(LLVMContext::MD_prof, nullptr);
NewInst.setMetadata(LLVMContext::MD_callees, nullptr);
CB.setMetadata(LLVMContext::MD_prof, nullptr);
CB.setMetadata(LLVMContext::MD_callees, nullptr);
}
else {
CB.setCalledOperand(Callee);
CB.setMetadata(LLVMContext::MD_prof, nullptr);
CB.setMetadata(LLVMContext::MD_callees, nullptr);
}
if (VCallSite.NumUnsafeUses)
--*VCallSite.NumUnsafeUses;
}
if (CSInfo.isExported())
IsExported = true;
CSInfo.markDevirt();
};
Apply(SlotInfo.CSInfo);
for (auto &P : SlotInfo.ConstCSInfo)
Apply(P.second);
}
static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
if (Callee.getSummaryList().empty())
return false;
bool IsExported = false;
auto &S = Callee.getSummaryList()[0];
CalleeInfo CI(CalleeInfo::HotnessType::Hot, 0);
auto AddCalls = [&](CallSiteInfo &CSInfo) {
for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
FS->addCall({Callee, CI});
IsExported |= S->modulePath() != FS->modulePath();
}
for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
FS->addCall({Callee, CI});
IsExported |= S->modulePath() != FS->modulePath();
}
};
AddCalls(SlotInfo.CSInfo);
for (auto &P : SlotInfo.ConstCSInfo)
AddCalls(P.second);
return IsExported;
}
bool DevirtModule::trySingleImplDevirt(
ModuleSummaryIndex *ExportSummary,
MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res) {
Function *TheFn = TargetsForSlot[0].Fn;
for (auto &&Target : TargetsForSlot)
if (TheFn != Target.Fn)
return false;
if (RemarksEnabled || AreStatisticsEnabled())
TargetsForSlot[0].WasDevirt = true;
bool IsExported = false;
applySingleImplDevirt(SlotInfo, TheFn, IsExported);
if (!IsExported)
return false;
if (TheFn->hasLocalLinkage()) {
std::string NewName = (TheFn->getName() + ".llvm.merged").str();
if (Comdat *C = TheFn->getComdat()) {
if (C->getName() == TheFn->getName()) {
Comdat *NewC = M.getOrInsertComdat(NewName);
NewC->setSelectionKind(C->getSelectionKind());
for (GlobalObject &GO : M.global_objects())
if (GO.getComdat() == C)
GO.setComdat(NewC);
}
}
TheFn->setLinkage(GlobalValue::ExternalLinkage);
TheFn->setVisibility(GlobalValue::HiddenVisibility);
TheFn->setName(NewName);
}
if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
AddCalls(SlotInfo, TheFnVI);
Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
Res->SingleImplName = std::string(TheFn->getName());
return true;
}
bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
VTableSlotSummary &SlotSummary,
VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res,
std::set<ValueInfo> &DevirtTargets) {
auto TheFn = TargetsForSlot[0];
for (auto &&Target : TargetsForSlot)
if (TheFn != Target)
return false;
auto Size = TheFn.getSummaryList().size();
if (!Size)
return false;
if (FunctionsToSkip.match(TheFn.name()))
return false;
for (auto &S : TheFn.getSummaryList())
if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1)
return false;
if (PrintSummaryDevirt || AreStatisticsEnabled())
DevirtTargets.insert(TheFn);
auto &S = TheFn.getSummaryList()[0];
bool IsExported = AddCalls(SlotInfo, TheFn);
if (IsExported)
ExportedGUIDs.insert(TheFn.getGUID());
Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
if (GlobalValue::isLocalLinkage(S->linkage())) {
if (IsExported)
Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
else {
LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
Res->SingleImplName = std::string(TheFn.name());
}
} else
Res->SingleImplName = std::string(TheFn.name());
assert(!Res->SingleImplName.empty());
return true;
}
void DevirtModule::tryICallBranchFunnel(
MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res, VTableSlot Slot) {
Triple T(M.getTargetTriple());
if (T.getArch() != Triple::x86_64)
return;
if (TargetsForSlot.size() > ClThreshold)
return;
bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
if (!HasNonDevirt)
for (auto &P : SlotInfo.ConstCSInfo)
if (!P.second.AllCallSitesDevirted) {
HasNonDevirt = true;
break;
}
if (!HasNonDevirt)
return;
FunctionType *FT =
FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
Function *JT;
if (isa<MDString>(Slot.TypeID)) {
JT = Function::Create(FT, Function::ExternalLinkage,
M.getDataLayout().getProgramAddressSpace(),
getGlobalName(Slot, {}, "branch_funnel"), &M);
JT->setVisibility(GlobalValue::HiddenVisibility);
} else {
JT = Function::Create(FT, Function::InternalLinkage,
M.getDataLayout().getProgramAddressSpace(),
"branch_funnel", &M);
}
JT->addParamAttr(0, Attribute::Nest);
std::vector<Value *> JTArgs;
JTArgs.push_back(JT->arg_begin());
for (auto &T : TargetsForSlot) {
JTArgs.push_back(getMemberAddr(T.TM));
JTArgs.push_back(T.Fn);
}
BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
Function *Intr =
Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
CI->setTailCallKind(CallInst::TCK_MustTail);
ReturnInst::Create(M.getContext(), nullptr, BB);
bool IsExported = false;
applyICallBranchFunnel(SlotInfo, JT, IsExported);
if (IsExported)
Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
}
void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
Constant *JT, bool &IsExported) {
auto Apply = [&](CallSiteInfo &CSInfo) {
if (CSInfo.isExported())
IsExported = true;
if (CSInfo.AllCallSitesDevirted)
return;
for (auto &&VCallSite : CSInfo.CallSites) {
CallBase &CB = VCallSite.CB;
Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features");
if (!FSAttr.isValid() ||
!FSAttr.getValueAsString().contains("+retpoline"))
continue;
NumBranchFunnel++;
if (RemarksEnabled)
VCallSite.emitRemark("branch-funnel",
JT->stripPointerCasts()->getName(), OREGetter);
std::vector<Type *> NewArgs;
NewArgs.push_back(Int8PtrTy);
append_range(NewArgs, CB.getFunctionType()->params());
FunctionType *NewFT =
FunctionType::get(CB.getFunctionType()->getReturnType(), NewArgs,
CB.getFunctionType()->isVarArg());
PointerType *NewFTPtr = PointerType::getUnqual(NewFT);
IRBuilder<> IRB(&CB);
std::vector<Value *> Args;
Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
llvm::append_range(Args, CB.args());
CallBase *NewCS = nullptr;
if (isa<CallInst>(CB))
NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args);
else
NewCS = IRB.CreateInvoke(NewFT, IRB.CreateBitCast(JT, NewFTPtr),
cast<InvokeInst>(CB).getNormalDest(),
cast<InvokeInst>(CB).getUnwindDest(), Args);
NewCS->setCallingConv(CB.getCallingConv());
AttributeList Attrs = CB.getAttributes();
std::vector<AttributeSet> NewArgAttrs;
NewArgAttrs.push_back(AttributeSet::get(
M.getContext(), ArrayRef<Attribute>{Attribute::get(
M.getContext(), Attribute::Nest)}));
for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
NewArgAttrs.push_back(Attrs.getParamAttrs(I));
NewCS->setAttributes(
AttributeList::get(M.getContext(), Attrs.getFnAttrs(),
Attrs.getRetAttrs(), NewArgAttrs));
CB.replaceAllUsesWith(NewCS);
CB.eraseFromParent();
if (VCallSite.NumUnsafeUses)
--*VCallSite.NumUnsafeUses;
}
};
Apply(SlotInfo.CSInfo);
for (auto &P : SlotInfo.ConstCSInfo)
Apply(P.second);
}
bool DevirtModule::tryEvaluateFunctionsWithArgs(
MutableArrayRef<VirtualCallTarget> TargetsForSlot,
ArrayRef<uint64_t> Args) {
for (VirtualCallTarget &Target : TargetsForSlot) {
if (Target.Fn->arg_size() != Args.size() + 1)
return false;
Evaluator Eval(M.getDataLayout(), nullptr);
SmallVector<Constant *, 2> EvalArgs;
EvalArgs.push_back(
Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
for (unsigned I = 0; I != Args.size(); ++I) {
auto *ArgTy = dyn_cast<IntegerType>(
Target.Fn->getFunctionType()->getParamType(I + 1));
if (!ArgTy)
return false;
EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
}
Constant *RetVal;
if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
!isa<ConstantInt>(RetVal))
return false;
Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
}
return true;
}
void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
uint64_t TheRetVal) {
for (auto Call : CSInfo.CallSites) {
if (!OptimizedCalls.insert(&Call.CB).second)
continue;
NumUniformRetVal++;
Call.replaceAndErase(
"uniform-ret-val", FnName, RemarksEnabled, OREGetter,
ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal));
}
CSInfo.markDevirt();
}
bool DevirtModule::tryUniformRetValOpt(
MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
WholeProgramDevirtResolution::ByArg *Res) {
uint64_t TheRetVal = TargetsForSlot[0].RetVal;
for (const VirtualCallTarget &Target : TargetsForSlot)
if (Target.RetVal != TheRetVal)
return false;
if (CSInfo.isExported()) {
Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
Res->Info = TheRetVal;
}
applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
if (RemarksEnabled || AreStatisticsEnabled())
for (auto &&Target : TargetsForSlot)
Target.WasDevirt = true;
return true;
}
std::string DevirtModule::getGlobalName(VTableSlot Slot,
ArrayRef<uint64_t> Args,
StringRef Name) {
std::string FullName = "__typeid_";
raw_string_ostream OS(FullName);
OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
for (uint64_t Arg : Args)
OS << '_' << Arg;
OS << '_' << Name;
return OS.str();
}
bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
Triple T(M.getTargetTriple());
return T.isX86() && T.getObjectFormat() == Triple::ELF;
}
void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
StringRef Name, Constant *C) {
GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
getGlobalName(Slot, Args, Name), C, &M);
GA->setVisibility(GlobalValue::HiddenVisibility);
}
void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
StringRef Name, uint32_t Const,
uint32_t &Storage) {
if (shouldExportConstantsAsAbsoluteSymbols()) {
exportGlobal(
Slot, Args, Name,
ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
return;
}
Storage = Const;
}
Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
StringRef Name) {
Constant *C =
M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty);
auto *GV = dyn_cast<GlobalVariable>(C);
if (GV)
GV->setVisibility(GlobalValue::HiddenVisibility);
return C;
}
Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
StringRef Name, IntegerType *IntTy,
uint32_t Storage) {
if (!shouldExportConstantsAsAbsoluteSymbols())
return ConstantInt::get(IntTy, Storage);
Constant *C = importGlobal(Slot, Args, Name);
auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
C = ConstantExpr::getPtrToInt(C, IntTy);
if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
return C;
auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
GV->setMetadata(LLVMContext::MD_absolute_symbol,
MDNode::get(M.getContext(), {MinC, MaxC}));
};
unsigned AbsWidth = IntTy->getBitWidth();
if (AbsWidth == IntPtrTy->getBitWidth())
SetAbsRange(~0ull, ~0ull); else
SetAbsRange(0, 1ull << AbsWidth);
return C;
}
void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
bool IsOne,
Constant *UniqueMemberAddr) {
for (auto &&Call : CSInfo.CallSites) {
if (!OptimizedCalls.insert(&Call.CB).second)
continue;
IRBuilder<> B(&Call.CB);
Value *Cmp =
B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable,
B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType()));
Cmp = B.CreateZExt(Cmp, Call.CB.getType());
NumUniqueRetVal++;
Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
Cmp);
}
CSInfo.markDevirt();
}
Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
return ConstantExpr::getGetElementPtr(Int8Ty, C,
ConstantInt::get(Int64Ty, M->Offset));
}
bool DevirtModule::tryUniqueRetValOpt(
unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
VTableSlot Slot, ArrayRef<uint64_t> Args) {
auto tryUniqueRetValOptFor = [&](bool IsOne) {
const TypeMemberInfo *UniqueMember = nullptr;
for (const VirtualCallTarget &Target : TargetsForSlot) {
if (Target.RetVal == (IsOne ? 1 : 0)) {
if (UniqueMember)
return false;
UniqueMember = Target.TM;
}
}
assert(UniqueMember);
Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
if (CSInfo.isExported()) {
Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
Res->Info = IsOne;
exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
}
applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
UniqueMemberAddr);
if (RemarksEnabled || AreStatisticsEnabled())
for (auto &&Target : TargetsForSlot)
Target.WasDevirt = true;
return true;
};
if (BitWidth == 1) {
if (tryUniqueRetValOptFor(true))
return true;
if (tryUniqueRetValOptFor(false))
return true;
}
return false;
}
void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
Constant *Byte, Constant *Bit) {
for (auto Call : CSInfo.CallSites) {
if (!OptimizedCalls.insert(&Call.CB).second)
continue;
auto *RetType = cast<IntegerType>(Call.CB.getType());
IRBuilder<> B(&Call.CB);
Value *Addr =
B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
if (RetType->getBitWidth() == 1) {
Value *Bits = B.CreateLoad(Int8Ty, Addr);
Value *BitsAndBit = B.CreateAnd(Bits, Bit);
auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
NumVirtConstProp1Bit++;
Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
OREGetter, IsBitSet);
} else {
Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
Value *Val = B.CreateLoad(RetType, ValAddr);
NumVirtConstProp++;
Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
OREGetter, Val);
}
}
CSInfo.markDevirt();
}
bool DevirtModule::tryVirtualConstProp(
MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
WholeProgramDevirtResolution *Res, VTableSlot Slot) {
auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
if (!RetType)
return false;
unsigned BitWidth = RetType->getBitWidth();
if (BitWidth > 64)
return false;
for (VirtualCallTarget &Target : TargetsForSlot) {
if (Target.Fn->isDeclaration() ||
computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
FMRB_DoesNotAccessMemory ||
Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
Target.Fn->getReturnType() != RetType)
return false;
}
for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
continue;
WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
if (Res)
ResByArg = &Res->ResByArg[CSByConstantArg.first];
if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
continue;
if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
ResByArg, Slot, CSByConstantArg.first))
continue;
uint64_t AllocBefore =
findLowestOffset(TargetsForSlot, false, BitWidth);
uint64_t AllocAfter =
findLowestOffset(TargetsForSlot, true, BitWidth);
uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
for (auto &&Target : TargetsForSlot) {
TotalPaddingBefore += std::max<int64_t>(
(AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
TotalPaddingAfter += std::max<int64_t>(
(AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
}
if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
continue;
int64_t OffsetByte;
uint64_t OffsetBit;
if (TotalPaddingBefore <= TotalPaddingAfter)
setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
OffsetBit);
else
setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
OffsetBit);
if (RemarksEnabled || AreStatisticsEnabled())
for (auto &&Target : TargetsForSlot)
Target.WasDevirt = true;
if (CSByConstantArg.second.isExported()) {
ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
ResByArg->Byte);
exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
ResByArg->Bit);
}
Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
applyVirtualConstProp(CSByConstantArg.second,
TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
}
return true;
}
void DevirtModule::rebuildGlobal(VTableBits &B) {
if (B.Before.Bytes.empty() && B.After.Bytes.empty())
return;
Align Alignment = M.getDataLayout().getValueOrABITypeAlignment(
B.GV->getAlign(), B.GV->getValueType());
B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
auto NewInit = ConstantStruct::getAnon(
{ConstantDataArray::get(M.getContext(), B.Before.Bytes),
B.GV->getInitializer(),
ConstantDataArray::get(M.getContext(), B.After.Bytes)});
auto NewGV =
new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
NewGV->setSection(B.GV->getSection());
NewGV->setComdat(B.GV->getComdat());
NewGV->setAlignment(B.GV->getAlign());
NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
auto Alias = GlobalAlias::create(
B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
ConstantExpr::getGetElementPtr(
NewInit->getType(), NewGV,
ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
ConstantInt::get(Int32Ty, 1)}),
&M);
Alias->setVisibility(B.GV->getVisibility());
Alias->takeName(B.GV);
B.GV->replaceAllUsesWith(Alias);
B.GV->eraseFromParent();
}
bool DevirtModule::areRemarksEnabled() {
const auto &FL = M.getFunctionList();
for (const Function &Fn : FL) {
const auto &BBL = Fn.getBasicBlockList();
if (BBL.empty())
continue;
auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
return DI.isEnabled();
}
return false;
}
void DevirtModule::scanTypeTestUsers(
Function *TypeTestFunc,
DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) {
auto *CI = dyn_cast<CallInst>(U.getUser());
if (!CI)
continue;
SmallVector<DevirtCallSite, 1> DevirtCalls;
SmallVector<CallInst *, 1> Assumes;
auto &DT = LookupDomTree(*CI->getFunction());
findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
Metadata *TypeId =
cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
if (!Assumes.empty()) {
Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
for (DevirtCallSite Call : DevirtCalls)
CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr);
}
auto RemoveTypeTestAssumes = [&]() {
for (auto Assume : Assumes)
Assume->eraseFromParent();
if (CI->use_empty())
CI->eraseFromParent();
};
if (!TypeIdMap.count(TypeId))
RemoveTypeTestAssumes();
else if (ImportSummary && isa<MDString>(TypeId)) {
const TypeIdSummary *TidSummary =
ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString());
if (!TidSummary)
RemoveTypeTestAssumes();
else
assert(TidSummary->TTRes.TheKind != TypeTestResolution::Unsat);
}
}
}
void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
for (Use &U : llvm::make_early_inc_range(TypeCheckedLoadFunc->uses())) {
auto *CI = dyn_cast<CallInst>(U.getUser());
if (!CI)
continue;
Value *Ptr = CI->getArgOperand(0);
Value *Offset = CI->getArgOperand(1);
Value *TypeIdValue = CI->getArgOperand(2);
Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
SmallVector<DevirtCallSite, 1> DevirtCalls;
SmallVector<Instruction *, 1> LoadedPtrs;
SmallVector<Instruction *, 1> Preds;
bool HasNonCallUses = false;
auto &DT = LookupDomTree(*CI->getFunction());
findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
HasNonCallUses, CI, DT);
IRBuilder<> LoadB(
(LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
for (Instruction *LoadedPtr : LoadedPtrs) {
LoadedPtr->replaceAllUsesWith(LoadedValue);
LoadedPtr->eraseFromParent();
}
IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
for (Instruction *Pred : Preds) {
Pred->replaceAllUsesWith(TypeTestCall);
Pred->eraseFromParent();
}
if (!CI->use_empty()) {
Value *Pair = PoisonValue::get(CI->getType());
IRBuilder<> B(CI);
Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
CI->replaceAllUsesWith(Pair);
}
auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
NumUnsafeUses = DevirtCalls.size();
if (HasNonCallUses)
++NumUnsafeUses;
for (DevirtCallSite Call : DevirtCalls) {
CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB,
&NumUnsafeUses);
}
CI->eraseFromParent();
}
}
void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
if (!TypeId)
return;
const TypeIdSummary *TidSummary =
ImportSummary->getTypeIdSummary(TypeId->getString());
if (!TidSummary)
return;
auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
if (ResI == TidSummary->WPDRes.end())
return;
const WholeProgramDevirtResolution &Res = ResI->second;
if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
assert(!Res.SingleImplName.empty());
Constant *SingleImpl =
cast<Constant>(M.getOrInsertFunction(Res.SingleImplName,
Type::getVoidTy(M.getContext()))
.getCallee());
bool IsExported = false;
applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
assert(!IsExported);
}
for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
auto I = Res.ResByArg.find(CSByConstantArg.first);
if (I == Res.ResByArg.end())
continue;
auto &ResByArg = I->second;
switch (ResByArg.TheKind) {
case WholeProgramDevirtResolution::ByArg::UniformRetVal:
applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
break;
case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
Constant *UniqueMemberAddr =
importGlobal(Slot, CSByConstantArg.first, "unique_member");
applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
UniqueMemberAddr);
break;
}
case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
Int32Ty, ResByArg.Byte);
Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
ResByArg.Bit);
applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
break;
}
default:
break;
}
}
if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
Constant *JT = cast<Constant>(
M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
Type::getVoidTy(M.getContext()))
.getCallee());
bool IsExported = false;
applyICallBranchFunnel(SlotInfo, JT, IsExported);
assert(!IsExported);
}
}
void DevirtModule::removeRedundantTypeTests() {
auto True = ConstantInt::getTrue(M.getContext());
for (auto &&U : NumUnsafeUsesForTypeTest) {
if (U.second == 0) {
U.first->replaceAllUsesWith(True);
U.first->eraseFromParent();
}
}
}
ValueInfo
DevirtModule::lookUpFunctionValueInfo(Function *TheFn,
ModuleSummaryIndex *ExportSummary) {
assert((ExportSummary != nullptr) &&
"Caller guarantees ExportSummary is not nullptr");
const auto TheFnGUID = TheFn->getGUID();
const auto TheFnGUIDWithExportedName = GlobalValue::getGUID(TheFn->getName());
ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFnGUID);
if ((!TheFnVI) && (TheFnGUID != TheFnGUIDWithExportedName)) {
TheFnVI = ExportSummary->getValueInfo(TheFnGUIDWithExportedName);
}
return TheFnVI;
}
bool DevirtModule::mustBeUnreachableFunction(
Function *const F, ModuleSummaryIndex *ExportSummary) {
if (!F->isDeclaration()) {
return isa<UnreachableInst>(F->getEntryBlock().getTerminator());
}
return ExportSummary &&
::mustBeUnreachableFunction(
DevirtModule::lookUpFunctionValueInfo(F, ExportSummary));
}
bool DevirtModule::run() {
if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
(ImportSummary && ImportSummary->partiallySplitLTOUnits()))
return false;
Function *TypeTestFunc =
M.getFunction(Intrinsic::getName(Intrinsic::type_test));
Function *TypeCheckedLoadFunc =
M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
if (!ExportSummary &&
(!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
AssumeFunc->use_empty()) &&
(!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
return false;
std::vector<VTableBits> Bits;
DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
buildTypeIdentifierMap(Bits, TypeIdMap);
if (TypeTestFunc && AssumeFunc)
scanTypeTestUsers(TypeTestFunc, TypeIdMap);
if (TypeCheckedLoadFunc)
scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
if (ImportSummary) {
for (auto &S : CallSlots)
importResolution(S.first, S.second);
removeRedundantTypeTests();
for (GlobalVariable &GV : M.globals())
GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
return true;
}
if (TypeIdMap.empty())
return true;
if (ExportSummary) {
DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
for (auto &P : TypeIdMap) {
if (auto *TypeId = dyn_cast<MDString>(P.first))
MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
TypeId);
}
for (auto &P : *ExportSummary) {
for (auto &S : P.second.SummaryList) {
auto *FS = dyn_cast<FunctionSummary>(S.get());
if (!FS)
continue;
for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
for (Metadata *MD : MetadataByGUID[VF.GUID]) {
CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
}
}
for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
for (Metadata *MD : MetadataByGUID[VF.GUID]) {
CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
}
}
for (const FunctionSummary::ConstVCall &VC :
FS->type_test_assume_const_vcalls()) {
for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
CallSlots[{MD, VC.VFunc.Offset}]
.ConstCSInfo[VC.Args]
.addSummaryTypeTestAssumeUser(FS);
}
}
for (const FunctionSummary::ConstVCall &VC :
FS->type_checked_load_const_vcalls()) {
for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
CallSlots[{MD, VC.VFunc.Offset}]
.ConstCSInfo[VC.Args]
.addSummaryTypeCheckedLoadUser(FS);
}
}
}
}
}
bool DidVirtualConstProp = false;
std::map<std::string, Function*> DevirtTargets;
for (auto &S : CallSlots) {
std::vector<VirtualCallTarget> TargetsForSlot;
WholeProgramDevirtResolution *Res = nullptr;
const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID];
if (ExportSummary && isa<MDString>(S.first.TypeID) &&
TypeMemberInfos.size())
Res = &ExportSummary
->getOrInsertTypeIdSummary(
cast<MDString>(S.first.TypeID)->getString())
.WPDRes[S.first.ByteOffset];
if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos,
S.first.ByteOffset, ExportSummary)) {
if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) {
DidVirtualConstProp |=
tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
}
if (RemarksEnabled || AreStatisticsEnabled())
for (const auto &T : TargetsForSlot)
if (T.WasDevirt)
DevirtTargets[std::string(T.Fn->getName())] = T.Fn;
}
if (ExportSummary && isa<MDString>(S.first.TypeID)) {
auto GUID =
GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
FS->addTypeTest(GUID);
for (auto &CCS : S.second.ConstCSInfo)
for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
FS->addTypeTest(GUID);
}
}
if (RemarksEnabled) {
for (const auto &DT : DevirtTargets) {
Function *F = DT.second;
using namespace ore;
OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
<< "devirtualized "
<< NV("FunctionName", DT.first));
}
}
NumDevirtTargets += DevirtTargets.size();
removeRedundantTypeTests();
if (DidVirtualConstProp)
for (VTableBits &B : Bits)
rebuildGlobal(B);
for (GlobalVariable &GV : M.globals())
GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
return true;
}
void DevirtIndex::run() {
if (ExportSummary.typeIdCompatibleVtableMap().empty())
return;
DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first);
}
for (auto &P : ExportSummary) {
for (auto &S : P.second.SummaryList) {
auto *FS = dyn_cast<FunctionSummary>(S.get());
if (!FS)
continue;
for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
for (StringRef Name : NameByGUID[VF.GUID]) {
CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
}
}
for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
for (StringRef Name : NameByGUID[VF.GUID]) {
CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
}
}
for (const FunctionSummary::ConstVCall &VC :
FS->type_test_assume_const_vcalls()) {
for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
CallSlots[{Name, VC.VFunc.Offset}]
.ConstCSInfo[VC.Args]
.addSummaryTypeTestAssumeUser(FS);
}
}
for (const FunctionSummary::ConstVCall &VC :
FS->type_checked_load_const_vcalls()) {
for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
CallSlots[{Name, VC.VFunc.Offset}]
.ConstCSInfo[VC.Args]
.addSummaryTypeCheckedLoadUser(FS);
}
}
}
}
std::set<ValueInfo> DevirtTargets;
for (auto &S : CallSlots) {
std::vector<ValueInfo> TargetsForSlot;
auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
assert(TidSummary);
WholeProgramDevirtResolution *Res =
&ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID)
.WPDRes[S.first.ByteOffset];
if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
S.first.ByteOffset)) {
if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
DevirtTargets))
continue;
}
}
if (PrintSummaryDevirt)
for (const auto &DT : DevirtTargets)
errs() << "Devirtualized call to " << DT << "\n";
NumDevirtTargets += DevirtTargets.size();
}