blob: 66b59d27dfdeb3b34565e981c55c37cfc594d414 [file] [log] [blame]
Adam Nemet9d9cb272016-02-18 21:38:19 +00001//===-------- LoopDataPrefetch.cpp - Loop Data Prefetching Pass -----------===//
Hal Finkele5aaf3f2015-02-20 05:08:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a Loop Data Prefetching Pass.
11//
12//===----------------------------------------------------------------------===//
13
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000014#define DEBUG_TYPE "loop-data-prefetch"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000015#include "llvm/Transforms/Scalar.h"
Hal Finkela9fceb82015-04-10 15:05:02 +000016#include "llvm/ADT/DepthFirstIterator.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000017#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/CodeMetrics.h"
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000023#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000024#include "llvm/Analysis/ScalarEvolutionExpander.h"
25#include "llvm/Analysis/ScalarEvolutionExpressions.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
28#include "llvm/IR/CFG.h"
Adam Nemet3c5eabf2016-05-05 00:08:15 +000029#include "llvm/IR/DiagnosticInfo.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000030#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Module.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Local.h"
38#include "llvm/Transforms/Utils/ValueMapper.h"
39using namespace llvm;
40
41// By default, we limit this to creating 16 PHIs (which is a little over half
42// of the allocatable register set).
43static cl::opt<bool>
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000044PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false),
Hal Finkele5aaf3f2015-02-20 05:08:21 +000045 cl::desc("Prefetch write addresses"));
46
Adam Nemet1428d412016-03-29 23:45:52 +000047static cl::opt<unsigned>
48 PrefetchDistance("prefetch-distance",
49 cl::desc("Number of instructions to prefetch ahead"),
50 cl::Hidden);
51
52static cl::opt<unsigned>
53 MinPrefetchStride("min-prefetch-stride",
54 cl::desc("Min stride to add prefetches"), cl::Hidden);
55
56static cl::opt<unsigned> MaxPrefetchIterationsAhead(
57 "max-prefetch-iters-ahead",
58 cl::desc("Max number of iterations to prefetch ahead"), cl::Hidden);
59
Adam Nemet34785ec2016-03-09 05:33:21 +000060STATISTIC(NumPrefetches, "Number of prefetches inserted");
61
Hal Finkele5aaf3f2015-02-20 05:08:21 +000062namespace llvm {
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000063 void initializeLoopDataPrefetchPass(PassRegistry&);
Hal Finkele5aaf3f2015-02-20 05:08:21 +000064}
65
66namespace {
67
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000068 class LoopDataPrefetch : public FunctionPass {
Hal Finkele5aaf3f2015-02-20 05:08:21 +000069 public:
70 static char ID; // Pass ID, replacement for typeid
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000071 LoopDataPrefetch() : FunctionPass(ID) {
72 initializeLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
Hal Finkele5aaf3f2015-02-20 05:08:21 +000073 }
74
75 void getAnalysisUsage(AnalysisUsage &AU) const override {
76 AU.addRequired<AssumptionCacheTracker>();
77 AU.addPreserved<DominatorTreeWrapperPass>();
78 AU.addRequired<LoopInfoWrapperPass>();
79 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000080 AU.addRequired<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000081 // FIXME: For some reason, preserving SE here breaks LSR (even if
82 // this pass changes nothing).
Chandler Carruth2f1fd162015-08-17 02:08:17 +000083 // AU.addPreserved<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000084 AU.addRequired<TargetTransformInfoWrapperPass>();
85 }
86
87 bool runOnFunction(Function &F) override;
Adam Nemet85fba392016-03-29 22:40:02 +000088
89 private:
Hal Finkele5aaf3f2015-02-20 05:08:21 +000090 bool runOnLoop(Loop *L);
91
Adam Nemet6d8beec2016-03-18 00:27:38 +000092 /// \brief Check if the the stride of the accesses is large enough to
93 /// warrant a prefetch.
94 bool isStrideLargeEnough(const SCEVAddRecExpr *AR);
95
Adam Nemet1428d412016-03-29 23:45:52 +000096 unsigned getMinPrefetchStride() {
97 if (MinPrefetchStride.getNumOccurrences() > 0)
98 return MinPrefetchStride;
99 return TTI->getMinPrefetchStride();
100 }
101
102 unsigned getPrefetchDistance() {
103 if (PrefetchDistance.getNumOccurrences() > 0)
104 return PrefetchDistance;
105 return TTI->getPrefetchDistance();
106 }
107
108 unsigned getMaxPrefetchIterationsAhead() {
109 if (MaxPrefetchIterationsAhead.getNumOccurrences() > 0)
110 return MaxPrefetchIterationsAhead;
111 return TTI->getMaxPrefetchIterationsAhead();
112 }
113
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000114 AssumptionCache *AC;
115 LoopInfo *LI;
116 ScalarEvolution *SE;
117 const TargetTransformInfo *TTI;
118 const DataLayout *DL;
119 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000120}
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000121
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000122char LoopDataPrefetch::ID = 0;
123INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch",
124 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000125INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
126INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
127INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000128INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000129INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch",
130 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000131
Adam Nemet9d9cb272016-02-18 21:38:19 +0000132FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); }
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000133
Adam Nemet6d8beec2016-03-18 00:27:38 +0000134bool LoopDataPrefetch::isStrideLargeEnough(const SCEVAddRecExpr *AR) {
Adam Nemet1428d412016-03-29 23:45:52 +0000135 unsigned TargetMinStride = getMinPrefetchStride();
Adam Nemet6d8beec2016-03-18 00:27:38 +0000136 // No need to check if any stride goes.
137 if (TargetMinStride <= 1)
138 return true;
139
140 const auto *ConstStride = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
141 // If MinStride is set, don't prefetch unless we can ensure that stride is
142 // larger.
143 if (!ConstStride)
144 return false;
145
146 unsigned AbsStride = std::abs(ConstStride->getAPInt().getSExtValue());
147 return TargetMinStride <= AbsStride;
148}
149
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000150bool LoopDataPrefetch::runOnFunction(Function &F) {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000151 if (skipFunction(F))
152 return false;
153
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000154 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000155 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Mehdi Amini46a43552015-03-04 18:43:29 +0000156 DL = &F.getParent()->getDataLayout();
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000157 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
158 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
159
Adam Nemetbb3680b2016-03-07 18:35:42 +0000160 // If PrefetchDistance is not set, don't run the pass. This gives an
161 // opportunity for targets to run this pass for selected subtargets only
162 // (whose TTI sets PrefetchDistance).
Adam Nemet1428d412016-03-29 23:45:52 +0000163 if (getPrefetchDistance() == 0)
Adam Nemetbb3680b2016-03-07 18:35:42 +0000164 return false;
Adam Nemetaf761102016-01-21 18:28:36 +0000165 assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
166
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000167 bool MadeChange = false;
168
Benjamin Kramer135f7352016-06-26 12:28:59 +0000169 for (Loop *I : *LI)
170 for (auto L = df_begin(I), LE = df_end(I); L != LE; ++L)
Hal Finkel5551f252015-04-12 17:18:56 +0000171 MadeChange |= runOnLoop(*L);
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000172
173 return MadeChange;
174}
175
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000176bool LoopDataPrefetch::runOnLoop(Loop *L) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000177 bool MadeChange = false;
178
179 // Only prefetch in the inner-most loop
180 if (!L->empty())
181 return MadeChange;
182
183 SmallPtrSet<const Value *, 32> EphValues;
184 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
185
186 // Calculate the number of iterations ahead to prefetch
187 CodeMetrics Metrics;
188 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
189 I != IE; ++I) {
190
191 // If the loop already has prefetches, then assume that the user knows
Nico Weber2cf5e892016-06-10 20:06:03 +0000192 // what they are doing and don't add any more.
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000193 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
194 J != JE; ++J)
195 if (CallInst *CI = dyn_cast<CallInst>(J))
196 if (Function *F = CI->getCalledFunction())
197 if (F->getIntrinsicID() == Intrinsic::prefetch)
198 return MadeChange;
199
200 Metrics.analyzeBasicBlock(*I, *TTI, EphValues);
201 }
202 unsigned LoopSize = Metrics.NumInsts;
203 if (!LoopSize)
204 LoopSize = 1;
205
Adam Nemet1428d412016-03-29 23:45:52 +0000206 unsigned ItersAhead = getPrefetchDistance() / LoopSize;
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000207 if (!ItersAhead)
208 ItersAhead = 1;
209
Adam Nemet1428d412016-03-29 23:45:52 +0000210 if (ItersAhead > getMaxPrefetchIterationsAhead())
Adam Nemet709e3042016-03-18 00:27:43 +0000211 return MadeChange;
212
Adam Nemet3c5eabf2016-05-05 00:08:15 +0000213 Function *F = L->getHeader()->getParent();
Adam Nemet34785ec2016-03-09 05:33:21 +0000214 DEBUG(dbgs() << "Prefetching " << ItersAhead
215 << " iterations ahead (loop size: " << LoopSize << ") in "
Adam Nemet3c5eabf2016-05-05 00:08:15 +0000216 << F->getName() << ": " << *L);
Adam Nemet34785ec2016-03-09 05:33:21 +0000217
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000218 SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
219 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
220 I != IE; ++I) {
221 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
222 J != JE; ++J) {
223 Value *PtrValue;
224 Instruction *MemI;
225
226 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
227 MemI = LMemI;
228 PtrValue = LMemI->getPointerOperand();
229 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
230 if (!PrefetchWrites) continue;
231 MemI = SMemI;
232 PtrValue = SMemI->getPointerOperand();
233 } else continue;
234
235 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
236 if (PtrAddrSpace)
237 continue;
238
239 if (L->isLoopInvariant(PtrValue))
240 continue;
241
242 const SCEV *LSCEV = SE->getSCEV(PtrValue);
243 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
244 if (!LSCEVAddRec)
245 continue;
246
Adam Nemet6d8beec2016-03-18 00:27:38 +0000247 // Check if the the stride of the accesses is large enough to warrant a
248 // prefetch.
249 if (!isStrideLargeEnough(LSCEVAddRec))
250 continue;
251
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000252 // We don't want to double prefetch individual cache lines. If this load
253 // is known to be within one cache line of some other load that has
254 // already been prefetched, then don't prefetch this one as well.
255 bool DupPref = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000256 for (const auto &PrefLoad : PrefLoads) {
257 const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, PrefLoad.second);
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000258 if (const SCEVConstant *ConstPtrDiff =
259 dyn_cast<SCEVConstant>(PtrDiff)) {
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000260 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
Adam Nemetaf761102016-01-21 18:28:36 +0000261 if (PD < (int64_t) TTI->getCacheLineSize()) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000262 DupPref = true;
263 break;
264 }
265 }
266 }
267 if (DupPref)
268 continue;
269
270 const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
271 SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
272 LSCEVAddRec->getStepRecurrence(*SE)));
273 if (!isSafeToExpand(NextLSCEV, *SE))
274 continue;
275
276 PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
277
278 Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000279 SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000280 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
281
282 IRBuilder<> Builder(MemI);
283 Module *M = (*I)->getParent()->getParent();
284 Type *I32 = Type::getInt32Ty((*I)->getContext());
285 Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
David Blaikieff6409d2015-05-18 22:13:54 +0000286 Builder.CreateCall(
287 PrefetchFunc,
288 {PrefPtrValue,
289 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
290 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
Adam Nemet34785ec2016-03-09 05:33:21 +0000291 ++NumPrefetches;
292 DEBUG(dbgs() << " Access: " << *PtrValue << ", SCEV: " << *LSCEV
293 << "\n");
Adam Nemet3c5eabf2016-05-05 00:08:15 +0000294 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F,
295 MemI->getDebugLoc(), "prefetched memory access");
296
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000297
298 MadeChange = true;
299 }
300 }
301
302 return MadeChange;
303}
304