blob: 5d0a590650982b112fd8683ac64abc08b764ec77 [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
Hal Finkele5aaf3f2015-02-20 05:08:21 +000046namespace llvm {
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000047 void initializeLoopDataPrefetchPass(PassRegistry&);
Hal Finkele5aaf3f2015-02-20 05:08:21 +000048}
49
50namespace {
51
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000052 class LoopDataPrefetch : public FunctionPass {
Hal Finkele5aaf3f2015-02-20 05:08:21 +000053 public:
54 static char ID; // Pass ID, replacement for typeid
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000055 LoopDataPrefetch() : FunctionPass(ID) {
56 initializeLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
Hal Finkele5aaf3f2015-02-20 05:08:21 +000057 }
58
59 void getAnalysisUsage(AnalysisUsage &AU) const override {
60 AU.addRequired<AssumptionCacheTracker>();
61 AU.addPreserved<DominatorTreeWrapperPass>();
62 AU.addRequired<LoopInfoWrapperPass>();
63 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000064 AU.addRequired<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000065 // FIXME: For some reason, preserving SE here breaks LSR (even if
66 // this pass changes nothing).
Chandler Carruth2f1fd162015-08-17 02:08:17 +000067 // AU.addPreserved<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000068 AU.addRequired<TargetTransformInfoWrapperPass>();
69 }
70
71 bool runOnFunction(Function &F) override;
72 bool runOnLoop(Loop *L);
73
74 private:
75 AssumptionCache *AC;
76 LoopInfo *LI;
77 ScalarEvolution *SE;
78 const TargetTransformInfo *TTI;
79 const DataLayout *DL;
80 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000081}
Hal Finkele5aaf3f2015-02-20 05:08:21 +000082
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000083char LoopDataPrefetch::ID = 0;
84INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch",
85 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000086INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
87INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
88INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000089INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000090INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch",
91 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000092
Adam Nemet9d9cb272016-02-18 21:38:19 +000093FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); }
Hal Finkele5aaf3f2015-02-20 05:08:21 +000094
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000095bool LoopDataPrefetch::runOnFunction(Function &F) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +000096 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000097 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Mehdi Amini46a43552015-03-04 18:43:29 +000098 DL = &F.getParent()->getDataLayout();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000099 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
100 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
101
Adam Nemetbb3680b2016-03-07 18:35:42 +0000102 // If PrefetchDistance is not set, don't run the pass. This gives an
103 // opportunity for targets to run this pass for selected subtargets only
104 // (whose TTI sets PrefetchDistance).
105 if (TTI->getPrefetchDistance() == 0)
106 return false;
Adam Nemetaf761102016-01-21 18:28:36 +0000107 assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
108
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000109 bool MadeChange = false;
110
Hal Finkel5551f252015-04-12 17:18:56 +0000111 for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
112 for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
113 MadeChange |= runOnLoop(*L);
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000114
115 return MadeChange;
116}
117
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000118bool LoopDataPrefetch::runOnLoop(Loop *L) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000119 bool MadeChange = false;
120
121 // Only prefetch in the inner-most loop
122 if (!L->empty())
123 return MadeChange;
124
125 SmallPtrSet<const Value *, 32> EphValues;
126 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
127
128 // Calculate the number of iterations ahead to prefetch
129 CodeMetrics Metrics;
130 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
131 I != IE; ++I) {
132
133 // If the loop already has prefetches, then assume that the user knows
134 // what he or she is doing and don't add any more.
135 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
136 J != JE; ++J)
137 if (CallInst *CI = dyn_cast<CallInst>(J))
138 if (Function *F = CI->getCalledFunction())
139 if (F->getIntrinsicID() == Intrinsic::prefetch)
140 return MadeChange;
141
142 Metrics.analyzeBasicBlock(*I, *TTI, EphValues);
143 }
144 unsigned LoopSize = Metrics.NumInsts;
145 if (!LoopSize)
146 LoopSize = 1;
147
Adam Nemetdadfbb52016-01-27 22:21:25 +0000148 unsigned ItersAhead = TTI->getPrefetchDistance() / LoopSize;
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000149 if (!ItersAhead)
150 ItersAhead = 1;
151
152 SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
153 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
154 I != IE; ++I) {
155 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
156 J != JE; ++J) {
157 Value *PtrValue;
158 Instruction *MemI;
159
160 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
161 MemI = LMemI;
162 PtrValue = LMemI->getPointerOperand();
163 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
164 if (!PrefetchWrites) continue;
165 MemI = SMemI;
166 PtrValue = SMemI->getPointerOperand();
167 } else continue;
168
169 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
170 if (PtrAddrSpace)
171 continue;
172
173 if (L->isLoopInvariant(PtrValue))
174 continue;
175
176 const SCEV *LSCEV = SE->getSCEV(PtrValue);
177 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
178 if (!LSCEVAddRec)
179 continue;
180
181 // We don't want to double prefetch individual cache lines. If this load
182 // is known to be within one cache line of some other load that has
183 // already been prefetched, then don't prefetch this one as well.
184 bool DupPref = false;
185 for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
186 16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
187 K != KE; ++K) {
188 const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
189 if (const SCEVConstant *ConstPtrDiff =
190 dyn_cast<SCEVConstant>(PtrDiff)) {
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000191 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
Adam Nemetaf761102016-01-21 18:28:36 +0000192 if (PD < (int64_t) TTI->getCacheLineSize()) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000193 DupPref = true;
194 break;
195 }
196 }
197 }
198 if (DupPref)
199 continue;
200
201 const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
202 SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
203 LSCEVAddRec->getStepRecurrence(*SE)));
204 if (!isSafeToExpand(NextLSCEV, *SE))
205 continue;
206
207 PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
208
209 Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000210 SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000211 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
212
213 IRBuilder<> Builder(MemI);
214 Module *M = (*I)->getParent()->getParent();
215 Type *I32 = Type::getInt32Ty((*I)->getContext());
216 Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
David Blaikieff6409d2015-05-18 22:13:54 +0000217 Builder.CreateCall(
218 PrefetchFunc,
219 {PrefPtrValue,
220 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
221 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000222
223 MadeChange = true;
224 }
225 }
226
227 return MadeChange;
228}
229