blob: 57a502b1d25fbb03972cc09940d8fa7aa0d75432 [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//===----------------------------------------------------------------------===//
Chris Lattnerbdce5722011-01-02 18:32:09 +000015//
16// TODO List:
17//
18// Future loop memory idioms to recognize:
19// memcmp, memmove, strlen, etc.
20// Future floating point idioms to recognize in -ffast-math mode:
21// fpowi
22// Future integer operation idioms to recognize:
23// ctpop, ctlz, cttz
24//
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.
28//
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
34//
35//===----------------------------------------------------------------------===//
Chris Lattnere6bb6492010-12-26 19:39:38 +000036
37#define DEBUG_TYPE "loop-idiom"
38#include "llvm/Transforms/Scalar.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000039#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000040#include "llvm/Analysis/LoopPass.h"
41#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000042#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000043#include "llvm/Analysis/ValueTracking.h"
44#include "llvm/Target/TargetData.h"
Chris Lattner9f391882010-12-27 00:03:23 +000045#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000046#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000047#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000048#include "llvm/Support/raw_ostream.h"
Chris Lattner4ce31fb2011-01-02 07:36:44 +000049#include "llvm/ADT/Statistic.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000050using namespace llvm;
51
52// TODO: Recognize "N" size array multiplies: replace with call to blas or
53// something.
Chris Lattner4ce31fb2011-01-02 07:36:44 +000054STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
55STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000056
57namespace {
58 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000059 Loop *CurLoop;
60 const TargetData *TD;
Chris Lattner62c50fd2011-01-02 19:01:03 +000061 DominatorTree *DT;
Chris Lattner22920b52010-12-26 20:45:45 +000062 ScalarEvolution *SE;
Chris Lattnere6bb6492010-12-26 19:39:38 +000063 public:
64 static char ID;
65 explicit LoopIdiomRecognize() : LoopPass(ID) {
66 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
67 }
68
69 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner62c50fd2011-01-02 19:01:03 +000070 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
71 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattnere6bb6492010-12-26 19:39:38 +000072
Chris Lattner22920b52010-12-26 20:45:45 +000073 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000074
Chris Lattnera92ff912010-12-26 23:42:51 +000075 bool processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
76 Value *SplatValue,
77 const SCEVAddRecExpr *Ev,
78 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +000079 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
80 const SCEVAddRecExpr *StoreEv,
81 const SCEVAddRecExpr *LoadEv,
82 const SCEV *BECount);
83
Chris Lattnere6bb6492010-12-26 19:39:38 +000084 /// This transformation requires natural loop information & requires that
85 /// loop preheaders be inserted into the CFG.
86 ///
87 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.addRequired<LoopInfo>();
89 AU.addPreserved<LoopInfo>();
90 AU.addRequiredID(LoopSimplifyID);
91 AU.addPreservedID(LoopSimplifyID);
92 AU.addRequiredID(LCSSAID);
93 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +000094 AU.addRequired<AliasAnalysis>();
95 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +000096 AU.addRequired<ScalarEvolution>();
97 AU.addPreserved<ScalarEvolution>();
98 AU.addPreserved<DominatorTree>();
Chris Lattner62c50fd2011-01-02 19:01:03 +000099 AU.addRequired<DominatorTree>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000100 }
101 };
102}
103
104char LoopIdiomRecognize::ID = 0;
105INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
106 false, false)
107INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chris Lattner62c50fd2011-01-02 19:01:03 +0000108INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000109INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
110INITIALIZE_PASS_DEPENDENCY(LCSSA)
111INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000112INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000113INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
114 false, false)
115
116Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
117
Chris Lattner9f391882010-12-27 00:03:23 +0000118/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
119/// and zero out all the operands of this instruction. If any of them become
120/// dead, delete them and the computation tree that feeds them.
121///
122static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
123 SmallVector<Instruction*, 32> NowDeadInsts;
124
125 NowDeadInsts.push_back(I);
126
127 // Before we touch this instruction, remove it from SE!
128 do {
129 Instruction *DeadInst = NowDeadInsts.pop_back_val();
130
131 // This instruction is dead, zap it, in stages. Start by removing it from
132 // SCEV.
133 SE.forgetValue(DeadInst);
134
135 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
136 Value *Op = DeadInst->getOperand(op);
137 DeadInst->setOperand(op, 0);
138
139 // If this operand just became dead, add it to the NowDeadInsts list.
140 if (!Op->use_empty()) continue;
141
142 if (Instruction *OpI = dyn_cast<Instruction>(Op))
143 if (isInstructionTriviallyDead(OpI))
144 NowDeadInsts.push_back(OpI);
145 }
146
147 DeadInst->eraseFromParent();
148
149 } while (!NowDeadInsts.empty());
150}
151
Chris Lattnere6bb6492010-12-26 19:39:38 +0000152bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000153 CurLoop = L;
154
Chris Lattner22920b52010-12-26 20:45:45 +0000155 // The trip count of the loop must be analyzable.
156 SE = &getAnalysis<ScalarEvolution>();
157 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
158 return false;
159 const SCEV *BECount = SE->getBackedgeTakenCount(L);
160 if (isa<SCEVCouldNotCompute>(BECount)) return false;
161
Chris Lattner8e08e732011-01-02 20:24:21 +0000162 // If this loop executes exactly one time, then it should be peeled, not
163 // optimized by this pass.
164 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
165 if (BECst->getValue()->getValue() == 0)
166 return false;
167
Chris Lattner22920b52010-12-26 20:45:45 +0000168 // We require target data for now.
169 TD = getAnalysisIfAvailable<TargetData>();
170 if (TD == 0) return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000171
Chris Lattner62c50fd2011-01-02 19:01:03 +0000172 DT = &getAnalysis<DominatorTree>();
173 LoopInfo &LI = getAnalysis<LoopInfo>();
174
175 SmallVector<BasicBlock*, 8> ExitBlocks;
176 CurLoop->getUniqueExitBlocks(ExitBlocks);
177
178 bool MadeChange = false;
179 // Scan all the blocks in the loop that are not in subloops.
180 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
181 ++BI) {
182 // Ignore blocks in subloops.
183 if (LI.getLoopFor(*BI) != CurLoop)
184 continue;
185
186 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
187 }
188 return MadeChange;
189}
190
191/// runOnLoopBlock - Process the specified block, which lives in a counted loop
192/// with the specified backedge count. This block is known to be in the current
193/// loop and not in any subloops.
194bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
195 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
196 // We can only promote stores in this block if they are unconditionally
197 // executed in the loop. For a block to be unconditionally executed, it has
198 // to dominate all the exit blocks of the loop. Verify this now.
199 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
200 if (!DT->dominates(BB, ExitBlocks[i]))
201 return false;
202
203 DEBUG(dbgs() << "loop-idiom Scanning: F[" << BB->getParent()->getName()
204 << "] Loop %" << BB->getName() << "\n");
205
Chris Lattner22920b52010-12-26 20:45:45 +0000206 bool MadeChange = false;
207 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
208 // Look for store instructions, which may be memsets.
Chris Lattnera92ff912010-12-26 23:42:51 +0000209 StoreInst *SI = dyn_cast<StoreInst>(I++);
210 if (SI == 0 || SI->isVolatile()) continue;
211
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000212 WeakVH InstPtr(SI);
213 if (!processLoopStore(SI, BECount)) continue;
214
215 MadeChange = true;
216
217 // If processing the store invalidated our iterator, start over from the
218 // head of the loop.
219 if (InstPtr == 0)
220 I = BB->begin();
Chris Lattner22920b52010-12-26 20:45:45 +0000221 }
222
223 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000224}
225
Chris Lattner62c50fd2011-01-02 19:01:03 +0000226
Chris Lattnere6bb6492010-12-26 19:39:38 +0000227/// scanBlock - Look over a block to see if we can promote anything out of it.
Chris Lattner22920b52010-12-26 20:45:45 +0000228bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
229 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000230 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000231
Chris Lattner95ae6762010-12-28 18:53:48 +0000232 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000233 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000234 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000235 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000236
Chris Lattner22920b52010-12-26 20:45:45 +0000237 // See if the pointer expression is an AddRec like {base,+,1} on the current
238 // loop, which indicates a strided store. If we have something else, it's a
239 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000240 const SCEVAddRecExpr *StoreEv =
241 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
242 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000243 return false;
244
245 // Check to see if the stride matches the size of the store. If so, then we
246 // know that every byte is touched in the loop.
247 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000248 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Chris Lattner30980b62011-01-01 19:39:01 +0000249
250 // TODO: Could also handle negative stride here someday, that will require the
251 // validity check in mayLoopModRefLocation to be updated though.
Chris Lattner22920b52010-12-26 20:45:45 +0000252 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
253 return false;
254
Chris Lattner22920b52010-12-26 20:45:45 +0000255 // If the stored value is a byte-wise value (like i32 -1), then it may be
256 // turned into a memset of i8 -1, assuming that all the consequtive bytes
257 // are stored. A store of i32 0x01020304 can never be turned into a memset.
Chris Lattnera92ff912010-12-26 23:42:51 +0000258 if (Value *SplatValue = isBytewiseValue(StoredVal))
Chris Lattnere2c43922011-01-02 03:37:56 +0000259 if (processLoopStoreOfSplatValue(SI, StoreSize, SplatValue, StoreEv,
260 BECount))
261 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000262
Chris Lattnere2c43922011-01-02 03:37:56 +0000263 // If the stored value is a strided load in the same loop with the same stride
264 // this this may be transformable into a memcpy. This kicks in for stuff like
265 // for (i) A[i] = B[i];
266 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
267 const SCEVAddRecExpr *LoadEv =
268 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
269 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
270 StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
271 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
272 return true;
273 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000274 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000275
Chris Lattnere6bb6492010-12-26 19:39:38 +0000276 return false;
277}
278
Chris Lattner30980b62011-01-01 19:39:01 +0000279/// mayLoopModRefLocation - Return true if the specified loop might do a load or
280/// store to the same location that the specified store could store to, which is
281/// a loop-strided access.
Chris Lattnere2c43922011-01-02 03:37:56 +0000282static bool mayLoopModRefLocation(Value *Ptr, Loop *L, const SCEV *BECount,
283 unsigned StoreSize, AliasAnalysis &AA,
284 StoreInst *IgnoredStore) {
Chris Lattner30980b62011-01-01 19:39:01 +0000285 // Get the location that may be stored across the loop. Since the access is
286 // strided positively through memory, we say that the modified location starts
287 // at the pointer and has infinite size.
Chris Lattnera64cbf02011-01-01 19:54:22 +0000288 uint64_t AccessSize = AliasAnalysis::UnknownSize;
289
290 // If the loop iterates a fixed number of times, we can refine the access size
291 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
292 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
293 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
294
295 // TODO: For this to be really effective, we have to dive into the pointer
296 // operand in the store. Store to &A[i] of 100 will always return may alias
297 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
298 // which will then no-alias a store to &A[100].
Chris Lattnere2c43922011-01-02 03:37:56 +0000299 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
Chris Lattner30980b62011-01-01 19:39:01 +0000300
301 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
302 ++BI)
303 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chris Lattnere2c43922011-01-02 03:37:56 +0000304 if (&*I != IgnoredStore &&
305 AA.getModRefInfo(I, StoreLoc) != AliasAnalysis::NoModRef)
Chris Lattner30980b62011-01-01 19:39:01 +0000306 return true;
307
308 return false;
309}
310
Chris Lattnera92ff912010-12-26 23:42:51 +0000311/// processLoopStoreOfSplatValue - We see a strided store of a memsetable value.
312/// If we can transform this into a memset in the loop preheader, do so.
313bool LoopIdiomRecognize::
314processLoopStoreOfSplatValue(StoreInst *SI, unsigned StoreSize,
315 Value *SplatValue,
316 const SCEVAddRecExpr *Ev, const SCEV *BECount) {
Chris Lattnerbafa1172011-01-01 20:12:04 +0000317 // Verify that the stored value is loop invariant. If not, we can't promote
318 // the memset.
319 if (!CurLoop->isLoopInvariant(SplatValue))
320 return false;
321
Chris Lattnera92ff912010-12-26 23:42:51 +0000322 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
323 // this into a memset in the loop preheader now if we want. However, this
324 // would be unsafe to do if there is anything else in the loop that may read
325 // or write to the aliased location. Check for an alias.
Chris Lattnere2c43922011-01-02 03:37:56 +0000326 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
327 StoreSize, getAnalysis<AliasAnalysis>(), SI))
328 return false;
Chris Lattnera92ff912010-12-26 23:42:51 +0000329
330 // Okay, everything looks good, insert the memset.
331 BasicBlock *Preheader = CurLoop->getLoopPreheader();
332
333 IRBuilder<> Builder(Preheader->getTerminator());
334
335 // The trip count of the loop and the base pointer of the addrec SCEV is
336 // guaranteed to be loop invariant, which means that it should dominate the
337 // header. Just insert code for it in the preheader.
338 SCEVExpander Expander(*SE);
339
340 unsigned AddrSpace = SI->getPointerAddressSpace();
341 Value *BasePtr =
342 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
343 Preheader->getTerminator());
344
345 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
346 // pointer size if it isn't already.
347 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
348 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
349 if (BESize < TD->getPointerSizeInBits())
350 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
351 else if (BESize > TD->getPointerSizeInBits())
352 BECount = SE->getTruncateExpr(BECount, IntPtr);
353
354 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
355 true, true /*nooverflow*/);
356 if (StoreSize != 1)
357 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
358 true, true /*nooverflow*/);
359
360 Value *NumBytes =
361 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
362
363 Value *NewCall =
364 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, SI->getAlignment());
365
366 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
367 << " from store to: " << *Ev << " at: " << *SI << "\n");
Duncan Sands7922d342010-12-28 09:41:15 +0000368 (void)NewCall;
Chris Lattnera92ff912010-12-26 23:42:51 +0000369
Chris Lattner9f391882010-12-27 00:03:23 +0000370 // Okay, the memset has been formed. Zap the original store and anything that
371 // feeds into it.
372 DeleteDeadInstruction(SI, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000373 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +0000374 return true;
375}
376
Chris Lattnere2c43922011-01-02 03:37:56 +0000377/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
378/// same-strided load.
379bool LoopIdiomRecognize::
380processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
381 const SCEVAddRecExpr *StoreEv,
382 const SCEVAddRecExpr *LoadEv,
383 const SCEV *BECount) {
384 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
385
386 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chris Lattnerbdce5722011-01-02 18:32:09 +0000387 // this into a memcpy in the loop preheader now if we want. However, this
Chris Lattnere2c43922011-01-02 03:37:56 +0000388 // would be unsafe to do if there is anything else in the loop that may read
389 // or write to the aliased location (including the load feeding the stores).
390 // Check for an alias.
391 if (mayLoopModRefLocation(SI->getPointerOperand(), CurLoop, BECount,
392 StoreSize, getAnalysis<AliasAnalysis>(), SI))
393 return false;
394
395 // Okay, everything looks good, insert the memcpy.
396 BasicBlock *Preheader = CurLoop->getLoopPreheader();
397
398 IRBuilder<> Builder(Preheader->getTerminator());
399
400 // The trip count of the loop and the base pointer of the addrec SCEV is
401 // guaranteed to be loop invariant, which means that it should dominate the
402 // header. Just insert code for it in the preheader.
403 SCEVExpander Expander(*SE);
404
405 Value *LoadBasePtr =
406 Expander.expandCodeFor(LoadEv->getStart(),
407 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
408 Preheader->getTerminator());
409 Value *StoreBasePtr =
410 Expander.expandCodeFor(StoreEv->getStart(),
411 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
412 Preheader->getTerminator());
413
414 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
415 // pointer size if it isn't already.
416 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
417 unsigned BESize = SE->getTypeSizeInBits(BECount->getType());
418 if (BESize < TD->getPointerSizeInBits())
419 BECount = SE->getZeroExtendExpr(BECount, IntPtr);
420 else if (BESize > TD->getPointerSizeInBits())
421 BECount = SE->getTruncateExpr(BECount, IntPtr);
422
423 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
424 true, true /*nooverflow*/);
425 if (StoreSize != 1)
426 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
427 true, true /*nooverflow*/);
428
429 Value *NumBytes =
430 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
431
432 Value *NewCall =
433 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
434 std::min(SI->getAlignment(), LI->getAlignment()));
435
436 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
437 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
438 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
439 (void)NewCall;
440
441 // Okay, the memset has been formed. Zap the original store and anything that
442 // feeds into it.
443 DeleteDeadInstruction(SI, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000444 ++NumMemCpy;
Chris Lattnere2c43922011-01-02 03:37:56 +0000445 return true;
446}