blob: 2b6723f0cafe0c434d28bf85e90dc440b2d4efda [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//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "loop-idiom"
17#include "llvm/Transforms/Scalar.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000018#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000019#include "llvm/Analysis/LoopPass.h"
20#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000021#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000022#include "llvm/Analysis/ValueTracking.h"
23#include "llvm/Target/TargetData.h"
Chris Lattner9f391882010-12-27 00:03:23 +000024#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000025#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000026#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000027#include "llvm/Support/raw_ostream.h"
28using namespace llvm;
29
30// TODO: Recognize "N" size array multiplies: replace with call to blas or
31// something.
32
33namespace {
34 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000035 Loop *CurLoop;
36 const TargetData *TD;
37 ScalarEvolution *SE;
Chris Lattnere6bb6492010-12-26 19:39:38 +000038 public:
39 static char ID;
40 explicit LoopIdiomRecognize() : LoopPass(ID) {
41 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
42 }
43
44 bool runOnLoop(Loop *L, LPPassManager &LPM);
45
Chris Lattner22920b52010-12-26 20:45:45 +000046 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000047
Chris Lattnera92ff912010-12-26 23:42:51 +000048 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
49 Value *SplatValue,
50 const SCEVAddRecExpr *Ev,
51 const SCEV *BECount);
52
Chris Lattnere6bb6492010-12-26 19:39:38 +000053 /// This transformation requires natural loop information & requires that
54 /// loop preheaders be inserted into the CFG.
55 ///
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);
Chris Lattner2e12f1a2010-12-27 18:39:08 +000063 AU.addRequired<AliasAnalysis>();
64 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +000065 AU.addRequired<ScalarEvolution>();
66 AU.addPreserved<ScalarEvolution>();
67 AU.addPreserved<DominatorTree>();
68 }
69 };
70}
71
72char LoopIdiomRecognize::ID = 0;
73INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
74 false, false)
75INITIALIZE_PASS_DEPENDENCY(LoopInfo)
76INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
77INITIALIZE_PASS_DEPENDENCY(LCSSA)
78INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattner2e12f1a2010-12-27 18:39:08 +000079INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +000080INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
81 false, false)
82
83Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
84
Chris Lattner9f391882010-12-27 00:03:23 +000085/// 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.
88///
89static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
90 SmallVector<Instruction*, 32> NowDeadInsts;
91
92 NowDeadInsts.push_back(I);
93
94 // Before we touch this instruction, remove it from SE!
95 do {
96 Instruction *DeadInst = NowDeadInsts.pop_back_val();
97
98 // This instruction is dead, zap it, in stages. Start by removing it from
99 // SCEV.
100 SE.forgetValue(DeadInst);
101
102 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
103 Value *Op = DeadInst->getOperand(op);
104 DeadInst->setOperand(op, 0);
105
106 // If this operand just became dead, add it to the NowDeadInsts list.
107 if (!Op->use_empty()) continue;
108
109 if (Instruction *OpI = dyn_cast<Instruction>(Op))
110 if (isInstructionTriviallyDead(OpI))
111 NowDeadInsts.push_back(OpI);
112 }
113
114 DeadInst->eraseFromParent();
115
116 } while (!NowDeadInsts.empty());
117}
118
Chris Lattnere6bb6492010-12-26 19:39:38 +0000119bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000120 CurLoop = L;
121
Chris Lattnere6bb6492010-12-26 19:39:38 +0000122 // 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)
125 return false;
126
Chris Lattner22920b52010-12-26 20:45:45 +0000127 // The trip count of the loop must be analyzable.
128 SE = &getAnalysis<ScalarEvolution>();
129 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
130 return false;
131 const SCEV *BECount = SE->getBackedgeTakenCount(L);
132 if (isa<SCEVCouldNotCompute>(BECount)) return false;
133
134 // We require target data for now.
135 TD = getAnalysisIfAvailable<TargetData>();
136 if (TD == 0) return false;
137
Chris Lattnere6bb6492010-12-26 19:39:38 +0000138 BasicBlock *BB = L->getHeader();
Chris Lattner22920b52010-12-26 20:45:45 +0000139 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
Chris Lattnere6bb6492010-12-26 19:39:38 +0000140 << "] Loop %" << BB->getName() << "\n");
141
Chris Lattner22920b52010-12-26 20:45:45 +0000142 bool MadeChange = false;
143 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
144 // Look for store instructions, which may be memsets.
Chris Lattnera92ff912010-12-26 23:42:51 +0000145 StoreInst *SI = dyn_cast<StoreInst>(I++);
146 if (SI == 0 || SI->isVolatile()) continue;
147
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000148 WeakVH InstPtr(SI);
149 if (!processLoopStore(SI, BECount)) continue;
150
151 MadeChange = true;
152
153 // If processing the store invalidated our iterator, start over from the
154 // head of the loop.
155 if (InstPtr == 0)
156 I = BB->begin();
Chris Lattner22920b52010-12-26 20:45:45 +0000157 }
158
159 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000160}
161
162/// scanBlock - Look over a block to see if we can promote anything out of it.
Chris Lattner22920b52010-12-26 20:45:45 +0000163bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
164 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000165 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000166
Chris Lattner95ae6762010-12-28 18:53:48 +0000167 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000168 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000169 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000170 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000171
Chris Lattner22920b52010-12-26 20:45:45 +0000172 // 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.
Chris Lattnera92ff912010-12-26 23:42:51 +0000175 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
Chris Lattner22920b52010-12-26 20:45:45 +0000176 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
177 return false;
178
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));
183 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
184 return false;
185
Chris Lattner22920b52010-12-26 20:45:45 +0000186 // If the stored value is a byte-wise value (like i32 -1), then it may be
187 // turned into a memset of i8 -1, assuming that all the consequtive bytes
188 // are stored. A store of i32 0x01020304 can never be turned into a memset.
Chris Lattnera92ff912010-12-26 23:42:51 +0000189 if (Value *SplatValue = isBytewiseValue(StoredVal))
190 return processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, Ev, BECount);
191
192 // Handle the memcpy case here.
193 errs() << "Found strided store: " << *Ev << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000194
195
Chris Lattnere6bb6492010-12-26 19:39:38 +0000196 return false;
197}
198
Chris Lattnera92ff912010-12-26 23:42:51 +0000199/// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
200/// If we can transform this into a memset in the loop preheader, do so.
201bool LoopIdiomRecognize::
202processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
203 Value *SplatValue,
204 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
205 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
206 // this into a memset in the loop preheader now if we want. However, this
207 // would be unsafe to do if there is anything else in the loop that may read
208 // or write to the aliased location. Check for an alias.
209
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000210 // FIXME: Need to get a base pointer that is valid.
211 // if (LoopCanModRefLocation(SI->getPointerOperand())
212
213
Chris Lattnera92ff912010-12-26 23:42:51 +0000214 // FIXME: TODO safety check.
215
216 // Okay, everything looks good, insert the memset.
217 BasicBlock *Preheader = CurLoop->getLoopPreheader();
218
219 IRBuilder<> Builder(Preheader->getTerminator());
220
221 // The trip count of the loop and the base pointer of the addrec SCEV is
222 // guaranteed to be loop invariant, which means that it should dominate the
223 // header. Just insert code for it in the preheader.
224 SCEVExpander Expander(*SE);
225
226 unsigned AddrSpace = SI->getPointerAddressSpace();
227 Value *BasePtr =
228 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
229 Preheader->getTerminator());
230
231 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
232 // pointer size if it isn't already.
233 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
234 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
235 if (BESize < TD->getPointerSizeInBits())
236 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
237 else if (BESize > TD->getPointerSizeInBits())
238 BECount = SE->getTruncateExpr(BECount, IntPtr);
239
240 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
241 true, true /*nooverflow*/);
242 if (StoreSize != 1)
243 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
244 true, true /*nooverflow*/);
245
246 Value *NumBytes =
247 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
248
249 Value *NewCall =
250 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
251
252 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
253 << " from store to: " << *Ev << " at: " << *SI << "\n");
Duncan Sands7922d342010-12-28 09:41:15 +0000254 (void)NewCall;
Chris Lattnera92ff912010-12-26 23:42:51 +0000255
Chris Lattner9f391882010-12-27 00:03:23 +0000256 // Okay, the memset has been formed. Zap the original store and anything that
257 // feeds into it.
258 DeleteDeadInstruction(SI, *SE);
Chris Lattnera92ff912010-12-26 23:42:51 +0000259 return true;
260}
261