33#define DEBUG_TYPE "loop-data-prefetch"
37STATISTIC(NumPrefetches,
"Number of prefetches inserted");
42class LoopDataPrefetch {
48 : Opts(Opts), AC(AC), DT(DT), LI(LI), SE(SE),
TTI(
TTI), ORE(ORE) {}
53 bool runOnLoop(
Loop *L);
57 bool isStrideLargeEnough(
const SCEVAddRecExpr *AR,
unsigned TargetMinStride);
59 unsigned getMinPrefetchStride(
unsigned NumMemAccesses,
60 unsigned NumStridedMemAccesses,
61 unsigned NumPrefetches,
63 if (Opts.min_prefetch_stride)
64 return *Opts.min_prefetch_stride;
65 return TTI->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
66 NumPrefetches, HasCall);
69 unsigned getPrefetchDistance() {
70 if (Opts.prefetch_distance)
71 return *Opts.prefetch_distance;
72 return TTI->getPrefetchDistance();
75 unsigned getMaxPrefetchIterationsAhead() {
76 if (Opts.max_prefetch_iters_ahead)
77 return *Opts.max_prefetch_iters_ahead;
78 return TTI->getMaxPrefetchIterationsAhead();
81 bool doPrefetchWrites() {
82 return valueOr(Opts.loop_prefetch_writes, TTI->enableWritePrefetching());
85 const ScalarOptions &Opts;
90 const TargetTransformInfo *TTI;
91 OptimizationRemarkEmitter *ORE;
98 LoopDataPrefetchLegacyPass() : FunctionPass(ID) {
102 void getAnalysisUsage(AnalysisUsage &AU)
const override {
110 AU.
addRequired<OptimizationRemarkEmitterWrapperPass>();
120char LoopDataPrefetchLegacyPass::ID = 0;
122 "Loop Data Prefetch",
false,
false)
133 return new LoopDataPrefetchLegacyPass();
136bool LoopDataPrefetch::isStrideLargeEnough(
const SCEVAddRecExpr *AR,
137 unsigned TargetMinStride) {
139 if (TargetMinStride <= 1)
148 unsigned AbsStride = std::abs(ConstStride->getAPInt().getSExtValue());
149 return TargetMinStride <= AbsStride;
162 const ScalarOptions &Opts =
163 F.getContext().getLibraryOptions().get<ScalarOptions>();
164 LoopDataPrefetch LDP(Opts, AC, DT, LI, SE,
TTI, ORE);
177bool LoopDataPrefetchLegacyPass::runOnFunction(
Function &
F) {
181 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
182 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
183 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
185 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
F);
187 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
189 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
191 const ScalarOptions &Opts =
192 F.getContext().getLibraryOptions().get<ScalarOptions>();
193 LoopDataPrefetch LDP(Opts, AC, DT, LI, SE,
TTI, ORE);
197bool LoopDataPrefetch::run() {
201 if (getPrefetchDistance() == 0 ||
TTI->getCacheLineSize() == 0) {
202 LLVM_DEBUG(
dbgs() <<
"Please set both PrefetchDistance and CacheLineSize "
203 "for loop data prefetch.\n");
207 bool MadeChange =
false;
211 MadeChange |= runOnLoop(L);
238 int64_t PtrDiff = 0) {
246 if (PrefBB != InsBB) {
258bool LoopDataPrefetch::runOnLoop(
Loop *L) {
259 bool MadeChange =
false;
262 if (!
L->isInnermost())
265 SmallPtrSet<const Value *, 32> EphValues;
270 bool HasCall =
false;
271 for (
const auto BB :
L->blocks()) {
274 for (
auto &
I : *BB) {
277 if (
F->getIntrinsicID() == Intrinsic::prefetch)
286 Metrics.analyzeBasicBlock(BB, *
TTI, EphValues);
289 if (!
Metrics.NumInsts.isValid())
292 unsigned LoopSize =
Metrics.NumInsts.getValue();
296 unsigned ItersAhead = getPrefetchDistance() / LoopSize;
300 if (ItersAhead > getMaxPrefetchIterationsAhead())
304 if (ConstantMaxTripCount && ConstantMaxTripCount < ItersAhead + 1)
307 unsigned NumMemAccesses = 0;
308 unsigned NumStridedMemAccesses = 0;
310 for (
const auto BB :
L->blocks())
311 for (
auto &
I : *BB) {
317 PtrValue = LMemI->getPointerOperand();
319 if (!doPrefetchWrites())
continue;
321 PtrValue = SMemI->getPointerOperand();
328 if (
L->isLoopInvariant(PtrValue))
331 const SCEV *LSCEV = SE->
getSCEV(PtrValue);
335 NumStridedMemAccesses++;
340 bool DupPref =
false;
341 for (
auto &Pref : Prefetches) {
342 const SCEV *PtrDiff = SE->
getMinusSCEV(LSCEVAddRec, Pref.LSCEVAddRec);
343 if (
const SCEVConstant *ConstPtrDiff =
345 int64_t
PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
347 Pref.addInstruction(MemI, DT, PD);
354 Prefetches.push_back(
Prefetch(LSCEVAddRec, MemI));
357 unsigned TargetMinStride =
358 getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
359 Prefetches.size(), HasCall);
362 <<
" iterations ahead (loop size: " << LoopSize <<
") in "
363 <<
L->getHeader()->getParent()->getName() <<
": " << *L);
365 << NumMemAccesses <<
" memory accesses, "
366 << NumStridedMemAccesses <<
" strided memory accesses, "
367 << Prefetches.size() <<
" potential prefetch(es), "
368 <<
"a minimum stride of " << TargetMinStride <<
", "
369 << (HasCall ?
"calls" :
"no calls") <<
".\n");
371 for (
auto &
P : Prefetches) {
374 if (!isStrideLargeEnough(
P.LSCEVAddRec, TargetMinStride))
378 SCEVExpander SCEVE(*SE,
"prefaddr");
382 P.LSCEVAddRec->getStepRecurrence(*SE)));
383 if (!SCEVE.isSafeToExpand(NextLSCEV))
388 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr,
P.InsertPt);
392 Builder.CreateIntrinsic(Intrinsic::prefetch, PrefPtrValue->
getType(),
393 {PrefPtrValue, ConstantInt::get(I32, P.Writes),
394 ConstantInt::get(I32, 3),
395 ConstantInt::get(I32, 1)});
399 <<
", SCEV: " << *
P.LSCEVAddRec <<
"\n");
401 return OptimizationRemark(
DEBUG_TYPE,
"Prefetched",
P.MemI)
402 <<
"prefetched memory access";
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
loop data Loop Data Prefetch
This file provides the interface for LLVM's Loop Data Prefetching Pass.
static const Function * getCalledFunction(const Value *V)
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_ABI AnalysisUsage & addRequiredID(const void *ID)
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
FunctionPass class - This class is used to implement most global optimizations.
Analysis pass that exposes the LoopInfo for a function.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
The legacy pass manager's analysis pass to compute loop information.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
This node represents a polynomial recurrence on the trip count of the specified loop.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
Analysis pass providing the TargetTransformInfo.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getType() const
All values are typed, get the type of this value.
@ BasicBlock
Various leaf nodes.
@ PD
PD - Prefix code for packed double precision vector floating point operations performed in the SSE re...
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI char & LoopSimplifyID
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI FunctionPass * createLoopDataPrefetchPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI void initializeLoopDataPrefetchLegacyPassPass(PassRegistry &)
constexpr bool valueOr(BoolOrDefault X, bool Default)
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Instruction * InsertPt
The point of insertion for the prefetch instruction.
void addInstruction(Instruction *I, DominatorTree *DT=nullptr, int64_t PtrDiff=0)
Add the instruction.
bool Writes
True if targeting a write memory access.
Instruction * MemI
The (first seen) prefetched instruction.
const SCEVAddRecExpr * LSCEVAddRec
The address formula for this prefetch as returned by ScalarEvolution.
Prefetch(const SCEVAddRecExpr *L, Instruction *I)
Constructor to create a new Prefetch for I.
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).