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,
52 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
53 const SCEVAddRecExpr *StoreEv,
54 const SCEVAddRecExpr *LoadEv,
57 /// This transformation requires natural loop information & requires that
58 /// loop preheaders be inserted into the CFG.
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);
67 AU.addRequired<AliasAnalysis>();
68 AU.addPreserved<AliasAnalysis>();
69 AU.addRequired<ScalarEvolution>();
70 AU.addPreserved<ScalarEvolution>();
71 AU.addPreserved<DominatorTree>();
76 char LoopIdiomRecognize::ID = 0;
77 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
79 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
80 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
81 INITIALIZE_PASS_DEPENDENCY(LCSSA)
82 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
83 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
84 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
87 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
89 /// 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.
93 static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
94 SmallVector<Instruction*, 32> NowDeadInsts;
96 NowDeadInsts.push_back(I);
98 // Before we touch this instruction, remove it from SE!
100 Instruction *DeadInst = NowDeadInsts.pop_back_val();
102 // This instruction is dead, zap it, in stages. Start by removing it from
104 SE.forgetValue(DeadInst);
106 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
107 Value *Op = DeadInst->getOperand(op);
108 DeadInst->setOperand(op, 0);
110 // If this operand just became dead, add it to the NowDeadInsts list.
111 if (!Op->use_empty()) continue;
113 if (Instruction *OpI = dyn_cast<Instruction>(Op))
114 if (isInstructionTriviallyDead(OpI))
115 NowDeadInsts.push_back(OpI);
118 DeadInst->eraseFromParent();
120 } while (!NowDeadInsts.empty());
123 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
126 // 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)
131 // The trip count of the loop must be analyzable.
132 SE = &getAnalysis<ScalarEvolution>();
133 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
135 const SCEV *BECount = SE->getBackedgeTakenCount(L);
136 if (isa<SCEVCouldNotCompute>(BECount)) return false;
138 // We require target data for now.
139 TD = getAnalysisIfAvailable<TargetData>();
140 if (TD == 0) return false;
142 BasicBlock *BB = L->getHeader();
143 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
144 << "] Loop %" << BB->getName() << "\n");
146 bool MadeChange = false;
147 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
148 // Look for store instructions, which may be memsets.
149 StoreInst *SI = dyn_cast<StoreInst>(I++);
150 if (SI == 0 || SI->isVolatile()) continue;
153 if (!processLoopStore(SI, BECount)) continue;
157 // If processing the store invalidated our iterator, start over from the
166 /// scanBlock - Look over a block to see if we can promote anything out of it.
167 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
168 Value *StoredVal = SI->getValueOperand();
169 Value *StorePtr = SI->getPointerOperand();
171 // Reject stores that are so large that they overflow an unsigned.
172 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
173 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
176 // 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.
179 const SCEVAddRecExpr *StoreEv =
180 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
181 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
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;
187 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
189 // TODO: Could also handle negative stride here someday, that will require the
190 // validity check in mayLoopModRefLocation to be updated though.
191 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
194 // 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.
197 if (Value *SplatValue = isBytewiseValue(StoredVal))
198 if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
202 // 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))
213 // errs() << "UNHANDLED strided store: " << *Ev << " - " << *SI << "\n";
218 /// 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.
221 static bool mayLoopModRefLocation(Value *Ptr, Loop *L, const SCEV *BECount,
222 unsigned StoreSize, AliasAnalysis &AA,
223 StoreInst *IgnoredStore) {
224 // 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.
227 uint64_t AccessSize = AliasAnalysis::UnknownSize;
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;
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].
238 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
240 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
242 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
243 if (&*I != IgnoredStore &&
244 AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
250 /// 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.
252 bool LoopIdiomRecognize::
253 processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
255 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
256 // Verify that the stored value is loop invariant. If not, we can't promote
258 if (!CurLoop->isLoopInvariant(SplatValue))
261 // 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.
265 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
266 StoreSize, getAnalysis<AliasAnalysis>(), SI))
269 // Okay, everything looks good, insert the memset.
270 BasicBlock *Preheader = CurLoop->getLoopPreheader();
272 IRBuilder<> Builder(Preheader->getTerminator());
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);
279 unsigned AddrSpace = SI->getPointerAddressSpace();
281 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
282 Preheader->getTerminator());
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);
293 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
294 true, true /*nooverflow*/);
296 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
297 true, true /*nooverflow*/);
300 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
303 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
305 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
306 << " from store to: " << *Ev << " at: " << *SI << "\n");
309 // Okay, the memset has been formed. Zap the original store and anything that
311 DeleteDeadInstruction(SI, *SE);
315 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
316 /// same-strided load.
317 bool LoopIdiomRecognize::
318 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
319 const SCEVAddRecExpr *StoreEv,
320 const SCEVAddRecExpr *LoadEv,
321 const SCEV *BECount) {
322 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
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))
333 // Okay, everything looks good, insert the memcpy.
334 BasicBlock *Preheader = CurLoop->getLoopPreheader();
336 IRBuilder<> Builder(Preheader->getTerminator());
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);
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());
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);
361 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
362 true, true /*nooverflow*/);
364 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
365 true, true /*nooverflow*/);
368 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
371 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
372 std::min(SI->getAlignment(), LI->getAlignment()));
374 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
375 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
376 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
379 // Okay, the memset has been formed. Zap the original store and anything that
381 DeleteDeadInstruction(SI, *SE);