blob: be3ff9258fc15ab83ed150ccd147c179601ae30c [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; }
Chris Lattner91139cc2011-01-02 23:19:45 +000033//
Chris Lattnerd957c712011-01-03 01:10:08 +000034// This could recognize common matrix multiplies and dot product idioms and
Chris Lattner91139cc2011-01-02 23:19:45 +000035// replace them with calls to BLAS (if linked in??).
36//
Chris Lattnerbdce5722011-01-02 18:32:09 +000037//===----------------------------------------------------------------------===//
Chris Lattnere6bb6492010-12-26 19:39:38 +000038
39#define DEBUG_TYPE "loop-idiom"
40#include "llvm/Transforms/Scalar.h"
Chris Lattnere41d3c02011-01-04 07:46:33 +000041#include "llvm/IntrinsicInst.h"
Chris Lattner3a393722011-02-19 19:31:39 +000042#include "llvm/Module.h"
Chris Lattner2e12f1a2010-12-27 18:39:08 +000043#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000044#include "llvm/Analysis/LoopPass.h"
45#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000046#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chris Lattner22920b52010-12-26 20:45:45 +000047#include "llvm/Analysis/ValueTracking.h"
48#include "llvm/Target/TargetData.h"
Chris Lattnerc19175c2011-02-18 22:22:15 +000049#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner9f391882010-12-27 00:03:23 +000050#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000051#include "llvm/Support/Debug.h"
Chris Lattnera92ff912010-12-26 23:42:51 +000052#include "llvm/Support/IRBuilder.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000053#include "llvm/Support/raw_ostream.h"
Chris Lattner4ce31fb2011-01-02 07:36:44 +000054#include "llvm/ADT/Statistic.h"
Chris Lattnere6bb6492010-12-26 19:39:38 +000055using namespace llvm;
56
Chris Lattner4ce31fb2011-01-02 07:36:44 +000057STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
58STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
Chris Lattnere6bb6492010-12-26 19:39:38 +000059
60namespace {
61 class LoopIdiomRecognize : public LoopPass {
Chris Lattner22920b52010-12-26 20:45:45 +000062 Loop *CurLoop;
63 const TargetData *TD;
Chris Lattner62c50fd2011-01-02 19:01:03 +000064 DominatorTree *DT;
Chris Lattner22920b52010-12-26 20:45:45 +000065 ScalarEvolution *SE;
Chris Lattnerc19175c2011-02-18 22:22:15 +000066 TargetLibraryInfo *TLI;
Chris Lattnere6bb6492010-12-26 19:39:38 +000067 public:
68 static char ID;
69 explicit LoopIdiomRecognize() : LoopPass(ID) {
70 initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
71 }
72
73 bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner62c50fd2011-01-02 19:01:03 +000074 bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
75 SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattnere6bb6492010-12-26 19:39:38 +000076
Chris Lattner22920b52010-12-26 20:45:45 +000077 bool processLoopStore(StoreInst *SI, const SCEV *BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +000078 bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
Chris Lattnere6bb6492010-12-26 19:39:38 +000079
Chris Lattner3a393722011-02-19 19:31:39 +000080 bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
81 unsigned StoreAlignment,
82 Value *SplatValue, Instruction *TheStore,
83 const SCEVAddRecExpr *Ev,
84 const SCEV *BECount);
Chris Lattnere2c43922011-01-02 03:37:56 +000085 bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
86 const SCEVAddRecExpr *StoreEv,
87 const SCEVAddRecExpr *LoadEv,
88 const SCEV *BECount);
89
Chris Lattnere6bb6492010-12-26 19:39:38 +000090 /// This transformation requires natural loop information & requires that
91 /// loop preheaders be inserted into the CFG.
92 ///
93 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94 AU.addRequired<LoopInfo>();
95 AU.addPreserved<LoopInfo>();
96 AU.addRequiredID(LoopSimplifyID);
97 AU.addPreservedID(LoopSimplifyID);
98 AU.addRequiredID(LCSSAID);
99 AU.addPreservedID(LCSSAID);
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000100 AU.addRequired<AliasAnalysis>();
101 AU.addPreserved<AliasAnalysis>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000102 AU.addRequired<ScalarEvolution>();
103 AU.addPreserved<ScalarEvolution>();
104 AU.addPreserved<DominatorTree>();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000105 AU.addRequired<DominatorTree>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000106 AU.addRequired<TargetLibraryInfo>();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000107 }
108 };
109}
110
111char LoopIdiomRecognize::ID = 0;
112INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
113 false, false)
114INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chris Lattner62c50fd2011-01-02 19:01:03 +0000115INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000116INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
117INITIALIZE_PASS_DEPENDENCY(LCSSA)
118INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chris Lattnerc19175c2011-02-18 22:22:15 +0000119INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000120INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Chris Lattnere6bb6492010-12-26 19:39:38 +0000121INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
122 false, false)
123
124Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
125
Chris Lattner9f391882010-12-27 00:03:23 +0000126/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
127/// and zero out all the operands of this instruction. If any of them become
128/// dead, delete them and the computation tree that feeds them.
129///
130static void DeleteDeadInstruction(Instruction *I, ScalarEvolution &SE) {
131 SmallVector<Instruction*, 32> NowDeadInsts;
132
133 NowDeadInsts.push_back(I);
134
135 // Before we touch this instruction, remove it from SE!
136 do {
137 Instruction *DeadInst = NowDeadInsts.pop_back_val();
138
139 // This instruction is dead, zap it, in stages. Start by removing it from
140 // SCEV.
141 SE.forgetValue(DeadInst);
142
143 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
144 Value *Op = DeadInst->getOperand(op);
145 DeadInst->setOperand(op, 0);
146
147 // If this operand just became dead, add it to the NowDeadInsts list.
148 if (!Op->use_empty()) continue;
149
150 if (Instruction *OpI = dyn_cast<Instruction>(Op))
151 if (isInstructionTriviallyDead(OpI))
152 NowDeadInsts.push_back(OpI);
153 }
154
155 DeadInst->eraseFromParent();
156
157 } while (!NowDeadInsts.empty());
158}
159
Chris Lattnere6bb6492010-12-26 19:39:38 +0000160bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner22920b52010-12-26 20:45:45 +0000161 CurLoop = L;
162
Chris Lattner22920b52010-12-26 20:45:45 +0000163 // The trip count of the loop must be analyzable.
164 SE = &getAnalysis<ScalarEvolution>();
165 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
166 return false;
167 const SCEV *BECount = SE->getBackedgeTakenCount(L);
168 if (isa<SCEVCouldNotCompute>(BECount)) return false;
169
Chris Lattner8e08e732011-01-02 20:24:21 +0000170 // If this loop executes exactly one time, then it should be peeled, not
171 // optimized by this pass.
172 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
173 if (BECst->getValue()->getValue() == 0)
174 return false;
175
Chris Lattner22920b52010-12-26 20:45:45 +0000176 // We require target data for now.
177 TD = getAnalysisIfAvailable<TargetData>();
178 if (TD == 0) return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000179
Chris Lattner62c50fd2011-01-02 19:01:03 +0000180 DT = &getAnalysis<DominatorTree>();
181 LoopInfo &LI = getAnalysis<LoopInfo>();
Chris Lattnerc19175c2011-02-18 22:22:15 +0000182 TLI = &getAnalysis<TargetLibraryInfo>();
Chris Lattner62c50fd2011-01-02 19:01:03 +0000183
184 SmallVector<BasicBlock*, 8> ExitBlocks;
185 CurLoop->getUniqueExitBlocks(ExitBlocks);
186
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000187 DEBUG(dbgs() << "loop-idiom Scanning: F["
188 << L->getHeader()->getParent()->getName()
189 << "] Loop %" << L->getHeader()->getName() << "\n");
190
Chris Lattner62c50fd2011-01-02 19:01:03 +0000191 bool MadeChange = false;
192 // Scan all the blocks in the loop that are not in subloops.
193 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
194 ++BI) {
195 // Ignore blocks in subloops.
196 if (LI.getLoopFor(*BI) != CurLoop)
197 continue;
198
199 MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
200 }
201 return MadeChange;
202}
203
204/// runOnLoopBlock - Process the specified block, which lives in a counted loop
205/// with the specified backedge count. This block is known to be in the current
206/// loop and not in any subloops.
207bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
208 SmallVectorImpl<BasicBlock*> &ExitBlocks) {
209 // We can only promote stores in this block if they are unconditionally
210 // executed in the loop. For a block to be unconditionally executed, it has
211 // to dominate all the exit blocks of the loop. Verify this now.
212 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
213 if (!DT->dominates(BB, ExitBlocks[i]))
214 return false;
215
Chris Lattner22920b52010-12-26 20:45:45 +0000216 bool MadeChange = false;
217 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000218 Instruction *Inst = I++;
219 // Look for store instructions, which may be optimized to memset/memcpy.
220 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000221 WeakVH InstPtr(I);
222 if (!processLoopStore(SI, BECount)) continue;
223 MadeChange = true;
224
225 // If processing the store invalidated our iterator, start over from the
Chris Lattnere41d3c02011-01-04 07:46:33 +0000226 // top of the block.
Chris Lattnerb7e9ef02011-01-04 07:27:30 +0000227 if (InstPtr == 0)
228 I = BB->begin();
229 continue;
230 }
Chris Lattner2e12f1a2010-12-27 18:39:08 +0000231
Chris Lattnere41d3c02011-01-04 07:46:33 +0000232 // Look for memset instructions, which may be optimized to a larger memset.
233 if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
234 WeakVH InstPtr(I);
235 if (!processLoopMemSet(MSI, BECount)) continue;
236 MadeChange = true;
237
238 // If processing the memset invalidated our iterator, start over from the
239 // top of the block.
240 if (InstPtr == 0)
241 I = BB->begin();
242 continue;
243 }
Chris Lattner22920b52010-12-26 20:45:45 +0000244 }
245
246 return MadeChange;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000247}
248
Chris Lattner62c50fd2011-01-02 19:01:03 +0000249
Chris Lattnere41d3c02011-01-04 07:46:33 +0000250/// processLoopStore - See if this store can be promoted to a memset or memcpy.
Chris Lattner22920b52010-12-26 20:45:45 +0000251bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Chris Lattnere41d3c02011-01-04 07:46:33 +0000252 if (SI->isVolatile()) return false;
253
Chris Lattner22920b52010-12-26 20:45:45 +0000254 Value *StoredVal = SI->getValueOperand();
Chris Lattnera92ff912010-12-26 23:42:51 +0000255 Value *StorePtr = SI->getPointerOperand();
Chris Lattnere6bb6492010-12-26 19:39:38 +0000256
Chris Lattner95ae6762010-12-28 18:53:48 +0000257 // Reject stores that are so large that they overflow an unsigned.
Chris Lattner22920b52010-12-26 20:45:45 +0000258 uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
Chris Lattner95ae6762010-12-28 18:53:48 +0000259 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
Chris Lattner22920b52010-12-26 20:45:45 +0000260 return false;
Chris Lattnere6bb6492010-12-26 19:39:38 +0000261
Chris Lattner22920b52010-12-26 20:45:45 +0000262 // See if the pointer expression is an AddRec like {base,+,1} on the current
263 // loop, which indicates a strided store. If we have something else, it's a
264 // random store we can't handle.
Chris Lattnere2c43922011-01-02 03:37:56 +0000265 const SCEVAddRecExpr *StoreEv =
266 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
267 if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
Chris Lattner22920b52010-12-26 20:45:45 +0000268 return false;
269
270 // Check to see if the stride matches the size of the store. If so, then we
271 // know that every byte is touched in the loop.
272 unsigned StoreSize = (unsigned)SizeInBits >> 3;
Chris Lattnere2c43922011-01-02 03:37:56 +0000273 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
Chris Lattner30980b62011-01-01 19:39:01 +0000274
275 // TODO: Could also handle negative stride here someday, that will require the
Owen Anderson6f96b272011-01-03 23:51:56 +0000276 // validity check in mayLoopAccessLocation to be updated though.
Chris Lattner22920b52010-12-26 20:45:45 +0000277 if (Stride == 0 || StoreSize != Stride->getValue()->getValue())
278 return false;
Chris Lattner3a393722011-02-19 19:31:39 +0000279
280 // See if we can optimize just this store in isolation.
281 if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
282 StoredVal, SI, StoreEv, BECount))
283 return true;
Chris Lattnera92ff912010-12-26 23:42:51 +0000284
Chris Lattnere2c43922011-01-02 03:37:56 +0000285 // If the stored value is a strided load in the same loop with the same stride
286 // this this may be transformable into a memcpy. This kicks in for stuff like
287 // for (i) A[i] = B[i];
288 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
289 const SCEVAddRecExpr *LoadEv =
290 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
291 if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
292 StoreEv->getOperand(1) == LoadEv->getOperand(1) && !LI->isVolatile())
293 if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
294 return true;
295 }
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000296 //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
Chris Lattner22920b52010-12-26 20:45:45 +0000297
Chris Lattnere6bb6492010-12-26 19:39:38 +0000298 return false;
299}
300
Chris Lattnere41d3c02011-01-04 07:46:33 +0000301/// processLoopMemSet - See if this memset can be promoted to a large memset.
302bool LoopIdiomRecognize::
303processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
304 // We can only handle non-volatile memsets with a constant size.
305 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
306
Chris Lattnerc19175c2011-02-18 22:22:15 +0000307 // If we're not allowed to hack on memset, we fail.
308 if (!TLI->has(LibFunc::memset))
309 return false;
310
Chris Lattnere41d3c02011-01-04 07:46:33 +0000311 Value *Pointer = MSI->getDest();
312
313 // See if the pointer expression is an AddRec like {base,+,1} on the current
314 // loop, which indicates a strided store. If we have something else, it's a
315 // random store we can't handle.
316 const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
317 if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
318 return false;
319
320 // Reject memsets that are so large that they overflow an unsigned.
321 uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
322 if ((SizeInBytes >> 32) != 0)
323 return false;
324
325 // Check to see if the stride matches the size of the memset. If so, then we
326 // know that every byte is touched in the loop.
327 const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
328
329 // TODO: Could also handle negative stride here someday, that will require the
330 // validity check in mayLoopAccessLocation to be updated though.
331 if (Stride == 0 || MSI->getLength() != Stride->getValue())
332 return false;
333
Chris Lattner3a393722011-02-19 19:31:39 +0000334 return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
335 MSI->getAlignment(), MSI->getValue(),
336 MSI, Ev, BECount);
Chris Lattnere41d3c02011-01-04 07:46:33 +0000337}
338
339
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000340/// mayLoopAccessLocation - Return true if the specified loop might access the
341/// specified pointer location, which is a loop-strided access. The 'Access'
342/// argument specifies what the verboten forms of access are (read or write).
343static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
344 Loop *L, const SCEV *BECount,
Chris Lattnere2c43922011-01-02 03:37:56 +0000345 unsigned StoreSize, AliasAnalysis &AA,
Chris Lattnere41d3c02011-01-04 07:46:33 +0000346 Instruction *IgnoredStore) {
Chris Lattner30980b62011-01-01 19:39:01 +0000347 // Get the location that may be stored across the loop. Since the access is
348 // strided positively through memory, we say that the modified location starts
349 // at the pointer and has infinite size.
Chris Lattnera64cbf02011-01-01 19:54:22 +0000350 uint64_t AccessSize = AliasAnalysis::UnknownSize;
351
352 // If the loop iterates a fixed number of times, we can refine the access size
353 // to be exactly the size of the memset, which is (BECount+1)*StoreSize
354 if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
355 AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
356
357 // TODO: For this to be really effective, we have to dive into the pointer
358 // operand in the store. Store to &A[i] of 100 will always return may alias
359 // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
360 // which will then no-alias a store to &A[100].
Chris Lattnere2c43922011-01-02 03:37:56 +0000361 AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
Chris Lattner30980b62011-01-01 19:39:01 +0000362
363 for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
364 ++BI)
365 for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
Chris Lattnere2c43922011-01-02 03:37:56 +0000366 if (&*I != IgnoredStore &&
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000367 (AA.getModRefInfo(I, StoreLoc) & Access))
Chris Lattner30980b62011-01-01 19:39:01 +0000368 return true;
369
370 return false;
371}
372
Chris Lattner3a393722011-02-19 19:31:39 +0000373/// getMemSetPatternValue - If a strided store of the specified value is safe to
374/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
375/// be passed in. Otherwise, return null.
376///
377/// Note that we don't ever attempt to use memset_pattern8 or 4, because these
378/// just replicate their input array and then pass on to memset_pattern16.
379static Constant *getMemSetPatternValue(Value *V, const TargetData &TD) {
380 // If the value isn't a constant, we can't promote it to being in a constant
381 // array. We could theoretically do a store to an alloca or something, but
382 // that doesn't seem worthwhile.
383 Constant *C = dyn_cast<Constant>(V);
384 if (C == 0) return 0;
Chris Lattnerc19175c2011-02-18 22:22:15 +0000385
Chris Lattner3a393722011-02-19 19:31:39 +0000386 // Only handle simple values that are a power of two bytes in size.
387 uint64_t Size = TD.getTypeSizeInBits(V->getType());
388 if (Size == 0 || (Size & 7) || (Size & (Size-1)))
389 return 0;
390
391 // Convert the constant to an integer type of the appropriate size so we can
392 // start hacking on it.
393 if (isa<PointerType>(V->getType()))
394 C = ConstantExpr::getPtrToInt(C, IntegerType::get(C->getContext(), Size));
395 else if (isa<VectorType>(V->getType()) || V->getType()->isFloatingPointTy())
396 C = ConstantExpr::getBitCast(C, IntegerType::get(C->getContext(), Size));
397 else if (!isa<IntegerType>(V->getType()))
398 return 0; // Unhandled type.
399
400 // Convert to size in bytes.
401 Size /= 8;
402
403 // If we couldn't fold this to an integer, we fail. We don't bother to handle
404 // relocatable expressions like the address of a global yet.
405 // FIXME!
406 ConstantInt *CI = dyn_cast<ConstantInt>(C);
407 if (CI == 0) return 0;
408
409 APInt CVal = CI->getValue();
410
411 // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
412 // if the top and bottom are the same.
413 if (Size > 16) return 0;
414
415 // If this is a big endian target (PPC) then we need to bswap.
416 if (TD.isBigEndian())
417 CVal = CVal.byteSwap();
418
419 // Determine what each byte of the pattern value should be.
420 char Value[16];
421 for (unsigned i = 0; i != 16; ++i) {
422 // Get the byte value we're indexing into.
423 unsigned CByte = i % Size;
424 Value[i] = (unsigned char)(CVal.getZExtValue() >> CByte);
425 }
426
427 return ConstantArray::get(V->getContext(), StringRef(Value, 16), false);
428}
429
430
431/// processLoopStridedStore - We see a strided store of some value. If we can
432/// transform this into a memset or memset_pattern in the loop preheader, do so.
433bool LoopIdiomRecognize::
434processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
435 unsigned StoreAlignment, Value *StoredVal,
436 Instruction *TheStore, const SCEVAddRecExpr *Ev,
437 const SCEV *BECount) {
438
439 // If the stored value is a byte-wise value (like i32 -1), then it may be
440 // turned into a memset of i8 -1, assuming that all the consecutive bytes
441 // are stored. A store of i32 0x01020304 can never be turned into a memset,
442 // but it can be turned into memset_pattern if the target supports it.
443 Value *SplatValue = isBytewiseValue(StoredVal);
444 Constant *PatternValue = 0;
445
446 // If we're allowed to form a memset, and the stored value would be acceptable
447 // for memset, use it.
448 if (SplatValue && TLI->has(LibFunc::memset) &&
449 // Verify that the stored value is loop invariant. If not, we can't
450 // promote the memset.
451 CurLoop->isLoopInvariant(SplatValue)) {
452 // Keep and use SplatValue.
453 PatternValue = 0;
454 } else if (TLI->has(LibFunc::memset_pattern16) &&
455 (PatternValue = getMemSetPatternValue(StoredVal, *TD))) {
456 // It looks like we can use PatternValue!
457 SplatValue = 0;
458 } else {
459 // Otherwise, this isn't an idiom we can transform. For example, we can't
460 // do anything with a 3-byte store, for example.
Chris Lattnerbafa1172011-01-01 20:12:04 +0000461 return false;
Chris Lattner3a393722011-02-19 19:31:39 +0000462 }
463
Chris Lattnerbafa1172011-01-01 20:12:04 +0000464
Chris Lattnera92ff912010-12-26 23:42:51 +0000465 // Okay, we have a strided store "p[i]" of a splattable value. We can turn
466 // this into a memset in the loop preheader now if we want. However, this
467 // would be unsafe to do if there is anything else in the loop that may read
468 // or write to the aliased location. Check for an alias.
Chris Lattnere41d3c02011-01-04 07:46:33 +0000469 if (mayLoopAccessLocation(DestPtr, AliasAnalysis::ModRef,
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000470 CurLoop, BECount,
Chris Lattnere41d3c02011-01-04 07:46:33 +0000471 StoreSize, getAnalysis<AliasAnalysis>(), TheStore))
Chris Lattnere2c43922011-01-02 03:37:56 +0000472 return false;
Chris Lattnera92ff912010-12-26 23:42:51 +0000473
474 // Okay, everything looks good, insert the memset.
475 BasicBlock *Preheader = CurLoop->getLoopPreheader();
476
477 IRBuilder<> Builder(Preheader->getTerminator());
478
479 // The trip count of the loop and the base pointer of the addrec SCEV is
480 // guaranteed to be loop invariant, which means that it should dominate the
481 // header. Just insert code for it in the preheader.
482 SCEVExpander Expander(*SE);
483
Chris Lattnere41d3c02011-01-04 07:46:33 +0000484 unsigned AddrSpace = cast<PointerType>(DestPtr->getType())->getAddressSpace();
Chris Lattnera92ff912010-12-26 23:42:51 +0000485 Value *BasePtr =
486 Expander.expandCodeFor(Ev->getStart(), Builder.getInt8PtrTy(AddrSpace),
487 Preheader->getTerminator());
488
489 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
490 // pointer size if it isn't already.
Chris Lattner3a393722011-02-19 19:31:39 +0000491 const Type *IntPtr = TD->getIntPtrType(DestPtr->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000492 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Chris Lattnera92ff912010-12-26 23:42:51 +0000493
494 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Chris Lattner7c90b902011-01-04 00:06:55 +0000495 true /*no unsigned overflow*/);
Chris Lattnera92ff912010-12-26 23:42:51 +0000496 if (StoreSize != 1)
497 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Chris Lattner7c90b902011-01-04 00:06:55 +0000498 true /*no unsigned overflow*/);
Chris Lattnera92ff912010-12-26 23:42:51 +0000499
500 Value *NumBytes =
501 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
502
Chris Lattner3a393722011-02-19 19:31:39 +0000503 Value *NewCall;
504 if (SplatValue)
505 NewCall = Builder.CreateMemSet(BasePtr, SplatValue,NumBytes,StoreAlignment);
506 else {
507 Module *M = TheStore->getParent()->getParent()->getParent();
508 Value *MSP = M->getOrInsertFunction("memset_pattern16",
509 Builder.getVoidTy(),
510 Builder.getInt8PtrTy(),
511 Builder.getInt8PtrTy(), IntPtr,
512 (void*)0);
513
514 // Otherwise we should form a memset_pattern16. PatternValue is known to be
515 // an constant array of 16-bytes. Plop the value into a mergable global.
516 GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
517 GlobalValue::InternalLinkage,
518 PatternValue, ".memset_pattern");
519 GV->setUnnamedAddr(true); // Ok to merge these.
520 GV->setAlignment(16);
521 Value *PatternPtr = Builder.CreateConstInBoundsGEP2_32(GV, 0, 0, "pattern");
522
523 NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
524 }
Chris Lattnera92ff912010-12-26 23:42:51 +0000525
526 DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"
Chris Lattnere41d3c02011-01-04 07:46:33 +0000527 << " from store to: " << *Ev << " at: " << *TheStore << "\n");
Duncan Sands7922d342010-12-28 09:41:15 +0000528 (void)NewCall;
Chris Lattnera92ff912010-12-26 23:42:51 +0000529
Chris Lattner9f391882010-12-27 00:03:23 +0000530 // Okay, the memset has been formed. Zap the original store and anything that
531 // feeds into it.
Chris Lattnere41d3c02011-01-04 07:46:33 +0000532 DeleteDeadInstruction(TheStore, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000533 ++NumMemSet;
Chris Lattnera92ff912010-12-26 23:42:51 +0000534 return true;
535}
536
Chris Lattnere2c43922011-01-02 03:37:56 +0000537/// processLoopStoreOfLoopLoad - We see a strided store whose value is a
538/// same-strided load.
539bool LoopIdiomRecognize::
540processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
541 const SCEVAddRecExpr *StoreEv,
542 const SCEVAddRecExpr *LoadEv,
543 const SCEV *BECount) {
Chris Lattnerc19175c2011-02-18 22:22:15 +0000544 // If we're not allowed to form memcpy, we fail.
545 if (!TLI->has(LibFunc::memcpy))
546 return false;
547
Chris Lattnere2c43922011-01-02 03:37:56 +0000548 LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
549
550 // Okay, we have a strided store "p[i]" of a loaded value. We can turn
Chris Lattnerbdce5722011-01-02 18:32:09 +0000551 // this into a memcpy in the loop preheader now if we want. However, this
Chris Lattnere2c43922011-01-02 03:37:56 +0000552 // would be unsafe to do if there is anything else in the loop that may read
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000553 // or write to the stored location (including the load feeding the stores).
Chris Lattnere2c43922011-01-02 03:37:56 +0000554 // Check for an alias.
Chris Lattner63f9c3c2011-01-02 21:14:18 +0000555 if (mayLoopAccessLocation(SI->getPointerOperand(), AliasAnalysis::ModRef,
556 CurLoop, BECount, StoreSize,
557 getAnalysis<AliasAnalysis>(), SI))
558 return false;
559
560 // For a memcpy, we have to make sure that the input array is not being
561 // mutated by the loop.
562 if (mayLoopAccessLocation(LI->getPointerOperand(), AliasAnalysis::Mod,
563 CurLoop, BECount, StoreSize,
564 getAnalysis<AliasAnalysis>(), SI))
Chris Lattnere2c43922011-01-02 03:37:56 +0000565 return false;
566
567 // Okay, everything looks good, insert the memcpy.
568 BasicBlock *Preheader = CurLoop->getLoopPreheader();
569
570 IRBuilder<> Builder(Preheader->getTerminator());
571
572 // The trip count of the loop and the base pointer of the addrec SCEV is
573 // guaranteed to be loop invariant, which means that it should dominate the
574 // header. Just insert code for it in the preheader.
575 SCEVExpander Expander(*SE);
576
577 Value *LoadBasePtr =
578 Expander.expandCodeFor(LoadEv->getStart(),
579 Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
580 Preheader->getTerminator());
581 Value *StoreBasePtr =
582 Expander.expandCodeFor(StoreEv->getStart(),
583 Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
584 Preheader->getTerminator());
585
586 // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
587 // pointer size if it isn't already.
588 const Type *IntPtr = TD->getIntPtrType(SI->getContext());
Chris Lattner7c90b902011-01-04 00:06:55 +0000589 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
Chris Lattnere2c43922011-01-02 03:37:56 +0000590
591 const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
Chris Lattner7c90b902011-01-04 00:06:55 +0000592 true /*no unsigned overflow*/);
Chris Lattnere2c43922011-01-02 03:37:56 +0000593 if (StoreSize != 1)
594 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
Chris Lattner7c90b902011-01-04 00:06:55 +0000595 true /*no unsigned overflow*/);
Chris Lattnere2c43922011-01-02 03:37:56 +0000596
597 Value *NumBytes =
598 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
599
600 Value *NewCall =
601 Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
602 std::min(SI->getAlignment(), LI->getAlignment()));
603
604 DEBUG(dbgs() << " Formed memcpy: " << *NewCall << "\n"
605 << " from load ptr=" << *LoadEv << " at: " << *LI << "\n"
606 << " from store ptr=" << *StoreEv << " at: " << *SI << "\n");
607 (void)NewCall;
608
609 // Okay, the memset has been formed. Zap the original store and anything that
610 // feeds into it.
611 DeleteDeadInstruction(SI, *SE);
Chris Lattner4ce31fb2011-01-02 07:36:44 +0000612 ++NumMemCpy;
Chris Lattnere2c43922011-01-02 03:37:56 +0000613 return true;
614}