#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/CodeMetrics.h"
#include "llvm/Analysis/InlineCost.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueLattice.h"
#include "llvm/Analysis/ValueLatticeUtils.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/Transforms/Scalar/SCCP.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/SCCPSolver.h"
#include "llvm/Transforms/Utils/SizeOpts.h"
#include <cmath>
using namespace llvm;
#define DEBUG_TYPE "function-specialization"
STATISTIC(NumFuncSpecialized, "Number of functions specialized");
static cl::opt<bool> ForceFunctionSpecialization(
"force-function-specialization", cl::init(false), cl::Hidden,
cl::desc("Force function specialization for every call site with a "
"constant argument"));
static cl::opt<unsigned> FuncSpecializationMaxIters(
"func-specialization-max-iters", cl::Hidden,
cl::desc("The maximum number of iterations function specialization is run"),
cl::init(1));
static cl::opt<unsigned> MaxClonesThreshold(
"func-specialization-max-clones", cl::Hidden,
cl::desc("The maximum number of clones allowed for a single function "
"specialization"),
cl::init(3));
static cl::opt<unsigned> SmallFunctionThreshold(
"func-specialization-size-threshold", cl::Hidden,
cl::desc("Don't specialize functions that have less than this theshold "
"number of instructions"),
cl::init(100));
static cl::opt<unsigned>
AvgLoopIterationCount("func-specialization-avg-iters-cost", cl::Hidden,
cl::desc("Average loop iteration count cost"),
cl::init(10));
static cl::opt<bool> SpecializeOnAddresses(
"func-specialization-on-address", cl::init(false), cl::Hidden,
cl::desc("Enable function specialization on the address of global values"));
static cl::opt<bool> EnableSpecializationForLiteralConstant(
"function-specialization-for-literal-constant", cl::init(false), cl::Hidden,
cl::desc("Enable specialization of functions that take a literal constant "
"as an argument."));
namespace {
struct SpecializationInfo {
SmallVector<ArgInfo, 8> Args; InstructionCost Gain; };
}
using FuncList = SmallVectorImpl<Function *>;
using CallArgBinding = std::pair<CallBase *, Constant *>;
using CallSpecBinding = std::pair<CallBase *, SpecializationInfo>;
using SpecializationMap = SmallMapVector<CallBase *, SpecializationInfo, 8>;
static bool isConstant(const ValueLatticeElement &LV) {
return LV.isConstant() ||
(LV.isConstantRange() && LV.getConstantRange().isSingleElement());
}
static bool isOverdefined(const ValueLatticeElement &LV) {
return !LV.isUnknownOrUndef() && !isConstant(LV);
}
static Constant *getPromotableAlloca(AllocaInst *Alloca, CallInst *Call) {
Value *StoreValue = nullptr;
for (auto *User : Alloca->users()) {
if (User == Call)
continue;
if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
return nullptr;
continue;
}
if (auto *Store = dyn_cast<StoreInst>(User)) {
if (StoreValue || Store->isVolatile())
return nullptr;
StoreValue = Store->getValueOperand();
continue;
}
return nullptr;
}
return dyn_cast_or_null<Constant>(StoreValue);
}
static Constant *getConstantStackValue(CallInst *Call, Value *Val,
SCCPSolver &Solver) {
if (!Val)
return nullptr;
Val = Val->stripPointerCasts();
if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
return ConstVal;
auto *Alloca = dyn_cast<AllocaInst>(Val);
if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
return nullptr;
return getPromotableAlloca(Alloca, Call);
}
static void constantArgPropagation(FuncList &WorkList, Module &M,
SCCPSolver &Solver) {
for (auto *F : WorkList) {
for (auto *User : F->users()) {
auto *Call = dyn_cast<CallInst>(User);
if (!Call)
continue;
bool Changed = false;
for (const Use &U : Call->args()) {
unsigned Idx = Call->getArgOperandNo(&U);
Value *ArgOp = Call->getArgOperand(Idx);
Type *ArgOpType = ArgOp->getType();
if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
continue;
auto *ConstVal = getConstantStackValue(Call, ArgOp, Solver);
if (!ConstVal)
continue;
Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
GlobalValue::InternalLinkage, ConstVal,
"funcspec.arg");
if (ArgOpType != ConstVal->getType())
GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOpType);
Call->setArgOperand(Idx, GV);
Changed = true;
}
if (Changed)
Solver.visitCall(*Call);
}
}
}
static void removeSSACopy(Function &F) {
for (BasicBlock &BB : F) {
for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
auto *II = dyn_cast<IntrinsicInst>(&Inst);
if (!II)
continue;
if (II->getIntrinsicID() != Intrinsic::ssa_copy)
continue;
Inst.replaceAllUsesWith(II->getOperand(0));
Inst.eraseFromParent();
}
}
}
static void removeSSACopy(Module &M) {
for (Function &F : M)
removeSSACopy(F);
}
namespace {
class FunctionSpecializer {
SCCPSolver &Solver;
std::function<AssumptionCache &(Function &)> GetAC;
std::function<TargetTransformInfo &(Function &)> GetTTI;
std::function<TargetLibraryInfo &(Function &)> GetTLI;
SmallPtrSet<Function *, 4> SpecializedFuncs;
SmallPtrSet<Function *, 4> FullySpecialized;
SmallVector<Instruction *> ReplacedWithConstant;
DenseMap<Function *, CodeMetrics> FunctionMetrics;
public:
FunctionSpecializer(SCCPSolver &Solver,
std::function<AssumptionCache &(Function &)> GetAC,
std::function<TargetTransformInfo &(Function &)> GetTTI,
std::function<TargetLibraryInfo &(Function &)> GetTLI)
: Solver(Solver), GetAC(GetAC), GetTTI(GetTTI), GetTLI(GetTLI) {}
~FunctionSpecializer() {
removeDeadInstructions();
removeDeadFunctions();
}
bool specializeFunctions(FuncList &Candidates, FuncList &WorkList) {
bool Changed = false;
for (auto *F : Candidates) {
if (!isCandidateFunction(F))
continue;
auto Cost = getSpecializationCost(F);
if (!Cost.isValid()) {
LLVM_DEBUG(
dbgs() << "FnSpecialization: Invalid specialization cost.\n");
continue;
}
LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
<< F->getName() << " is " << Cost << "\n");
SmallVector<CallSpecBinding, 8> Specializations;
if (!calculateGains(F, Cost, Specializations)) {
LLVM_DEBUG(dbgs() << "FnSpecialization: No possible constants found\n");
continue;
}
Changed = true;
for (auto &Entry : Specializations)
specializeFunction(F, Entry.second, WorkList);
}
updateSpecializedFuncs(Candidates, WorkList);
NumFuncSpecialized += NbFunctionsSpecialized;
return Changed;
}
void removeDeadInstructions() {
for (auto *I : ReplacedWithConstant) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead instruction " << *I
<< "\n");
I->eraseFromParent();
}
ReplacedWithConstant.clear();
}
void removeDeadFunctions() {
for (auto *F : FullySpecialized) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
<< F->getName() << "\n");
F->eraseFromParent();
}
FullySpecialized.clear();
}
bool tryToReplaceWithConstant(Value *V) {
if (!V->getType()->isSingleValueType() || isa<CallBase>(V) ||
V->user_empty())
return false;
const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
if (isOverdefined(IV))
return false;
auto *Const =
isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType());
LLVM_DEBUG(dbgs() << "FnSpecialization: Replacing " << *V
<< "\nFnSpecialization: with " << *Const << "\n");
SmallVector<Instruction *> UseInsts;
for (auto *U : V->users())
if (auto *I = dyn_cast<Instruction>(U))
if (Solver.isBlockExecutable(I->getParent()))
UseInsts.push_back(I);
V->replaceAllUsesWith(Const);
for (auto *I : UseInsts)
Solver.visit(I);
if (auto *I = dyn_cast<Instruction>(V)) {
if (I->isSafeToRemove()) {
ReplacedWithConstant.push_back(I);
Solver.removeLatticeValueFor(I);
}
}
return true;
}
private:
unsigned NbFunctionsSpecialized = 0;
CodeMetrics &analyzeFunction(Function *F) {
auto I = FunctionMetrics.insert({F, CodeMetrics()});
CodeMetrics &Metrics = I.first->second;
if (I.second) {
SmallPtrSet<const Value *, 32> EphValues;
CodeMetrics::collectEphemeralValues(F, &(GetAC)(*F), EphValues);
for (BasicBlock &BB : *F)
Metrics.analyzeBasicBlock(&BB, (GetTTI)(*F), EphValues);
LLVM_DEBUG(dbgs() << "FnSpecialization: Code size of function "
<< F->getName() << " is " << Metrics.NumInsts
<< " instructions\n");
}
return Metrics;
}
Function *cloneCandidateFunction(Function *F, ValueToValueMapTy &Mappings) {
Function *Clone = CloneFunction(F, Mappings);
removeSSACopy(*Clone);
return Clone;
}
bool calculateGains(Function *F, InstructionCost Cost,
SmallVectorImpl<CallSpecBinding> &WorkList) {
SpecializationMap Specializations;
for (Argument &FormalArg : F->args()) {
SmallVector<CallArgBinding, 8> ActualArgs;
if (!isArgumentInteresting(&FormalArg, ActualArgs)) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Argument "
<< FormalArg.getNameOrAsOperand()
<< " is not interesting\n");
continue;
}
for (const auto &Entry : ActualArgs) {
CallBase *Call = Entry.first;
Constant *ActualArg = Entry.second;
auto I = Specializations.insert({Call, SpecializationInfo()});
SpecializationInfo &S = I.first->second;
if (I.second)
S.Gain = ForceFunctionSpecialization ? 1 : 0 - Cost;
if (!ForceFunctionSpecialization)
S.Gain += getSpecializationBonus(&FormalArg, ActualArg);
S.Args.push_back({&FormalArg, ActualArg});
}
}
Specializations.remove_if(
[](const auto &Entry) { return Entry.second.Gain <= 0; });
WorkList = Specializations.takeVector();
llvm::stable_sort(WorkList, [](const auto &L, const auto &R) {
return L.second.Gain > R.second.Gain;
});
if (WorkList.size() > MaxClonesThreshold) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
<< "the maximum number of clones threshold.\n"
<< "FnSpecialization: Truncating worklist to "
<< MaxClonesThreshold << " candidates.\n");
WorkList.erase(WorkList.begin() + MaxClonesThreshold, WorkList.end());
}
LLVM_DEBUG(dbgs() << "FnSpecialization: Specializations for function "
<< F->getName() << "\n";
for (const auto &Entry
: WorkList) {
dbgs() << "FnSpecialization: Gain = " << Entry.second.Gain
<< "\n";
for (const ArgInfo &Arg : Entry.second.Args)
dbgs() << "FnSpecialization: FormalArg = "
<< Arg.Formal->getNameOrAsOperand()
<< ", ActualArg = "
<< Arg.Actual->getNameOrAsOperand() << "\n";
});
return !WorkList.empty();
}
bool isCandidateFunction(Function *F) {
if (SpecializedFuncs.contains(F))
return false;
if (F->hasOptSize() ||
shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
return false;
if (!Solver.isBlockExecutable(&F->getEntryBlock()))
return false;
if (F->hasFnAttribute(Attribute::AlwaysInline))
return false;
LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
<< "\n");
return true;
}
void specializeFunction(Function *F, SpecializationInfo &S,
FuncList &WorkList) {
ValueToValueMapTy Mappings;
Function *Clone = cloneCandidateFunction(F, Mappings);
rewriteCallSites(Clone, S.Args, Mappings);
Solver.markArgInFuncSpecialization(Clone, S.Args);
WorkList.push_back(Clone);
NbFunctionsSpecialized++;
if (F->getNumUses() == 0 || all_of(F->users(), [F](User *U) {
if (auto *CS = dyn_cast<CallBase>(U))
return CS->getFunction() == F;
return false;
})) {
Solver.markFunctionUnreachable(F);
FullySpecialized.insert(F);
}
}
InstructionCost getSpecializationCost(Function *F) {
CodeMetrics &Metrics = analyzeFunction(F);
if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
(!ForceFunctionSpecialization &&
*Metrics.NumInsts.getValue() < SmallFunctionThreshold)) {
InstructionCost C{};
C.setInvalid();
return C;
}
unsigned Penalty = NbFunctionsSpecialized + 1;
return Metrics.NumInsts * InlineConstants::InstrCost * Penalty;
}
InstructionCost getUserBonus(User *U, llvm::TargetTransformInfo &TTI,
LoopInfo &LI) {
auto *I = dyn_cast_or_null<Instruction>(U);
if (!I)
return std::numeric_limits<unsigned>::min();
auto Cost = TTI.getUserCost(U, TargetTransformInfo::TCK_SizeAndLatency);
if (I->mayReadFromMemory() || I->isCast())
for (auto *User : I->users())
Cost += getUserBonus(User, TTI, LI);
auto LoopDepth = LI.getLoopDepth(I->getParent());
Cost *= std::pow((double)AvgLoopIterationCount, LoopDepth);
return Cost;
}
InstructionCost getSpecializationBonus(Argument *A, Constant *C) {
Function *F = A->getParent();
DominatorTree DT(*F);
LoopInfo LI(DT);
auto &TTI = (GetTTI)(*F);
LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
<< C->getNameOrAsOperand() << "\n");
InstructionCost TotalCost = 0;
for (auto *U : A->users()) {
TotalCost += getUserBonus(U, TTI, LI);
LLVM_DEBUG(dbgs() << "FnSpecialization: User cost ";
TotalCost.print(dbgs()); dbgs() << " for: " << *U << "\n");
}
Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
if (!CalledFunction)
return TotalCost;
auto &CalleeTTI = (GetTTI)(*CalledFunction);
int Bonus = 0;
for (User *U : A->users()) {
if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
continue;
auto *CS = cast<CallBase>(U);
if (CS->getCalledOperand() != A)
continue;
auto Params = getInlineParams();
Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
InlineCost IC =
getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
if (IC.isAlways())
Bonus += Params.DefaultThreshold;
else if (IC.isVariable() && IC.getCostDelta() > 0)
Bonus += IC.getCostDelta();
LLVM_DEBUG(dbgs() << "FnSpecialization: Inlining bonus " << Bonus
<< " for user " << *U << "\n");
}
return TotalCost + Bonus;
}
bool isArgumentInteresting(Argument *A,
SmallVectorImpl<CallArgBinding> &Constants) {
if (!A->getType()->isSingleValueType() || A->user_empty())
return false;
if (!Solver.getLatticeValueFor(A).isOverdefined()) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Nothing to do, argument "
<< A->getNameOrAsOperand()
<< " is already constant?\n");
return false;
}
getPossibleConstants(A, Constants);
if (Constants.empty())
return false;
LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
<< A->getNameOrAsOperand() << "\n");
return true;
}
void getPossibleConstants(Argument *A,
SmallVectorImpl<CallArgBinding> &Constants) {
Function *F = A->getParent();
if (A->hasByValAttr() && !F->onlyReadsMemory())
return;
for (User *U : F->users()) {
if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
continue;
auto &CS = *cast<CallBase>(U);
if (CS.hasFnAttr(Attribute::MinSize))
continue;
if (!Solver.isBlockExecutable(CS.getParent()))
continue;
auto *V = CS.getArgOperand(A->getArgNo());
if (isa<PoisonValue>(V))
return;
if (auto *GV = dyn_cast<GlobalVariable>(V)) {
if (!GV->isConstant())
if (!SpecializeOnAddresses)
return;
if (!GV->getValueType()->isSingleValueType())
return;
}
if (isa<Constant>(V) && (Solver.getLatticeValueFor(V).isConstant() ||
EnableSpecializationForLiteralConstant))
Constants.push_back({&CS, cast<Constant>(V)});
}
}
void rewriteCallSites(Function *Clone, const SmallVectorImpl<ArgInfo> &Args,
ValueToValueMapTy &Mappings) {
assert(!Args.empty() && "Specialization without arguments");
Function *F = Args[0].Formal->getParent();
SmallVector<CallBase *, 8> CallSitesToRewrite;
for (auto *U : F->users()) {
if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
continue;
auto &CS = *cast<CallBase>(U);
if (!CS.getCalledFunction() || CS.getCalledFunction() != F)
continue;
CallSitesToRewrite.push_back(&CS);
}
LLVM_DEBUG(dbgs() << "FnSpecialization: Replacing call sites of "
<< F->getName() << " with " << Clone->getName() << "\n");
for (auto *CS : CallSitesToRewrite) {
LLVM_DEBUG(dbgs() << "FnSpecialization: "
<< CS->getFunction()->getName() << " ->" << *CS
<< "\n");
if (
(CS->getFunction() == Clone &&
all_of(Args,
[CS, &Mappings](const ArgInfo &Arg) {
unsigned ArgNo = Arg.Formal->getArgNo();
return CS->getArgOperand(ArgNo) == Mappings[Arg.Formal];
})) ||
all_of(Args, [CS](const ArgInfo &Arg) {
unsigned ArgNo = Arg.Formal->getArgNo();
return CS->getArgOperand(ArgNo) == Arg.Actual;
})) {
CS->setCalledFunction(Clone);
Solver.markOverdefined(CS);
}
}
}
void updateSpecializedFuncs(FuncList &Candidates, FuncList &WorkList) {
for (auto *F : WorkList) {
SpecializedFuncs.insert(F);
if (F->hasExactDefinition() && !F->hasFnAttribute(Attribute::Naked))
Solver.addTrackedFunction(F);
Solver.addArgumentTrackedFunction(F);
Candidates.push_back(F);
Solver.markBlockExecutable(&F->front());
for (Argument &Arg : F->args())
if (!Arg.use_empty() && tryToReplaceWithConstant(&Arg))
LLVM_DEBUG(dbgs() << "FnSpecialization: Replaced constant argument: "
<< Arg.getNameOrAsOperand() << "\n");
}
}
};
}
bool llvm::runFunctionSpecialization(
Module &M, const DataLayout &DL,
std::function<TargetLibraryInfo &(Function &)> GetTLI,
std::function<TargetTransformInfo &(Function &)> GetTTI,
std::function<AssumptionCache &(Function &)> GetAC,
function_ref<AnalysisResultsForFn(Function &)> GetAnalysis) {
SCCPSolver Solver(DL, GetTLI, M.getContext());
FunctionSpecializer FS(Solver, GetAC, GetTTI, GetTLI);
bool Changed = false;
for (Function &F : M) {
if (F.isDeclaration())
continue;
if (F.hasFnAttribute(Attribute::NoDuplicate))
continue;
LLVM_DEBUG(dbgs() << "\nFnSpecialization: Analysing decl: " << F.getName()
<< "\n");
Solver.addAnalysis(F, GetAnalysis(F));
if (canTrackArgumentsInterprocedurally(&F)) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Can track arguments\n");
Solver.addArgumentTrackedFunction(&F);
continue;
} else {
LLVM_DEBUG(dbgs() << "FnSpecialization: Can't track arguments!\n"
<< "FnSpecialization: Doesn't have local linkage, or "
<< "has its address taken\n");
}
Solver.markBlockExecutable(&F.front());
for (Argument &AI : F.args())
Solver.markOverdefined(&AI);
}
for (GlobalVariable &G : M.globals()) {
G.removeDeadConstantUsers();
if (canTrackGlobalVariableInterprocedurally(&G))
Solver.trackValueOfGlobalVariable(&G);
}
auto &TrackedFuncs = Solver.getArgumentTrackedFunctions();
SmallVector<Function *, 16> FuncDecls(TrackedFuncs.begin(),
TrackedFuncs.end());
if (TrackedFuncs.empty()) {
removeSSACopy(M);
return false;
}
auto RunSCCPSolver = [&](auto &WorkList) {
bool ResolvedUndefs = true;
while (ResolvedUndefs) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Running solver\n");
Solver.solve();
LLVM_DEBUG(dbgs() << "FnSpecialization: Resolving undefs\n");
ResolvedUndefs = false;
for (Function *F : WorkList)
if (Solver.resolvedUndefsIn(*F))
ResolvedUndefs = true;
}
for (auto *F : WorkList) {
for (BasicBlock &BB : *F) {
if (!Solver.isBlockExecutable(&BB))
continue;
for (auto &I : make_early_inc_range(BB))
Changed |= FS.tryToReplaceWithConstant(&I);
}
}
};
#ifndef NDEBUG
LLVM_DEBUG(dbgs() << "FnSpecialization: Worklist fn decls:\n");
for (auto *F : FuncDecls)
LLVM_DEBUG(dbgs() << "FnSpecialization: *) " << F->getName() << "\n");
#endif
RunSCCPSolver(FuncDecls);
SmallVector<Function *, 8> WorkList;
unsigned I = 0;
while (FuncSpecializationMaxIters != I++ &&
FS.specializeFunctions(FuncDecls, WorkList)) {
LLVM_DEBUG(dbgs() << "FnSpecialization: Finished iteration " << I << "\n");
RunSCCPSolver(WorkList);
constantArgPropagation(FuncDecls, M, Solver);
WorkList.clear();
Changed = true;
}
LLVM_DEBUG(dbgs() << "FnSpecialization: Number of specializations = "
<< NumFuncSpecialized << "\n");
removeSSACopy(M);
return Changed;
}