blob: 72fee7012e1d2af514f5f6d5314161bf73fc544f [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//===----------------------------------------------------------------------===//
Chris Lattnerbdce5722011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
19// memcmp, memmove, strlen, etc.
20// Future floating point idioms to recognize in -ffast-math mode:
21// fpowi
22// Future integer operation idioms to recognize:
23// ctpop, ctlz, cttz
24//
25// Beware that isel's default lowering for ctpop is highly inefficient for
26// i64 and larger types when i64 is legal and the value has few bits set. It
27// would be good to enhance isel to emit a loop for ctpop in this case.
28//
29// We should enhance the memset/memcpy recognition to handle multiple stores in
30// the loop. This would handle things like:
31// void foo(_Complex float *P)
32// for (i) { __real__(*P) = 0; __imag__(*P) = 0; }
33// this is also "Example 2" from http://blog.regehr.org/archives/320
34//
35//===----------------------------------------------------------------------===//
Chris Lattnere6bb6492010-12-26 19:39:38 +000036
37#define DEBUG_TYPE "loop-idiom"
38#include "llvm/Transforms/Scalar.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000039#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000040#include "llvm/Analysis/LoopPass.h"
41#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000042#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000043#include "llvm/Analysis/ValueTracking.h"
44#include "llvm/Target/TargetData.h"
Chris Lattner9f391882010-12-27 00:03:23 +000045#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000046#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000047#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000048#include "llvm/Support/raw_ostream.h"
Chris Lattner4ce31fb2011-01-02 07:36:44 +000049#include "llvm/ADT/Statistic.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000050using namespace llvm;
51
52// TODO: Recognize "N" size array multiplies: replace with call to blas or
53// something.
Chris Lattner4ce31fb2011-01-02 07:36:44 +000054STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
55STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000056
57namespace {
58 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000059 Loop *CurLoop;
60 const TargetData *TD;
61 ScalarEvolution *SE;
Chris Lattnere6bb6492010-12-26 19:39:38 +000062 public:
63 static char ID;
64 explicit LoopIdiomRecognize() : LoopPass(ID) {
65 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
66 }
67
68 bool runOnLoop(Loop *L, LPPassManager &LPM);
69
Chris Lattner22920b52010-12-26 20:45:45 +000070 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000071
Chris Lattnera92ff912010-12-26 23:42:51 +000072 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
73 Value *SplatValue,
74 const SCEVAddRecExpr *Ev,
75 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +000076 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
77 const SCEVAddRecExpr *StoreEv,
78 const SCEVAddRecExpr *LoadEv,
79 const SCEV *BECount);
80
Chris Lattnere6bb6492010-12-26 19:39:38 +000081 /// This transformation requires natural loop information & requires that
82 /// loop preheaders be inserted into the CFG.
83 ///
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo>();
86 AU.addPreserved<LoopInfo>();
87 AU.addRequiredID(LoopSimplifyID);
88 AU.addPreservedID(LoopSimplifyID);
89 AU.addRequiredID(LCSSAID);
90 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +000091 AU.addRequired<AliasAnalysis>();
92 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +000093 AU.addRequired<ScalarEvolution>();
94 AU.addPreserved<ScalarEvolution>();
95 AU.addPreserved<DominatorTree>();
96 }
97 };
98}
99
100char LoopIdiomRecognize::ID = 0;
101INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
102 false, false)
103INITIALIZE_PASS_DEPENDENCY(LoopInfo)
104INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
105INITIALIZE_PASS_DEPENDENCY(LCSSA)
106INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000107INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000108INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
109 false, false)
110
111Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
112
Chris Lattner9f391882010-12-27 00:03:23 +0000113/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
114/// and zero out all the operands of this instruction. If any of them become
115/// dead, delete them and the computation tree that feeds them.
116///
117static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
118 SmallVector<Instruction*, 32> NowDeadInsts;
119
120 NowDeadInsts.push_back(I);
121
122 // Before we touch this instruction, remove it from SE!
123 do {
124 Instruction *DeadInst = NowDeadInsts.pop_back_val();
125
126 // This instruction is dead, zap it, in stages. Start by removing it from
127 // SCEV.
128 SE.forgetValue(DeadInst);
129
130 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
131 Value *Op = DeadInst->getOperand(op);
132 DeadInst->setOperand(op, 0);
133
134 // If this operand just became dead, add it to the NowDeadInsts list.
135 if (!Op->use_empty()) continue;
136
137 if (Instruction *OpI = dyn_cast<Instruction>(Op))
138 if (isInstructionTriviallyDead(OpI))
139 NowDeadInsts.push_back(OpI);
140 }
141
142 DeadInst->eraseFromParent();
143
144 } while (!NowDeadInsts.empty());
145}
146
Chris Lattnere6bb6492010-12-26 19:39:38 +0000147bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000148 CurLoop = L;
149
Chris Lattner22920b52010-12-26 20:45:45 +0000150 // The trip count of the loop must be analyzable.
151 SE = &getAnalysis<ScalarEvolution>();
152 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
153 return false;
154 const SCEV *BECount = SE->getBackedgeTakenCount(L);
155 if (isa<SCEVCouldNotCompute>(BECount)) return false;
156
157 // We require target data for now.
158 TD = getAnalysisIfAvailable<TargetData>();
159 if (TD == 0) return false;
160
Chris Lattnercf078f22011-01-02 07:58:36 +0000161 // TODO: We currently only scan the header of the loop, because it is the only
162 // part that is known to execute and we don't want to make a conditional store
163 // into an unconditional one in the preheader. However, there can be diamonds
164 // and other things in the loop that would make other blocks "always executed"
165 // we should get the full set and scan each block.
Chris Lattnere6bb6492010-12-26 19:39:38 +0000166 BasicBlock *BB = L->getHeader();
Chris Lattner22920b52010-12-26 20:45:45 +0000167 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
Chris Lattnere6bb6492010-12-26 19:39:38 +0000168 << "] Loop %" << BB->getName() << "\n");
169
Chris Lattner22920b52010-12-26 20:45:45 +0000170 bool MadeChange = false;
171 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
172 // Look for store instructions, which may be memsets.
Chris Lattnera92ff912010-12-26 23:42:51 +0000173 StoreInst *SI = dyn_cast<StoreInst>(I++);
174 if (SI == 0 || SI->isVolatile()) continue;
175
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000176 WeakVH InstPtr(SI);
177 if (!processLoopStore(SI, BECount)) continue;
178
179 MadeChange = true;
180
181 // If processing the store invalidated our iterator, start over from the
182 // head of the loop.
183 if (InstPtr == 0)
184 I = BB->begin();
Chris Lattner22920b52010-12-26 20:45:45 +0000185 }
186
187 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000188}
189
190/// scanBlock - Look over a block to see if we can promote anything out of it.
Chris Lattner22920b52010-12-26 20:45:45 +0000191bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
192 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000193 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000194
Chris Lattner95ae6762010-12-28 18:53:48 +0000195 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000196 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000197 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000198 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000199
Chris Lattner22920b52010-12-26 20:45:45 +0000200 // See if the pointer expression is an AddRec like {base,+,1} on the current
201 // loop, which indicates a strided store. If we have something else, it's a
202 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000203 const SCEVAddRecExpr *StoreEv =
204 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
205 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000206 return false;
207
208 // Check to see if the stride matches the size of the store. If so, then we
209 // know that every byte is touched in the loop.
210 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000211 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Chris Lattner30980b62011-01-01 19:39:01 +0000212
213 // TODO: Could also handle negative stride here someday, that will require the
214 // validity check in mayLoopModRefLocation to be updated though.
Chris Lattner22920b52010-12-26 20:45:45 +0000215 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
216 return false;
217
Chris Lattner22920b52010-12-26 20:45:45 +0000218 // If the stored value is a byte-wise value (like i32 -1), then it may be
219 // turned into a memset of i8 -1, assuming that all the consequtive bytes
220 // are stored. A store of i32 0x01020304 can never be turned into a memset.
Chris Lattnera92ff912010-12-26 23:42:51 +0000221 if (Value *SplatValue = isBytewiseValue(StoredVal))
Chris Lattnere2c43922011-01-02 03:37:56 +0000222 if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
223 BECount))
224 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000225
Chris Lattnere2c43922011-01-02 03:37:56 +0000226 // If the stored value is a strided load in the same loop with the same stride
227 // this this may be transformable into a memcpy. This kicks in for stuff like
228 // for (i) A[i] = B[i];
229 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
230 const SCEVAddRecExpr *LoadEv =
231 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
232 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
233 StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
234 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
235 return true;
236 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000237 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000238
Chris Lattnere6bb6492010-12-26 19:39:38 +0000239 return false;
240}
241
Chris Lattner30980b62011-01-01 19:39:01 +0000242/// mayLoopModRefLocation - Return true if the specified loop might do a load or
243/// store to the same location that the specified store could store to, which is
244/// a loop-strided access.
Chris Lattnere2c43922011-01-02 03:37:56 +0000245static bool mayLoopModRefLocation(Value *Ptr, Loop *L, const SCEV *BECount,
246 unsigned StoreSize, AliasAnalysis &AA,
247 StoreInst *IgnoredStore) {
Chris Lattner30980b62011-01-01 19:39:01 +0000248 // Get the location that may be stored across the loop. Since the access is
249 // strided positively through memory, we say that the modified location starts
250 // at the pointer and has infinite size.
Chris Lattnera64cbf02011-01-01 19:54:22 +0000251 uint64_t AccessSize = AliasAnalysis::UnknownSize;
252
253 // If the loop iterates a fixed number of times, we can refine the access size
254 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
255 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
256 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
257
258 // TODO: For this to be really effective, we have to dive into the pointer
259 // operand in the store. Store to &A[i] of 100 will always return may alias
260 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
261 // which will then no-alias a store to &A[100].
Chris Lattnere2c43922011-01-02 03:37:56 +0000262 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
Chris Lattner30980b62011-01-01 19:39:01 +0000263
264 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
265 ++BI)
266 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chris Lattnere2c43922011-01-02 03:37:56 +0000267 if (&*I != IgnoredStore &&
268 AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
Chris Lattner30980b62011-01-01 19:39:01 +0000269 return true;
270
271 return false;
272}
273
Chris Lattnera92ff912010-12-26 23:42:51 +0000274/// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
275/// If we can transform this into a memset in the loop preheader, do so.
276bool LoopIdiomRecognize::
277processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
278 Value *SplatValue,
279 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
Chris Lattnerbafa1172011-01-01 20:12:04 +0000280 // Verify that the stored value is loop invariant. If not, we can't promote
281 // the memset.
282 if (!CurLoop->isLoopInvariant(SplatValue))
283 return false;
284
Chris Lattnera92ff912010-12-26 23:42:51 +0000285 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
286 // this into a memset in the loop preheader now if we want. However, this
287 // would be unsafe to do if there is anything else in the loop that may read
288 // or write to the aliased location. Check for an alias.
Chris Lattnere2c43922011-01-02 03:37:56 +0000289 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
290 StoreSize, getAnalysis<AliasAnalysis>(), SI))
291 return false;
Chris Lattnera92ff912010-12-26 23:42:51 +0000292
293 // Okay, everything looks good, insert the memset.
294 BasicBlock *Preheader = CurLoop->getLoopPreheader();
295
296 IRBuilder<> Builder(Preheader->getTerminator());
297
298 // The trip count of the loop and the base pointer of the addrec SCEV is
299 // guaranteed to be loop invariant, which means that it should dominate the
300 // header. Just insert code for it in the preheader.
301 SCEVExpander Expander(*SE);
302
303 unsigned AddrSpace = SI->getPointerAddressSpace();
304 Value *BasePtr =
305 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
306 Preheader->getTerminator());
307
308 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
309 // pointer size if it isn't already.
310 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
311 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
312 if (BESize < TD->getPointerSizeInBits())
313 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
314 else if (BESize > TD->getPointerSizeInBits())
315 BECount = SE->getTruncateExpr(BECount, IntPtr);
316
317 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
318 true, true /*nooverflow*/);
319 if (StoreSize != 1)
320 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
321 true, true /*nooverflow*/);
322
323 Value *NumBytes =
324 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
325
326 Value *NewCall =
327 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
328
329 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
330 << " from store to: " << *Ev << " at: " << *SI << "\n");
Duncan Sands7922d342010-12-28 09:41:15 +0000331 (void)NewCall;
Chris Lattnera92ff912010-12-26 23:42:51 +0000332
Chris Lattner9f391882010-12-27 00:03:23 +0000333 // Okay, the memset has been formed. Zap the original store and anything that
334 // feeds into it.
335 DeleteDeadInstruction(SI, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000336 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +0000337 return true;
338}
339
Chris Lattnere2c43922011-01-02 03:37:56 +0000340/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
341/// same-strided load.
342bool LoopIdiomRecognize::
343processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
344 const SCEVAddRecExpr *StoreEv,
345 const SCEVAddRecExpr *LoadEv,
346 const SCEV *BECount) {
347 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
348
349 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chris Lattnerbdce5722011-01-02 18:32:09 +0000350 // this into a memcpy in the loop preheader now if we want. However, this
Chris Lattnere2c43922011-01-02 03:37:56 +0000351 // would be unsafe to do if there is anything else in the loop that may read
352 // or write to the aliased location (including the load feeding the stores).
353 // Check for an alias.
354 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
355 StoreSize, getAnalysis<AliasAnalysis>(), SI))
356 return false;
357
358 // Okay, everything looks good, insert the memcpy.
359 BasicBlock *Preheader = CurLoop->getLoopPreheader();
360
361 IRBuilder<> Builder(Preheader->getTerminator());
362
363 // The trip count of the loop and the base pointer of the addrec SCEV is
364 // guaranteed to be loop invariant, which means that it should dominate the
365 // header. Just insert code for it in the preheader.
366 SCEVExpander Expander(*SE);
367
368 Value *LoadBasePtr =
369 Expander.expandCodeFor(LoadEv->getStart(),
370 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
371 Preheader->getTerminator());
372 Value *StoreBasePtr =
373 Expander.expandCodeFor(StoreEv->getStart(),
374 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
375 Preheader->getTerminator());
376
377 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
378 // pointer size if it isn't already.
379 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
380 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
381 if (BESize < TD->getPointerSizeInBits())
382 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
383 else if (BESize > TD->getPointerSizeInBits())
384 BECount = SE->getTruncateExpr(BECount, IntPtr);
385
386 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
387 true, true /*nooverflow*/);
388 if (StoreSize != 1)
389 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
390 true, true /*nooverflow*/);
391
392 Value *NumBytes =
393 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
394
395 Value *NewCall =
396 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
397 std::min(SI->getAlignment(), LI->getAlignment()));
398
399 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
400 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
401 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
402 (void)NewCall;
403
404 // Okay, the memset has been formed. Zap the original store and anything that
405 // feeds into it.
406 DeleteDeadInstruction(SI, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000407 ++NumMemCpy;
Chris Lattnere2c43922011-01-02 03:37:56 +0000408 return true;
409}