1 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
18 // Future loop memory idioms to recognize:
19 // memcmp, memmove, strlen, etc.
20 // Future floating point idioms to recognize in -ffast-math mode:
22 // Future integer operation idioms to recognize:
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.
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
35 // This could recognize common matrix multiplies and dot product idioms and
36 // replace them with calls to BLAS (if linked in??).
38 //===----------------------------------------------------------------------===//
40 #define DEBUG_TYPE "loop-idiom"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Analysis/AliasAnalysis.h"
43 #include "llvm/Analysis/LoopPass.h"
44 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
45 #include "llvm/Analysis/ScalarEvolutionExpander.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/IRBuilder.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/ADT/Statistic.h"
55 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
56 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
59 class LoopIdiomRecognize : public LoopPass {
66 explicit LoopIdiomRecognize() : LoopPass(ID) {
67 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
70 bool runOnLoop(Loop *L, LPPassManager &LPM);
71 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
72 SmallVectorImpl<BasicBlock*> &ExitBlocks);
74 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
76 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
78 const SCEVAddRecExpr *Ev,
80 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
81 const SCEVAddRecExpr *StoreEv,
82 const SCEVAddRecExpr *LoadEv,
85 /// This transformation requires natural loop information & requires that
86 /// loop preheaders be inserted into the CFG.
88 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addRequired<LoopInfo>();
90 AU.addPreserved<LoopInfo>();
91 AU.addRequiredID(LoopSimplifyID);
92 AU.addPreservedID(LoopSimplifyID);
93 AU.addRequiredID(LCSSAID);
94 AU.addPreservedID(LCSSAID);
95 AU.addRequired<AliasAnalysis>();
96 AU.addPreserved<AliasAnalysis>();
97 AU.addRequired<ScalarEvolution>();
98 AU.addPreserved<ScalarEvolution>();
99 AU.addPreserved<DominatorTree>();
100 AU.addRequired<DominatorTree>();
105 char LoopIdiomRecognize::ID = 0;
106 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
108 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
109 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
110 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
111 INITIALIZE_PASS_DEPENDENCY(LCSSA)
112 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
113 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
114 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
117 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
119 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
120 /// and zero out all the operands of this instruction. If any of them become
121 /// dead, delete them and the computation tree that feeds them.
123 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
124 SmallVector<Instruction*, 32> NowDeadInsts;
126 NowDeadInsts.push_back(I);
128 // Before we touch this instruction, remove it from SE!
130 Instruction *DeadInst = NowDeadInsts.pop_back_val();
132 // This instruction is dead, zap it, in stages. Start by removing it from
134 SE.forgetValue(DeadInst);
136 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
137 Value *Op = DeadInst->getOperand(op);
138 DeadInst->setOperand(op, 0);
140 // If this operand just became dead, add it to the NowDeadInsts list.
141 if (!Op->use_empty()) continue;
143 if (Instruction *OpI = dyn_cast<Instruction>(Op))
144 if (isInstructionTriviallyDead(OpI))
145 NowDeadInsts.push_back(OpI);
148 DeadInst->eraseFromParent();
150 } while (!NowDeadInsts.empty());
153 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
156 // The trip count of the loop must be analyzable.
157 SE = &getAnalysis<ScalarEvolution>();
158 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
160 const SCEV *BECount = SE->getBackedgeTakenCount(L);
161 if (isa<SCEVCouldNotCompute>(BECount)) return false;
163 // If this loop executes exactly one time, then it should be peeled, not
164 // optimized by this pass.
165 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
166 if (BECst->getValue()->getValue() == 0)
169 // We require target data for now.
170 TD = getAnalysisIfAvailable<TargetData>();
171 if (TD == 0) return false;
173 DT = &getAnalysis<DominatorTree>();
174 LoopInfo &LI = getAnalysis<LoopInfo>();
176 SmallVector<BasicBlock*, 8> ExitBlocks;
177 CurLoop->getUniqueExitBlocks(ExitBlocks);
179 DEBUG(dbgs() << "loop-idiom Scanning: F["
180 << L->getHeader()->getParent()->getName()
181 << "] Loop %" << L->getHeader()->getName() << "\n");
183 bool MadeChange = false;
184 // Scan all the blocks in the loop that are not in subloops.
185 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
187 // Ignore blocks in subloops.
188 if (LI.getLoopFor(*BI) != CurLoop)
191 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
196 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
197 /// with the specified backedge count. This block is known to be in the current
198 /// loop and not in any subloops.
199 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
200 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
201 // We can only promote stores in this block if they are unconditionally
202 // executed in the loop. For a block to be unconditionally executed, it has
203 // to dominate all the exit blocks of the loop. Verify this now.
204 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
205 if (!DT->dominates(BB, ExitBlocks[i]))
208 bool MadeChange = false;
209 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
210 Instruction *Inst = I++;
211 // Look for store instructions, which may be optimized to memset/memcpy.
212 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
213 if (SI->isVolatile()) continue;
216 if (!processLoopStore(SI, BECount)) continue;
219 // If processing the store invalidated our iterator, start over from the
232 /// scanBlock - Look over a block to see if we can promote anything out of it.
233 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
234 Value *StoredVal = SI->getValueOperand();
235 Value *StorePtr = SI->getPointerOperand();
237 // Reject stores that are so large that they overflow an unsigned.
238 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
239 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
242 // See if the pointer expression is an AddRec like {base,+,1} on the current
243 // loop, which indicates a strided store. If we have something else, it's a
244 // random store we can't handle.
245 const SCEVAddRecExpr *StoreEv =
246 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
247 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
250 // Check to see if the stride matches the size of the store. If so, then we
251 // know that every byte is touched in the loop.
252 unsigned StoreSize = (unsigned)SizeInBits >> 3;
253 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
255 // TODO: Could also handle negative stride here someday, that will require the
256 // validity check in mayLoopAccessLocation to be updated though.
257 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
260 // If the stored value is a byte-wise value (like i32 -1), then it may be
261 // turned into a memset of i8 -1, assuming that all the consequtive bytes
262 // are stored. A store of i32 0x01020304 can never be turned into a memset.
263 if (Value *SplatValue = isBytewiseValue(StoredVal))
264 if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
268 // If the stored value is a strided load in the same loop with the same stride
269 // this this may be transformable into a memcpy. This kicks in for stuff like
270 // for (i) A[i] = B[i];
271 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
272 const SCEVAddRecExpr *LoadEv =
273 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
274 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
275 StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
276 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
279 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
284 /// mayLoopAccessLocation - Return true if the specified loop might access the
285 /// specified pointer location, which is a loop-strided access. The 'Access'
286 /// argument specifies what the verboten forms of access are (read or write).
287 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
288 Loop *L, const SCEV *BECount,
289 unsigned StoreSize, AliasAnalysis &AA,
290 StoreInst *IgnoredStore) {
291 // Get the location that may be stored across the loop. Since the access is
292 // strided positively through memory, we say that the modified location starts
293 // at the pointer and has infinite size.
294 uint64_t AccessSize = AliasAnalysis::UnknownSize;
296 // If the loop iterates a fixed number of times, we can refine the access size
297 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
298 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
299 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
301 // TODO: For this to be really effective, we have to dive into the pointer
302 // operand in the store. Store to &A[i] of 100 will always return may alias
303 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
304 // which will then no-alias a store to &A[100].
305 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
307 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
309 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
310 if (&*I != IgnoredStore &&
311 (AA.getModRefInfo(I, StoreLoc) & Access))
317 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
318 /// If we can transform this into a memset in the loop preheader, do so.
319 bool LoopIdiomRecognize::
320 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
322 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
323 // Verify that the stored value is loop invariant. If not, we can't promote
325 if (!CurLoop->isLoopInvariant(SplatValue))
328 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
329 // this into a memset in the loop preheader now if we want. However, this
330 // would be unsafe to do if there is anything else in the loop that may read
331 // or write to the aliased location. Check for an alias.
332 if (mayLoopAccessLocation(SI->getPointerOperand(), AliasAnalysis::ModRef,
334 StoreSize, getAnalysis<AliasAnalysis>(), SI))
337 // Okay, everything looks good, insert the memset.
338 BasicBlock *Preheader = CurLoop->getLoopPreheader();
340 IRBuilder<> Builder(Preheader->getTerminator());
342 // The trip count of the loop and the base pointer of the addrec SCEV is
343 // guaranteed to be loop invariant, which means that it should dominate the
344 // header. Just insert code for it in the preheader.
345 SCEVExpander Expander(*SE);
347 unsigned AddrSpace = SI->getPointerAddressSpace();
349 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
350 Preheader->getTerminator());
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 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
357 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
358 true /*no unsigned overflow*/);
360 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
361 true /*no unsigned overflow*/);
364 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
367 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
369 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
370 << " from store to: " << *Ev << " at: " << *SI << "\n");
373 // Okay, the memset has been formed. Zap the original store and anything that
375 DeleteDeadInstruction(SI, *SE);
380 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
381 /// same-strided load.
382 bool LoopIdiomRecognize::
383 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
384 const SCEVAddRecExpr *StoreEv,
385 const SCEVAddRecExpr *LoadEv,
386 const SCEV *BECount) {
387 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
389 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
390 // this into a memcpy in the loop preheader now if we want. However, this
391 // would be unsafe to do if there is anything else in the loop that may read
392 // or write to the stored location (including the load feeding the stores).
393 // Check for an alias.
394 if (mayLoopAccessLocation(SI->getPointerOperand(), AliasAnalysis::ModRef,
395 CurLoop, BECount, StoreSize,
396 getAnalysis<AliasAnalysis>(), SI))
399 // For a memcpy, we have to make sure that the input array is not being
400 // mutated by the loop.
401 if (mayLoopAccessLocation(LI->getPointerOperand(), AliasAnalysis::Mod,
402 CurLoop, BECount, StoreSize,
403 getAnalysis<AliasAnalysis>(), SI))
406 // Okay, everything looks good, insert the memcpy.
407 BasicBlock *Preheader = CurLoop->getLoopPreheader();
409 IRBuilder<> Builder(Preheader->getTerminator());
411 // The trip count of the loop and the base pointer of the addrec SCEV is
412 // guaranteed to be loop invariant, which means that it should dominate the
413 // header. Just insert code for it in the preheader.
414 SCEVExpander Expander(*SE);
417 Expander.expandCodeFor(LoadEv->getStart(),
418 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
419 Preheader->getTerminator());
420 Value *StoreBasePtr =
421 Expander.expandCodeFor(StoreEv->getStart(),
422 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
423 Preheader->getTerminator());
425 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
426 // pointer size if it isn't already.
427 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
428 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
430 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
431 true /*no unsigned overflow*/);
433 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
434 true /*no unsigned overflow*/);
437 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
440 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
441 std::min(SI->getAlignment(), LI->getAlignment()));
443 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
444 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
445 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
448 // Okay, the memset has been formed. Zap the original store and anything that
450 DeleteDeadInstruction(SI, *SE);