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/AliasAnalysis.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
21 #include "llvm/Analysis/ScalarEvolutionExpander.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/IRBuilder.h"
27 #include "llvm/Support/raw_ostream.h"
30 // TODO: Recognize "N" size array multiplies: replace with call to blas or
34 class LoopIdiomRecognize : public LoopPass {
40 explicit LoopIdiomRecognize() : LoopPass(ID) {
41 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
44 bool runOnLoop(Loop *L, LPPassManager &LPM);
46 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
48 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
50 const SCEVAddRecExpr *Ev,
53 /// This transformation requires natural loop information & requires that
54 /// loop preheaders be inserted into the CFG.
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired<LoopInfo>();
58 AU.addPreserved<LoopInfo>();
59 AU.addRequiredID(LoopSimplifyID);
60 AU.addPreservedID(LoopSimplifyID);
61 AU.addRequiredID(LCSSAID);
62 AU.addPreservedID(LCSSAID);
63 AU.addRequired<AliasAnalysis>();
64 AU.addPreserved<AliasAnalysis>();
65 AU.addRequired<ScalarEvolution>();
66 AU.addPreserved<ScalarEvolution>();
67 AU.addPreserved<DominatorTree>();
72 char LoopIdiomRecognize::ID = 0;
73 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
75 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
76 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
77 INITIALIZE_PASS_DEPENDENCY(LCSSA)
78 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
79 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
80 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
83 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
85 /// DeleteDeadInstruction - Delete this instruction. Before we do, go through
86 /// and zero out all the operands of this instruction. If any of them become
87 /// dead, delete them and the computation tree that feeds them.
89 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
90 SmallVector<Instruction*, 32> NowDeadInsts;
92 NowDeadInsts.push_back(I);
94 // Before we touch this instruction, remove it from SE!
96 Instruction *DeadInst = NowDeadInsts.pop_back_val();
98 // This instruction is dead, zap it, in stages. Start by removing it from
100 SE.forgetValue(DeadInst);
102 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
103 Value *Op = DeadInst->getOperand(op);
104 DeadInst->setOperand(op, 0);
106 // If this operand just became dead, add it to the NowDeadInsts list.
107 if (!Op->use_empty()) continue;
109 if (Instruction *OpI = dyn_cast<Instruction>(Op))
110 if (isInstructionTriviallyDead(OpI))
111 NowDeadInsts.push_back(OpI);
114 DeadInst->eraseFromParent();
116 } while (!NowDeadInsts.empty());
119 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
122 // We only look at trivial single basic block loops.
123 // TODO: eventually support more complex loops, scanning the header.
124 if (L->getBlocks().size() != 1)
127 // The trip count of the loop must be analyzable.
128 SE = &getAnalysis<ScalarEvolution>();
129 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
131 const SCEV *BECount = SE->getBackedgeTakenCount(L);
132 if (isa<SCEVCouldNotCompute>(BECount)) return false;
134 // We require target data for now.
135 TD = getAnalysisIfAvailable<TargetData>();
136 if (TD == 0) return false;
138 BasicBlock *BB = L->getHeader();
139 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
140 << "] Loop %" << BB->getName() << "\n");
142 bool MadeChange = false;
143 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
144 // Look for store instructions, which may be memsets.
145 StoreInst *SI = dyn_cast<StoreInst>(I++);
146 if (SI == 0 || SI->isVolatile()) continue;
149 if (!processLoopStore(SI, BECount)) continue;
153 // If processing the store invalidated our iterator, start over from the
162 /// scanBlock - Look over a block to see if we can promote anything out of it.
163 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
164 Value *StoredVal = SI->getValueOperand();
165 Value *StorePtr = SI->getPointerOperand();
167 // Reject stores that are so large that they overflow an unsigned.
168 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
169 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
172 // See if the pointer expression is an AddRec like {base,+,1} on the current
173 // loop, which indicates a strided store. If we have something else, it's a
174 // random store we can't handle.
175 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
176 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
179 // Check to see if the stride matches the size of the store. If so, then we
180 // know that every byte is touched in the loop.
181 unsigned StoreSize = (unsigned)SizeInBits >> 3;
182 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
184 // TODO: Could also handle negative stride here someday, that will require the
185 // validity check in mayLoopModRefLocation to be updated though.
186 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
189 // If the stored value is a byte-wise value (like i32 -1), then it may be
190 // turned into a memset of i8 -1, assuming that all the consequtive bytes
191 // are stored. A store of i32 0x01020304 can never be turned into a memset.
192 if (Value *SplatValue = isBytewiseValue(StoredVal))
193 return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
195 // Handle the memcpy case here.
196 errs() << "Found strided store: " << *Ev << "\n";
202 /// mayLoopModRefLocation - Return true if the specified loop might do a load or
203 /// store to the same location that the specified store could store to, which is
204 /// a loop-strided access.
205 static bool mayLoopModRefLocation(StoreInst *SI, Loop *L, AliasAnalysis &AA) {
206 // Get the location that may be stored across the loop. Since the access is
207 // strided positively through memory, we say that the modified location starts
208 // at the pointer and has infinite size.
209 // TODO: Could improve this for constant trip-count loops.
210 AliasAnalysis::Location StoreLoc =
211 AliasAnalysis::Location(SI->getPointerOperand());
213 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
215 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
216 if (AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
222 /// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
223 /// If we can transform this into a memset in the loop preheader, do so.
224 bool LoopIdiomRecognize::
225 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
227 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
228 // Temporarily remove the store from the loop, to avoid the mod/ref query from
230 Instruction *InstAfterStore = ++BasicBlock::iterator(SI);
231 SI->removeFromParent();
233 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
234 // this into a memset in the loop preheader now if we want. However, this
235 // would be unsafe to do if there is anything else in the loop that may read
236 // or write to the aliased location. Check for an alias.
237 bool Unsafe=mayLoopModRefLocation(SI, CurLoop, getAnalysis<AliasAnalysis>());
239 SI->insertBefore(InstAfterStore);
241 if (Unsafe) return false;
243 // Okay, everything looks good, insert the memset.
244 BasicBlock *Preheader = CurLoop->getLoopPreheader();
246 IRBuilder<> Builder(Preheader->getTerminator());
248 // The trip count of the loop and the base pointer of the addrec SCEV is
249 // guaranteed to be loop invariant, which means that it should dominate the
250 // header. Just insert code for it in the preheader.
251 SCEVExpander Expander(*SE);
253 unsigned AddrSpace = SI->getPointerAddressSpace();
255 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
256 Preheader->getTerminator());
258 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
259 // pointer size if it isn't already.
260 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
261 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
262 if (BESize < TD->getPointerSizeInBits())
263 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
264 else if (BESize > TD->getPointerSizeInBits())
265 BECount = SE->getTruncateExpr(BECount, IntPtr);
267 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
268 true, true /*nooverflow*/);
270 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
271 true, true /*nooverflow*/);
274 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
277 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
279 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
280 << " from store to: " << *Ev << " at: " << *SI << "\n");
283 // Okay, the memset has been formed. Zap the original store and anything that
285 DeleteDeadInstruction(SI, *SE);