blob: 97f9ef2fa0428cb3bb75b5f417d7856421c8877a [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"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000018#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000019#include "llvm/Analysis/LoopPass.h"
20#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000021#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000022#include "llvm/Analysis/ValueTracking.h"
23#include "llvm/Target/TargetData.h"
Chris Lattner9f391882010-12-27 00:03:23 +000024#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000025#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000026#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
30// TODO: Recognize "N" size array multiplies: replace with call to blas or
31// something.
32
33namespace {
34 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000035 Loop *CurLoop;
36 const TargetData *TD;
37 ScalarEvolution *SE;
Chris Lattnere6bb6492010-12-26 19:39:38 +000038 public:
39 static char ID;
40 explicit LoopIdiomRecognize() : LoopPass(ID) {
41 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
42 }
43
44 bool runOnLoop(Loop *L, LPPassManager &LPM);
45
Chris Lattner22920b52010-12-26 20:45:45 +000046 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000047
Chris Lattnera92ff912010-12-26 23:42:51 +000048 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
49 Value *SplatValue,
50 const SCEVAddRecExpr *Ev,
51 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +000052 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
53 const SCEVAddRecExpr *StoreEv,
54 const SCEVAddRecExpr *LoadEv,
55 const SCEV *BECount);
56
Chris Lattnere6bb6492010-12-26 19:39:38 +000057 /// This transformation requires natural loop information & requires that
58 /// loop preheaders be inserted into the CFG.
59 ///
60 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<LoopInfo>();
62 AU.addPreserved<LoopInfo>();
63 AU.addRequiredID(LoopSimplifyID);
64 AU.addPreservedID(LoopSimplifyID);
65 AU.addRequiredID(LCSSAID);
66 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +000067 AU.addRequired<AliasAnalysis>();
68 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +000069 AU.addRequired<ScalarEvolution>();
70 AU.addPreserved<ScalarEvolution>();
71 AU.addPreserved<DominatorTree>();
72 }
73 };
74}
75
76char LoopIdiomRecognize::ID = 0;
77INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
78 false, false)
79INITIALIZE_PASS_DEPENDENCY(LoopInfo)
80INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
81INITIALIZE_PASS_DEPENDENCY(LCSSA)
82INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattner2e12f1a2010-12-27 18:39:08 +000083INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +000084INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
85 false, false)
86
87Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
88
Chris Lattner9f391882010-12-27 00:03:23 +000089/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
90/// and zero out all the operands of this instruction. If any of them become
91/// dead, delete them and the computation tree that feeds them.
92///
93static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
94 SmallVector<Instruction*, 32> NowDeadInsts;
95
96 NowDeadInsts.push_back(I);
97
98 // Before we touch this instruction, remove it from SE!
99 do {
100 Instruction *DeadInst = NowDeadInsts.pop_back_val();
101
102 // This instruction is dead, zap it, in stages. Start by removing it from
103 // SCEV.
104 SE.forgetValue(DeadInst);
105
106 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
107 Value *Op = DeadInst->getOperand(op);
108 DeadInst->setOperand(op, 0);
109
110 // If this operand just became dead, add it to the NowDeadInsts list.
111 if (!Op->use_empty()) continue;
112
113 if (Instruction *OpI = dyn_cast<Instruction>(Op))
114 if (isInstructionTriviallyDead(OpI))
115 NowDeadInsts.push_back(OpI);
116 }
117
118 DeadInst->eraseFromParent();
119
120 } while (!NowDeadInsts.empty());
121}
122
Chris Lattnere6bb6492010-12-26 19:39:38 +0000123bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000124 CurLoop = L;
125
Chris Lattnere6bb6492010-12-26 19:39:38 +0000126 // We only look at trivial single basic block loops.
127 // TODO: eventually support more complex loops, scanning the header.
128 if (L->getBlocks().size() != 1)
129 return false;
130
Chris Lattner22920b52010-12-26 20:45:45 +0000131 // The trip count of the loop must be analyzable.
132 SE = &getAnalysis<ScalarEvolution>();
133 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
134 return false;
135 const SCEV *BECount = SE->getBackedgeTakenCount(L);
136 if (isa<SCEVCouldNotCompute>(BECount)) return false;
137
138 // We require target data for now.
139 TD = getAnalysisIfAvailable<TargetData>();
140 if (TD == 0) return false;
141
Chris Lattnere6bb6492010-12-26 19:39:38 +0000142 BasicBlock *BB = L->getHeader();
Chris Lattner22920b52010-12-26 20:45:45 +0000143 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
Chris Lattnere6bb6492010-12-26 19:39:38 +0000144 << "] Loop %" << BB->getName() << "\n");
145
Chris Lattner22920b52010-12-26 20:45:45 +0000146 bool MadeChange = false;
147 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
148 // Look for store instructions, which may be memsets.
Chris Lattnera92ff912010-12-26 23:42:51 +0000149 StoreInst *SI = dyn_cast<StoreInst>(I++);
150 if (SI == 0 || SI->isVolatile()) continue;
151
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000152 WeakVH InstPtr(SI);
153 if (!processLoopStore(SI, BECount)) continue;
154
155 MadeChange = true;
156
157 // If processing the store invalidated our iterator, start over from the
158 // head of the loop.
159 if (InstPtr == 0)
160 I = BB->begin();
Chris Lattner22920b52010-12-26 20:45:45 +0000161 }
162
163 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000164}
165
166/// scanBlock - Look over a block to see if we can promote anything out of it.
Chris Lattner22920b52010-12-26 20:45:45 +0000167bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
168 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000169 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000170
Chris Lattner95ae6762010-12-28 18:53:48 +0000171 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000172 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000173 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000174 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000175
Chris Lattner22920b52010-12-26 20:45:45 +0000176 // See if the pointer expression is an AddRec like {base,+,1} on the current
177 // loop, which indicates a strided store. If we have something else, it's a
178 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000179 const SCEVAddRecExpr *StoreEv =
180 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
181 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000182 return false;
183
184 // Check to see if the stride matches the size of the store. If so, then we
185 // know that every byte is touched in the loop.
186 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000187 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Chris Lattner30980b62011-01-01 19:39:01 +0000188
189 // TODO: Could also handle negative stride here someday, that will require the
190 // validity check in mayLoopModRefLocation to be updated though.
Chris Lattner22920b52010-12-26 20:45:45 +0000191 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
192 return false;
193
Chris Lattner22920b52010-12-26 20:45:45 +0000194 // If the stored value is a byte-wise value (like i32 -1), then it may be
195 // turned into a memset of i8 -1, assuming that all the consequtive bytes
196 // are stored. A store of i32 0x01020304 can never be turned into a memset.
Chris Lattnera92ff912010-12-26 23:42:51 +0000197 if (Value *SplatValue = isBytewiseValue(StoredVal))
Chris Lattnere2c43922011-01-02 03:37:56 +0000198 if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
199 BECount))
200 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000201
Chris Lattnere2c43922011-01-02 03:37:56 +0000202 // If the stored value is a strided load in the same loop with the same stride
203 // this this may be transformable into a memcpy. This kicks in for stuff like
204 // for (i) A[i] = B[i];
205 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
206 const SCEVAddRecExpr *LoadEv =
207 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
208 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
209 StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
210 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
211 return true;
212 }
213 // errs() << "UNHANDLED strided store: " << *Ev << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000214
Chris Lattnere6bb6492010-12-26 19:39:38 +0000215 return false;
216}
217
Chris Lattner30980b62011-01-01 19:39:01 +0000218/// mayLoopModRefLocation - Return true if the specified loop might do a load or
219/// store to the same location that the specified store could store to, which is
220/// a loop-strided access.
Chris Lattnere2c43922011-01-02 03:37:56 +0000221static bool mayLoopModRefLocation(Value *Ptr, Loop *L, const SCEV *BECount,
222 unsigned StoreSize, AliasAnalysis &AA,
223 StoreInst *IgnoredStore) {
Chris Lattner30980b62011-01-01 19:39:01 +0000224 // Get the location that may be stored across the loop. Since the access is
225 // strided positively through memory, we say that the modified location starts
226 // at the pointer and has infinite size.
Chris Lattnera64cbf02011-01-01 19:54:22 +0000227 uint64_t AccessSize = AliasAnalysis::UnknownSize;
228
229 // If the loop iterates a fixed number of times, we can refine the access size
230 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
231 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
232 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
233
234 // TODO: For this to be really effective, we have to dive into the pointer
235 // operand in the store. Store to &A[i] of 100 will always return may alias
236 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
237 // which will then no-alias a store to &A[100].
Chris Lattnere2c43922011-01-02 03:37:56 +0000238 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
Chris Lattner30980b62011-01-01 19:39:01 +0000239
240 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
241 ++BI)
242 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chris Lattnere2c43922011-01-02 03:37:56 +0000243 if (&*I != IgnoredStore &&
244 AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
Chris Lattner30980b62011-01-01 19:39:01 +0000245 return true;
246
247 return false;
248}
249
Chris Lattnera92ff912010-12-26 23:42:51 +0000250/// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
251/// If we can transform this into a memset in the loop preheader, do so.
252bool LoopIdiomRecognize::
253processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
254 Value *SplatValue,
255 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
Chris Lattnerbafa1172011-01-01 20:12:04 +0000256 // Verify that the stored value is loop invariant. If not, we can't promote
257 // the memset.
258 if (!CurLoop->isLoopInvariant(SplatValue))
259 return false;
260
Chris Lattnera92ff912010-12-26 23:42:51 +0000261 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
262 // this into a memset in the loop preheader now if we want. However, this
263 // would be unsafe to do if there is anything else in the loop that may read
264 // or write to the aliased location. Check for an alias.
Chris Lattnere2c43922011-01-02 03:37:56 +0000265 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
266 StoreSize, getAnalysis<AliasAnalysis>(), SI))
267 return false;
Chris Lattnera92ff912010-12-26 23:42:51 +0000268
269 // Okay, everything looks good, insert the memset.
270 BasicBlock *Preheader = CurLoop->getLoopPreheader();
271
272 IRBuilder<> Builder(Preheader->getTerminator());
273
274 // The trip count of the loop and the base pointer of the addrec SCEV is
275 // guaranteed to be loop invariant, which means that it should dominate the
276 // header. Just insert code for it in the preheader.
277 SCEVExpander Expander(*SE);
278
279 unsigned AddrSpace = SI->getPointerAddressSpace();
280 Value *BasePtr =
281 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
282 Preheader->getTerminator());
283
284 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
285 // pointer size if it isn't already.
286 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
287 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
288 if (BESize < TD->getPointerSizeInBits())
289 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
290 else if (BESize > TD->getPointerSizeInBits())
291 BECount = SE->getTruncateExpr(BECount, IntPtr);
292
293 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
294 true, true /*nooverflow*/);
295 if (StoreSize != 1)
296 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
297 true, true /*nooverflow*/);
298
299 Value *NumBytes =
300 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
301
302 Value *NewCall =
303 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
304
305 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
306 << " from store to: " << *Ev << " at: " << *SI << "\n");
Duncan Sands7922d342010-12-28 09:41:15 +0000307 (void)NewCall;
Chris Lattnera92ff912010-12-26 23:42:51 +0000308
Chris Lattner9f391882010-12-27 00:03:23 +0000309 // Okay, the memset has been formed. Zap the original store and anything that
310 // feeds into it.
311 DeleteDeadInstruction(SI, *SE);
Chris Lattnera92ff912010-12-26 23:42:51 +0000312 return true;
313}
314
Chris Lattnere2c43922011-01-02 03:37:56 +0000315/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
316/// same-strided load.
317bool LoopIdiomRecognize::
318processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
319 const SCEVAddRecExpr *StoreEv,
320 const SCEVAddRecExpr *LoadEv,
321 const SCEV *BECount) {
322 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
323
324 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
325 // this into a memcmp in the loop preheader now if we want. However, this
326 // would be unsafe to do if there is anything else in the loop that may read
327 // or write to the aliased location (including the load feeding the stores).
328 // Check for an alias.
329 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
330 StoreSize, getAnalysis<AliasAnalysis>(), SI))
331 return false;
332
333 // Okay, everything looks good, insert the memcpy.
334 BasicBlock *Preheader = CurLoop->getLoopPreheader();
335
336 IRBuilder<> Builder(Preheader->getTerminator());
337
338 // The trip count of the loop and the base pointer of the addrec SCEV is
339 // guaranteed to be loop invariant, which means that it should dominate the
340 // header. Just insert code for it in the preheader.
341 SCEVExpander Expander(*SE);
342
343 Value *LoadBasePtr =
344 Expander.expandCodeFor(LoadEv->getStart(),
345 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
346 Preheader->getTerminator());
347 Value *StoreBasePtr =
348 Expander.expandCodeFor(StoreEv->getStart(),
349 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
350 Preheader->getTerminator());
351
352 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
353 // pointer size if it isn't already.
354 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
355 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
356 if (BESize < TD->getPointerSizeInBits())
357 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
358 else if (BESize > TD->getPointerSizeInBits())
359 BECount = SE->getTruncateExpr(BECount, IntPtr);
360
361 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
362 true, true /*nooverflow*/);
363 if (StoreSize != 1)
364 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
365 true, true /*nooverflow*/);
366
367 Value *NumBytes =
368 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
369
370 Value *NewCall =
371 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
372 std::min(SI->getAlignment(), LI->getAlignment()));
373
374 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
375 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
376 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
377 (void)NewCall;
378
379 // Okay, the memset has been formed. Zap the original store and anything that
380 // feeds into it.
381 DeleteDeadInstruction(SI, *SE);
382 return true;
383}