blob: 14553ab9d57d235576ffbfcbff006faf1564100c [file] [log] [blame]
Hal Finkele5aaf3f2015-02-20 05:08:21 +00001//===-------- PPCLoopDataPrefetch.cpp - Loop Data Prefetching Pass --------===//
2//
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
14#define DEBUG_TYPE "ppc-loop-data-prefetch"
15#include "PPC.h"
16#include "llvm/Transforms/Scalar.h"
Hal Finkela9fceb82015-04-10 15:05:02 +000017#include "llvm/ADT/DepthFirstIterator.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000018#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/AssumptionCache.h"
20#include "llvm/Analysis/CodeMetrics.h"
21#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000025#include "llvm/Analysis/ScalarEvolutionExpander.h"
26#include "llvm/Analysis/ScalarEvolutionExpressions.h"
27#include "llvm/Analysis/TargetTransformInfo.h"
28#include "llvm/Analysis/ValueTracking.h"
29#include "llvm/IR/CFG.h"
30#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>
44PrefetchWrites("ppc-loop-prefetch-writes", cl::Hidden, cl::init(false),
45 cl::desc("Prefetch write addresses"));
46
Hal Finkele5aaf3f2015-02-20 05:08:21 +000047namespace llvm {
48 void initializePPCLoopDataPrefetchPass(PassRegistry&);
49}
50
51namespace {
52
53 class PPCLoopDataPrefetch : public FunctionPass {
54 public:
55 static char ID; // Pass ID, replacement for typeid
56 PPCLoopDataPrefetch() : FunctionPass(ID) {
57 initializePPCLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
58 }
59
60 void getAnalysisUsage(AnalysisUsage &AU) const override {
61 AU.addRequired<AssumptionCacheTracker>();
62 AU.addPreserved<DominatorTreeWrapperPass>();
63 AU.addRequired<LoopInfoWrapperPass>();
64 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000065 AU.addRequired<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000066 // FIXME: For some reason, preserving SE here breaks LSR (even if
67 // this pass changes nothing).
Chandler Carruth2f1fd162015-08-17 02:08:17 +000068 // AU.addPreserved<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000069 AU.addRequired<TargetTransformInfoWrapperPass>();
70 }
71
72 bool runOnFunction(Function &F) override;
73 bool runOnLoop(Loop *L);
74
75 private:
76 AssumptionCache *AC;
77 LoopInfo *LI;
78 ScalarEvolution *SE;
79 const TargetTransformInfo *TTI;
80 const DataLayout *DL;
81 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000082}
Hal Finkele5aaf3f2015-02-20 05:08:21 +000083
84char PPCLoopDataPrefetch::ID = 0;
85INITIALIZE_PASS_BEGIN(PPCLoopDataPrefetch, "ppc-loop-data-prefetch",
86 "PPC Loop Data Prefetch", false, false)
87INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
88INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
89INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000090INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000091INITIALIZE_PASS_END(PPCLoopDataPrefetch, "ppc-loop-data-prefetch",
92 "PPC Loop Data Prefetch", false, false)
93
94FunctionPass *llvm::createPPCLoopDataPrefetchPass() { return new PPCLoopDataPrefetch(); }
95
96bool PPCLoopDataPrefetch::runOnFunction(Function &F) {
97 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000098 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Mehdi Amini46a43552015-03-04 18:43:29 +000099 DL = &F.getParent()->getDataLayout();
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000100 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
101 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
102
Adam Nemetaf761102016-01-21 18:28:36 +0000103 assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
Adam Nemetdadfbb52016-01-27 22:21:25 +0000104 assert(TTI->getPrefetchDistance() &&
105 "Prefetch distance is not set for target");
Adam Nemetaf761102016-01-21 18:28:36 +0000106
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000107 bool MadeChange = false;
108
Hal Finkel5551f252015-04-12 17:18:56 +0000109 for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
110 for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
111 MadeChange |= runOnLoop(*L);
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000112
113 return MadeChange;
114}
115
116bool PPCLoopDataPrefetch::runOnLoop(Loop *L) {
117 bool MadeChange = false;
118
119 // Only prefetch in the inner-most loop
120 if (!L->empty())
121 return MadeChange;
122
123 SmallPtrSet<const Value *, 32> EphValues;
124 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
125
126 // Calculate the number of iterations ahead to prefetch
127 CodeMetrics Metrics;
128 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
129 I != IE; ++I) {
130
131 // If the loop already has prefetches, then assume that the user knows
132 // what he or she is doing and don't add any more.
133 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
134 J != JE; ++J)
135 if (CallInst *CI = dyn_cast<CallInst>(J))
136 if (Function *F = CI->getCalledFunction())
137 if (F->getIntrinsicID() == Intrinsic::prefetch)
138 return MadeChange;
139
140 Metrics.analyzeBasicBlock(*I, *TTI, EphValues);
141 }
142 unsigned LoopSize = Metrics.NumInsts;
143 if (!LoopSize)
144 LoopSize = 1;
145
Adam Nemetdadfbb52016-01-27 22:21:25 +0000146 unsigned ItersAhead = TTI->getPrefetchDistance() / LoopSize;
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000147 if (!ItersAhead)
148 ItersAhead = 1;
149
150 SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
151 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
152 I != IE; ++I) {
153 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
154 J != JE; ++J) {
155 Value *PtrValue;
156 Instruction *MemI;
157
158 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
159 MemI = LMemI;
160 PtrValue = LMemI->getPointerOperand();
161 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
162 if (!PrefetchWrites) continue;
163 MemI = SMemI;
164 PtrValue = SMemI->getPointerOperand();
165 } else continue;
166
167 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
168 if (PtrAddrSpace)
169 continue;
170
171 if (L->isLoopInvariant(PtrValue))
172 continue;
173
174 const SCEV *LSCEV = SE->getSCEV(PtrValue);
175 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
176 if (!LSCEVAddRec)
177 continue;
178
179 // We don't want to double prefetch individual cache lines. If this load
180 // is known to be within one cache line of some other load that has
181 // already been prefetched, then don't prefetch this one as well.
182 bool DupPref = false;
183 for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
184 16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
185 K != KE; ++K) {
186 const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
187 if (const SCEVConstant *ConstPtrDiff =
188 dyn_cast<SCEVConstant>(PtrDiff)) {
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000189 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
Adam Nemetaf761102016-01-21 18:28:36 +0000190 if (PD < (int64_t) TTI->getCacheLineSize()) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000191 DupPref = true;
192 break;
193 }
194 }
195 }
196 if (DupPref)
197 continue;
198
199 const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
200 SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
201 LSCEVAddRec->getStepRecurrence(*SE)));
202 if (!isSafeToExpand(NextLSCEV, *SE))
203 continue;
204
205 PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
206
207 Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000208 SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000209 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
210
211 IRBuilder<> Builder(MemI);
212 Module *M = (*I)->getParent()->getParent();
213 Type *I32 = Type::getInt32Ty((*I)->getContext());
214 Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
David Blaikieff6409d2015-05-18 22:13:54 +0000215 Builder.CreateCall(
216 PrefetchFunc,
217 {PrefPtrValue,
218 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
219 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000220
221 MadeChange = true;
222 }
223 }
224
225 return MadeChange;
226}
227