blob: a5e2b2dba175180f8d2026f101cadc2db403f16c [file] [log] [blame]
Chris Lattnere6bb6492010-12-26 19:39:38 +00001//===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
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 pass implements an idiom recognizer that transforms simple loops into a
11// non-loop form. In cases that this kicks in, it can be a significant
12// performance win.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "loop-idiom"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000020#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000021#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/Target/TargetData.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000023#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000024#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000025#include "llvm/Support/raw_ostream.h"
26using namespace llvm;
27
28// TODO: Recognize "N" size array multiplies: replace with call to blas or
29// something.
30
31namespace {
32 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000033 Loop *CurLoop;
34 const TargetData *TD;
35 ScalarEvolution *SE;
Chris Lattnere6bb6492010-12-26 19:39:38 +000036 public:
37 static char ID;
38 explicit LoopIdiomRecognize() : LoopPass(ID) {
39 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
40 }
41
42 bool runOnLoop(Loop *L, LPPassManager &LPM);
43
Chris Lattner22920b52010-12-26 20:45:45 +000044 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000045
Chris Lattnera92ff912010-12-26 23:42:51 +000046 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
47 Value *SplatValue,
48 const SCEVAddRecExpr *Ev,
49 const SCEV *BECount);
50
Chris Lattnere6bb6492010-12-26 19:39:38 +000051 /// This transformation requires natural loop information & requires that
52 /// loop preheaders be inserted into the CFG.
53 ///
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.addRequired<LoopInfo>();
56 AU.addPreserved<LoopInfo>();
57 AU.addRequiredID(LoopSimplifyID);
58 AU.addPreservedID(LoopSimplifyID);
59 AU.addRequiredID(LCSSAID);
60 AU.addPreservedID(LCSSAID);
61 AU.addRequired<ScalarEvolution>();
62 AU.addPreserved<ScalarEvolution>();
63 AU.addPreserved<DominatorTree>();
64 }
65 };
66}
67
68char LoopIdiomRecognize::ID = 0;
69INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
70 false, false)
71INITIALIZE_PASS_DEPENDENCY(LoopInfo)
72INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
73INITIALIZE_PASS_DEPENDENCY(LCSSA)
74INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
75INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
76 false, false)
77
78Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
79
80bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +000081 CurLoop = L;
82
Chris Lattnere6bb6492010-12-26 19:39:38 +000083 // We only look at trivial single basic block loops.
84 // TODO: eventually support more complex loops, scanning the header.
85 if (L->getBlocks().size() != 1)
86 return false;
87
Chris Lattner22920b52010-12-26 20:45:45 +000088 // The trip count of the loop must be analyzable.
89 SE = &getAnalysis<ScalarEvolution>();
90 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
91 return false;
92 const SCEV *BECount = SE->getBackedgeTakenCount(L);
93 if (isa<SCEVCouldNotCompute>(BECount)) return false;
94
95 // We require target data for now.
96 TD = getAnalysisIfAvailable<TargetData>();
97 if (TD == 0) return false;
98
Chris Lattnere6bb6492010-12-26 19:39:38 +000099 BasicBlock *BB = L->getHeader();
Chris Lattner22920b52010-12-26 20:45:45 +0000100 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
Chris Lattnere6bb6492010-12-26 19:39:38 +0000101 << "] Loop %" << BB->getName() << "\n");
102
Chris Lattner22920b52010-12-26 20:45:45 +0000103 bool MadeChange = false;
104 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
105 // Look for store instructions, which may be memsets.
Chris Lattnera92ff912010-12-26 23:42:51 +0000106 StoreInst *SI = dyn_cast<StoreInst>(I++);
107 if (SI == 0 || SI->isVolatile()) continue;
108
109
110 MadeChange |= processLoopStore(SI, BECount);
Chris Lattner22920b52010-12-26 20:45:45 +0000111 }
112
113 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000114}
115
116/// scanBlock - Look over a block to see if we can promote anything out of it.
Chris Lattner22920b52010-12-26 20:45:45 +0000117bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
118 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000119 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000120
Chris Lattner22920b52010-12-26 20:45:45 +0000121 // Check to see if the store updates all bits in memory. We don't want to
122 // process things like a store of i3. We also require that the store be a
123 // multiple of a byte.
124 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
125 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0 ||
126 SizeInBits != TD->getTypeStoreSizeInBits(StoredVal->getType()))
127 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000128
Chris Lattner22920b52010-12-26 20:45:45 +0000129 // See if the pointer expression is an AddRec like {base,+,1} on the current
130 // loop, which indicates a strided store. If we have something else, it's a
131 // random store we can't handle.
Chris Lattnera92ff912010-12-26 23:42:51 +0000132 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chris Lattner22920b52010-12-26 20:45:45 +0000133 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
134 return false;
135
136 // Check to see if the stride matches the size of the store. If so, then we
137 // know that every byte is touched in the loop.
138 unsigned StoreSize = (unsigned)SizeInBits >> 3;
139 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
140 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
141 return false;
142
Chris Lattner22920b52010-12-26 20:45:45 +0000143 // If the stored value is a byte-wise value (like i32 -1), then it may be
144 // turned into a memset of i8 -1, assuming that all the consequtive bytes
145 // are stored. A store of i32 0x01020304 can never be turned into a memset.
Chris Lattnera92ff912010-12-26 23:42:51 +0000146 if (Value *SplatValue = isBytewiseValue(StoredVal))
147 return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
148
149 // Handle the memcpy case here.
150 errs() << "Found strided store: " << *Ev << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000151
152
Chris Lattnere6bb6492010-12-26 19:39:38 +0000153 return false;
154}
155
Chris Lattnera92ff912010-12-26 23:42:51 +0000156/// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
157/// If we can transform this into a memset in the loop preheader, do so.
158bool LoopIdiomRecognize::
159processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
160 Value *SplatValue,
161 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
162 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
163 // this into a memset in the loop preheader now if we want. However, this
164 // would be unsafe to do if there is anything else in the loop that may read
165 // or write to the aliased location. Check for an alias.
166
167 // FIXME: TODO safety check.
168
169 // Okay, everything looks good, insert the memset.
170 BasicBlock *Preheader = CurLoop->getLoopPreheader();
171
172 IRBuilder<> Builder(Preheader->getTerminator());
173
174 // The trip count of the loop and the base pointer of the addrec SCEV is
175 // guaranteed to be loop invariant, which means that it should dominate the
176 // header. Just insert code for it in the preheader.
177 SCEVExpander Expander(*SE);
178
179 unsigned AddrSpace = SI->getPointerAddressSpace();
180 Value *BasePtr =
181 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
182 Preheader->getTerminator());
183
184 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
185 // pointer size if it isn't already.
186 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
187 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
188 if (BESize < TD->getPointerSizeInBits())
189 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
190 else if (BESize > TD->getPointerSizeInBits())
191 BECount = SE->getTruncateExpr(BECount, IntPtr);
192
193 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
194 true, true /*nooverflow*/);
195 if (StoreSize != 1)
196 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
197 true, true /*nooverflow*/);
198
199 Value *NumBytes =
200 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
201
202 Value *NewCall =
203 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
204
205 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
206 << " from store to: " << *Ev << " at: " << *SI << "\n");
207
208 // Okay, the memset has been formed. Zap the original store.
209 // FIXME: We want to recursively delete dead instructions, but we have to
210 // update SCEV.
211 SI->eraseFromParent();
212 return true;
213}
214