xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp (revision bb3680bd8590b2dd817bbbb482badd6ebcbe6224)
1 //===-------- LoopDataPrefetch.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 "loop-data-prefetch"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #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"
23 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
24 #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"
38 using 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).
42 static cl::opt<bool>
43 PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false),
44                cl::desc("Prefetch write addresses"));
45 
46 namespace llvm {
47   void initializeLoopDataPrefetchPass(PassRegistry&);
48 }
49 
50 namespace {
51 
52   class LoopDataPrefetch : public FunctionPass {
53   public:
54     static char ID; // Pass ID, replacement for typeid
55     LoopDataPrefetch() : FunctionPass(ID) {
56       initializeLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
57     }
58 
59     void getAnalysisUsage(AnalysisUsage &AU) const override {
60       AU.addRequired<AssumptionCacheTracker>();
61       AU.addPreserved<DominatorTreeWrapperPass>();
62       AU.addRequired<LoopInfoWrapperPass>();
63       AU.addPreserved<LoopInfoWrapperPass>();
64       AU.addRequired<ScalarEvolutionWrapperPass>();
65       // FIXME: For some reason, preserving SE here breaks LSR (even if
66       // this pass changes nothing).
67       // AU.addPreserved<ScalarEvolutionWrapperPass>();
68       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   };
81 }
82 
83 char LoopDataPrefetch::ID = 0;
84 INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch",
85                       "Loop Data Prefetch", false, false)
86 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
87 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
88 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
89 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
90 INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch",
91                     "Loop Data Prefetch", false, false)
92 
93 FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); }
94 
95 bool LoopDataPrefetch::runOnFunction(Function &F) {
96   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
97   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
98   DL = &F.getParent()->getDataLayout();
99   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
100   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
101 
102   // 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;
107   assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
108 
109   bool MadeChange = false;
110 
111   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);
114 
115   return MadeChange;
116 }
117 
118 bool LoopDataPrefetch::runOnLoop(Loop *L) {
119   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 
148   unsigned ItersAhead = TTI->getPrefetchDistance() / LoopSize;
149   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)) {
191           int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
192           if (PD < (int64_t) TTI->getCacheLineSize()) {
193             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);
210       SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
211       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);
217       Builder.CreateCall(
218           PrefetchFunc,
219           {PrefPtrValue,
220            ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
221            ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
222 
223       MadeChange = true;
224     }
225   }
226 
227   return MadeChange;
228 }
229 
230