37#define INSTR_PROF_VALUE_PROF_MEMOP_API
52#define DEBUG_TYPE "pgo-memop-opt"
54STATISTIC(NumOfPGOMemOPOpt,
"Number of memop intrinsics optimized.");
55STATISTIC(NumOfPGOMemOPAnnotate,
"Number of memop intrinsics annotated.");
62 cl::desc(
"The minimum count to optimize memory "
74 cl::desc(
"The percentage threshold for the "
75 "memory intrinsic calls optimization"));
80 cl::desc(
"The max version for the optimized memory "
86 cl::desc(
"Scale the memop size counts using the basic "
87 " block count value"));
92 cl::desc(
"Size-specialize memcmp and bcmp calls"));
96 cl::desc(
"Optimize the memop size <= this value"));
103 switch (
MI->getIntrinsicID()) {
104 case Intrinsic::memcpy:
106 case Intrinsic::memmove:
108 case Intrinsic::memset:
118 MemOp(MemIntrinsic *
MI) : I(
MI) {}
119 MemOp(CallInst *CI) : I(CI) {}
123 if (
auto MI = asMI())
128 if (
auto MI = asMI())
129 return MI->getLength();
130 return asCI()->getArgOperand(2);
133 if (
auto MI = asMI())
135 asCI()->setArgOperand(2,
Length);
137 StringRef getFuncName() {
138 if (
auto MI = asMI())
139 return MI->getCalledFunction()->getName();
140 return asCI()->getCalledFunction()->getName();
143 if (
auto MI = asMI())
144 if (
MI->getIntrinsicID() == Intrinsic::memmove)
148 bool isMemcmp(TargetLibraryInfo &TLI) {
149 return asMI() ==
nullptr && TLI.
getLibFunc(*asCI()) == LibFunc_memcmp;
151 bool isBcmp(TargetLibraryInfo &TLI) {
152 return asMI() ==
nullptr && TLI.
getLibFunc(*asCI()) == LibFunc_bcmp;
154 const char *
getName(TargetLibraryInfo &TLI) {
155 if (
auto MI = asMI())
156 return getMIName(
MI);
158 if (Func == LibFunc_memcmp)
160 if (Func == LibFunc_bcmp)
167class MemOPSizeOpt :
public InstVisitor<MemOPSizeOpt> {
169 MemOPSizeOpt(
Function &Func, BlockFrequencyInfo &BFI,
170 OptimizationRemarkEmitter &ORE, DominatorTree *DT,
171 TargetLibraryInfo &TLI)
172 : Func(Func), BFI(BFI), ORE(ORE), DT(DT), TLI(TLI), Changed(
false) {}
173 bool isChanged()
const {
return Changed; }
178 for (
auto &MO : WorkList) {
179 ++NumOfPGOMemOPAnnotate;
184 <<
"is Transformed.\n");
189 void visitMemIntrinsic(MemIntrinsic &
MI) {
194 WorkList.push_back(MemOp(&
MI));
197 void visitCallInst(CallInst &CI) {
198 LibFunc Func = TLI.getLibFunc(CI);
199 if ((Func == LibFunc_memcmp || Func == LibFunc_bcmp) &&
201 WorkList.push_back(MemOp(&CI));
207 BlockFrequencyInfo &BFI;
208 OptimizationRemarkEmitter &ORE;
210 TargetLibraryInfo &TLI;
212 std::vector<MemOp> WorkList;
213 bool perform(MemOp MO);
231 return ScaleCount / Denom;
234bool MemOPSizeOpt::perform(
MemOp MO) {
241 uint32_t MaxNumVals = INSTR_PROF_NUM_BUCKETS;
249 uint64_t SavedTotalCount = TotalCount;
254 ActualCount = *BBEdgeCount;
257 LLVM_DEBUG(
dbgs() <<
"Read one memory intrinsic profile with count "
258 << ActualCount <<
"\n");
261 : VDs) {
dbgs() <<
" (" << VD.Value <<
"," << VD.Count <<
")\n"; });
270 TotalCount = ActualCount;
273 <<
" denominator = " << SavedTotalCount <<
"\n");
277 uint64_t SavedRemainCount = SavedTotalCount;
278 SmallVector<uint64_t, 16> SizeIds;
279 SmallVector<uint64_t, 16> CaseCounts;
285 for (
auto I = VDs.begin(),
E = VDs.end();
I !=
E; ++
I) {
287 int64_t
V = VD.Value;
290 C = getScaledCount(
C, ActualCount, SavedTotalCount);
311 assert(SavedRemainCount >= VD.Count);
312 SavedRemainCount -= VD.Count;
323 CaseCounts[0] = RemainCount;
324 if (RemainCount > MaxCount)
325 MaxCount = RemainCount;
327 uint64_t SumForOpt = TotalCount - RemainCount;
330 <<
" Versions (covering " << SumForOpt <<
" out of "
331 << TotalCount <<
")\n");
359 MergeBB->
setName(
"MemOP.Merge");
361 DefaultBB->
setName(
"MemOP.Default");
363 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
364 auto &Ctx =
Func.getContext();
367 Value *SizeVar = MO.getLength();
368 SwitchInst *
SI = IRB.CreateSwitch(SizeVar, DefaultBB, SizeIds.
size());
369 Type *MemOpTy = MO.I->getType();
370 PHINode *
PHI =
nullptr;
374 PHI = IRBM.CreatePHI(MemOpTy, SizeIds.
size() + 1,
"MemOP.RVMerge");
375 MO.I->replaceAllUsesWith(
PHI);
376 PHI->addIncoming(MO.I, DefaultBB);
380 MO.I->setMetadata(LLVMContext::MD_prof,
nullptr);
382 if (SavedRemainCount > 0 ||
Version != VDs.size()) {
385 IPVK_MemOPSize, VDs.
size());
390 std::vector<DominatorTree::UpdateType> Updates;
392 Updates.reserve(2 * SizeIds.
size());
396 Ctx, Twine(
"MemOP.Case.") + Twine(SizeId), &Func, DefaultBB);
397 MemOp NewMO = MO.clone();
400 assert(SizeType &&
"Expected integer type size argument.");
401 ConstantInt *CaseSizeId = ConstantInt::get(SizeType, SizeId);
402 NewMO.setLength(CaseSizeId);
403 NewMO.I->insertInto(CaseBB, CaseBB->
end());
405 IRBCase.CreateBr(MergeBB);
406 SI->addCase(CaseSizeId, CaseBB);
408 PHI->addIncoming(NewMO.I, CaseBB);
410 Updates.push_back({DominatorTree::Insert, CaseBB, MergeBB});
411 Updates.push_back({DominatorTree::Insert, BB, CaseBB});
415 DTU.applyUpdates(Updates);
427 return OptimizationRemark(
DEBUG_TYPE,
"memopt-opt", MO.I)
428 <<
"optimized " <<
NV(
"Memop", MO.getName(TLI)) <<
" with count "
429 <<
NV(
"Count", SumForOpt) <<
" out of " <<
NV(
"Total", TotalCount)
430 <<
" for " <<
NV(
"Versions",
Version) <<
" versions";
445 MemOPSizeOpt MemOPSizeOpt(
F, BFI, ORE, DT, TLI);
446 MemOPSizeOpt.perform();
447 return MemOPSizeOpt.isChanged();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This header defines various interfaces for pass management in LLVM.
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
static bool PGOMemOPSizeOptImpl(Function &F, BlockFrequencyInfo &BFI, OptimizationRemarkEmitter &ORE, DominatorTree *DT, TargetLibraryInfo &TLI)
FunctionAnalysisManager FAM
static StringRef getName(Value *V)
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB, bool AllowSynthetic=false) const
Returns the estimated profile count of BB.
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Value * getArgOperand(unsigned i) const
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Base class for instruction visitors.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This is the common base class for memset/memcpy/memmove.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &MAM)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
bool isVoidTy() const
Return true if this is 'void'.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void setProfMetadata(Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
static cl::opt< bool > MemOPScaleCount("pgo-memop-scale-count", cl::init(true), cl::Hidden, cl::desc("Scale the memop size counts using the basic " " block count value"))
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
static cl::opt< bool > DisableMemOPOPT("disable-memop-opt", cl::init(false), cl::Hidden, cl::desc("Disable optimize"))
static cl::opt< unsigned > MemOPCountThreshold("pgo-memop-count-threshold", cl::Hidden, cl::init(1000), cl::desc("The minimum count to optimize memory " "intrinsic calls"))
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
static cl::opt< unsigned > MemOpMaxOptSize("memop-value-prof-max-opt-size", cl::Hidden, cl::init(128), cl::desc("Optimize the memop size <= this value"))
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
cl::opt< bool > MemOPOptMemcmpBcmp("pgo-memop-optimize-memcmp-bcmp", cl::init(true), cl::Hidden, cl::desc("Size-specialize memcmp and bcmp calls"))
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
static cl::opt< unsigned > MemOPMaxVersion("pgo-memop-max-version", cl::init(3), cl::Hidden, cl::desc("The max version for the optimized memory " " intrinsic calls"))
static cl::opt< unsigned > MemOPPercentThreshold("pgo-memop-percent-threshold", cl::init(40), cl::Hidden, cl::desc("The percentage threshold for the " "memory intrinsic calls optimization"))
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.