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 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "loop-idiom"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ScalarEvolutionExpander.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/IRBuilder.h"
25 #include "llvm/Support/raw_ostream.h"
28 // TODO: Recognize "N" size array multiplies: replace with call to blas or
32 class LoopIdiomRecognize : public LoopPass {
38 explicit LoopIdiomRecognize() : LoopPass(ID) {
39 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
42 bool runOnLoop(Loop *L, LPPassManager &LPM);
44 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
46 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
48 const SCEVAddRecExpr *Ev,
51 /// This transformation requires natural loop information & requires that
52 /// loop preheaders be inserted into the CFG.
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>();
68 char LoopIdiomRecognize::ID = 0;
69 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
71 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
72 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
73 INITIALIZE_PASS_DEPENDENCY(LCSSA)
74 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
75 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
78 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
80 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
83 // 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)
88 // The trip count of the loop must be analyzable.
89 SE = &getAnalysis<ScalarEvolution>();
90 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
92 const SCEV *BECount = SE->getBackedgeTakenCount(L);
93 if (isa<SCEVCouldNotCompute>(BECount)) return false;
95 // We require target data for now.
96 TD = getAnalysisIfAvailable<TargetData>();
97 if (TD == 0) return false;
99 BasicBlock *BB = L->getHeader();
100 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
101 << "] Loop %" << BB->getName() << "\n");
103 bool MadeChange = false;
104 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
105 // Look for store instructions, which may be memsets.
106 StoreInst *SI = dyn_cast<StoreInst>(I++);
107 if (SI == 0 || SI->isVolatile()) continue;
110 MadeChange |= processLoopStore(SI, BECount);
116 /// scanBlock - Look over a block to see if we can promote anything out of it.
117 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
118 Value *StoredVal = SI->getValueOperand();
119 Value *StorePtr = SI->getPointerOperand();
121 // 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()))
129 // 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.
132 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
133 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
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())
143 // 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.
146 if (Value *SplatValue = isBytewiseValue(StoredVal))
147 return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
149 // Handle the memcpy case here.
150 errs() << "Found strided store: " << *Ev << "\n";
156 /// 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.
158 bool LoopIdiomRecognize::
159 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
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.
167 // FIXME: TODO safety check.
169 // Okay, everything looks good, insert the memset.
170 BasicBlock *Preheader = CurLoop->getLoopPreheader();
172 IRBuilder<> Builder(Preheader->getTerminator());
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);
179 unsigned AddrSpace = SI->getPointerAddressSpace();
181 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
182 Preheader->getTerminator());
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);
193 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
194 true, true /*nooverflow*/);
196 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
197 true, true /*nooverflow*/);
200 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
203 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
205 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
206 << " from store to: " << *Ev << " at: " << *SI << "\n");
208 // Okay, the memset has been formed. Zap the original store.
209 // FIXME: We want to recursively delete dead instructions, but we have to
211 SI->eraseFromParent();