blob: 82af46e393c76e80ea9ffde64b297e1c60717581 [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"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Module.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Transforms/Utils/BasicBlockUtils.h"
36#include "llvm/Transforms/Utils/Local.h"
37#include "llvm/Transforms/Utils/ValueMapper.h"
38using namespace llvm;
39
40// By default, we limit this to creating 16 PHIs (which is a little over half
41// of the allocatable register set).
42static cl::opt<bool>
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000043PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false),
Hal Finkele5aaf3f2015-02-20 05:08:21 +000044 cl::desc("Prefetch write addresses"));
45
Adam Nemet34785ec2016-03-09 05:33:21 +000046STATISTIC(NumPrefetches, "Number of prefetches inserted");
47
Hal Finkele5aaf3f2015-02-20 05:08:21 +000048namespace llvm {
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000049 void initializeLoopDataPrefetchPass(PassRegistry&);
Hal Finkele5aaf3f2015-02-20 05:08:21 +000050}
51
52namespace {
53
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000054 class LoopDataPrefetch : public FunctionPass {
Hal Finkele5aaf3f2015-02-20 05:08:21 +000055 public:
56 static char ID; // Pass ID, replacement for typeid
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000057 LoopDataPrefetch() : FunctionPass(ID) {
58 initializeLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
Hal Finkele5aaf3f2015-02-20 05:08:21 +000059 }
60
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AU.addRequired<AssumptionCacheTracker>();
63 AU.addPreserved<DominatorTreeWrapperPass>();
64 AU.addRequired<LoopInfoWrapperPass>();
65 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000066 AU.addRequired<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000067 // FIXME: For some reason, preserving SE here breaks LSR (even if
68 // this pass changes nothing).
Chandler Carruth2f1fd162015-08-17 02:08:17 +000069 // AU.addPreserved<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000070 AU.addRequired<TargetTransformInfoWrapperPass>();
71 }
72
73 bool runOnFunction(Function &F) override;
Adam Nemet85fba392016-03-29 22:40:02 +000074
75 private:
Hal Finkele5aaf3f2015-02-20 05:08:21 +000076 bool runOnLoop(Loop *L);
77
Adam Nemet6d8beec2016-03-18 00:27:38 +000078 /// \brief Check if the the stride of the accesses is large enough to
79 /// warrant a prefetch.
80 bool isStrideLargeEnough(const SCEVAddRecExpr *AR);
81
Hal Finkele5aaf3f2015-02-20 05:08:21 +000082 AssumptionCache *AC;
83 LoopInfo *LI;
84 ScalarEvolution *SE;
85 const TargetTransformInfo *TTI;
86 const DataLayout *DL;
87 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000088}
Hal Finkele5aaf3f2015-02-20 05:08:21 +000089
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000090char LoopDataPrefetch::ID = 0;
91INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch",
92 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000093INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
94INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
95INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000096INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000097INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch",
98 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000099
Adam Nemet9d9cb272016-02-18 21:38:19 +0000100FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); }
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000101
Adam Nemet6d8beec2016-03-18 00:27:38 +0000102bool LoopDataPrefetch::isStrideLargeEnough(const SCEVAddRecExpr *AR) {
103 unsigned TargetMinStride = TTI->getMinPrefetchStride();
104 // No need to check if any stride goes.
105 if (TargetMinStride <= 1)
106 return true;
107
108 const auto *ConstStride = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
109 // If MinStride is set, don't prefetch unless we can ensure that stride is
110 // larger.
111 if (!ConstStride)
112 return false;
113
114 unsigned AbsStride = std::abs(ConstStride->getAPInt().getSExtValue());
115 return TargetMinStride <= AbsStride;
116}
117
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000118bool LoopDataPrefetch::runOnFunction(Function &F) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000119 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000120 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Mehdi Amini46a43552015-03-04 18:43:29 +0000121 DL = &F.getParent()->getDataLayout();
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000122 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
123 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
124
Adam Nemetbb3680b2016-03-07 18:35:42 +0000125 // If PrefetchDistance is not set, don't run the pass. This gives an
126 // opportunity for targets to run this pass for selected subtargets only
127 // (whose TTI sets PrefetchDistance).
128 if (TTI->getPrefetchDistance() == 0)
129 return false;
Adam Nemetaf761102016-01-21 18:28:36 +0000130 assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
131
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000132 bool MadeChange = false;
133
Hal Finkel5551f252015-04-12 17:18:56 +0000134 for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
135 for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
136 MadeChange |= runOnLoop(*L);
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000137
138 return MadeChange;
139}
140
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000141bool LoopDataPrefetch::runOnLoop(Loop *L) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000142 bool MadeChange = false;
143
144 // Only prefetch in the inner-most loop
145 if (!L->empty())
146 return MadeChange;
147
148 SmallPtrSet<const Value *, 32> EphValues;
149 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
150
151 // Calculate the number of iterations ahead to prefetch
152 CodeMetrics Metrics;
153 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
154 I != IE; ++I) {
155
156 // If the loop already has prefetches, then assume that the user knows
157 // what he or she is doing and don't add any more.
158 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
159 J != JE; ++J)
160 if (CallInst *CI = dyn_cast<CallInst>(J))
161 if (Function *F = CI->getCalledFunction())
162 if (F->getIntrinsicID() == Intrinsic::prefetch)
163 return MadeChange;
164
165 Metrics.analyzeBasicBlock(*I, *TTI, EphValues);
166 }
167 unsigned LoopSize = Metrics.NumInsts;
168 if (!LoopSize)
169 LoopSize = 1;
170
Adam Nemetdadfbb52016-01-27 22:21:25 +0000171 unsigned ItersAhead = TTI->getPrefetchDistance() / LoopSize;
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000172 if (!ItersAhead)
173 ItersAhead = 1;
174
Adam Nemet709e3042016-03-18 00:27:43 +0000175 if (ItersAhead > TTI->getMaxPrefetchIterationsAhead())
176 return MadeChange;
177
Adam Nemet34785ec2016-03-09 05:33:21 +0000178 DEBUG(dbgs() << "Prefetching " << ItersAhead
179 << " iterations ahead (loop size: " << LoopSize << ") in "
180 << L->getHeader()->getParent()->getName() << ": " << *L);
181
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000182 SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
183 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
184 I != IE; ++I) {
185 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
186 J != JE; ++J) {
187 Value *PtrValue;
188 Instruction *MemI;
189
190 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
191 MemI = LMemI;
192 PtrValue = LMemI->getPointerOperand();
193 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
194 if (!PrefetchWrites) continue;
195 MemI = SMemI;
196 PtrValue = SMemI->getPointerOperand();
197 } else continue;
198
199 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
200 if (PtrAddrSpace)
201 continue;
202
203 if (L->isLoopInvariant(PtrValue))
204 continue;
205
206 const SCEV *LSCEV = SE->getSCEV(PtrValue);
207 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
208 if (!LSCEVAddRec)
209 continue;
210
Adam Nemet6d8beec2016-03-18 00:27:38 +0000211 // Check if the the stride of the accesses is large enough to warrant a
212 // prefetch.
213 if (!isStrideLargeEnough(LSCEVAddRec))
214 continue;
215
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000216 // We don't want to double prefetch individual cache lines. If this load
217 // is known to be within one cache line of some other load that has
218 // already been prefetched, then don't prefetch this one as well.
219 bool DupPref = false;
220 for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
221 16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
222 K != KE; ++K) {
223 const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
224 if (const SCEVConstant *ConstPtrDiff =
225 dyn_cast<SCEVConstant>(PtrDiff)) {
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000226 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
Adam Nemetaf761102016-01-21 18:28:36 +0000227 if (PD < (int64_t) TTI->getCacheLineSize()) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000228 DupPref = true;
229 break;
230 }
231 }
232 }
233 if (DupPref)
234 continue;
235
236 const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
237 SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
238 LSCEVAddRec->getStepRecurrence(*SE)));
239 if (!isSafeToExpand(NextLSCEV, *SE))
240 continue;
241
242 PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
243
244 Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000245 SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000246 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
247
248 IRBuilder<> Builder(MemI);
249 Module *M = (*I)->getParent()->getParent();
250 Type *I32 = Type::getInt32Ty((*I)->getContext());
251 Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
David Blaikieff6409d2015-05-18 22:13:54 +0000252 Builder.CreateCall(
253 PrefetchFunc,
254 {PrefPtrValue,
255 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
256 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
Adam Nemet34785ec2016-03-09 05:33:21 +0000257 ++NumPrefetches;
258 DEBUG(dbgs() << " Access: " << *PtrValue << ", SCEV: " << *LSCEV
259 << "\n");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000260
261 MadeChange = true;
262 }
263 }
264
265 return MadeChange;
266}
267