Disable most IR-level transform passes on functions marked 'optnone'.
[oota-llvm.git] / lib / Transforms / Scalar / LoopIdiomRecognize.cpp
1 //===-- 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 // 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 //
34 // We should enhance this to handle negative strides through memory.
35 // Alternatively (and perhaps better) we could rely on an earlier pass to force
36 // forward iteration through memory, which is generally better for cache
37 // behavior.  Negative strides *do* happen for memset/memcpy loops.
38 //
39 // This could recognize common matrix multiplies and dot product idioms and
40 // replace them with calls to BLAS (if linked in??).
41 //
42 //===----------------------------------------------------------------------===//
43
44 #define DEBUG_TYPE "loop-idiom"
45 #include "llvm/Transforms/Scalar.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Analysis/AliasAnalysis.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Analysis/ScalarEvolutionExpander.h"
50 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
51 #include "llvm/Analysis/TargetTransformInfo.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/Dominators.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/IntrinsicInst.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Target/TargetLibraryInfo.h"
61 #include "llvm/Transforms/Utils/Local.h"
62 using namespace llvm;
63
64 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
65 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
66
67 namespace {
68
69   class LoopIdiomRecognize;
70
71   /// This class defines some utility functions for loop idiom recognization.
72   class LIRUtil {
73   public:
74     /// Return true iff the block contains nothing but an uncondition branch
75     /// (aka goto instruction).
76     static bool isAlmostEmpty(BasicBlock *);
77
78     static BranchInst *getBranch(BasicBlock *BB) {
79       return dyn_cast<BranchInst>(BB->getTerminator());
80     }
81
82     /// Return the condition of the branch terminating the given basic block.
83     static Value *getBrCondtion(BasicBlock *);
84
85     /// Derive the precondition block (i.e the block that guards the loop
86     /// preheader) from the given preheader.
87     static BasicBlock *getPrecondBb(BasicBlock *PreHead);
88   };
89
90   /// This class is to recoginize idioms of population-count conducted in
91   /// a noncountable loop. Currently it only recognizes this pattern:
92   /// \code
93   ///   while(x) {cnt++; ...; x &= x - 1; ...}
94   /// \endcode
95   class NclPopcountRecognize {
96     LoopIdiomRecognize &LIR;
97     Loop *CurLoop;
98     BasicBlock *PreCondBB;
99
100     typedef IRBuilder<> IRBuilderTy;
101
102   public:
103     explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
104     bool recognize();
105
106   private:
107     /// Take a glimpse of the loop to see if we need to go ahead recoginizing
108     /// the idiom.
109     bool preliminaryScreen();
110
111     /// Check if the given conditional branch is based on the comparison
112     /// between a variable and zero, and if the variable is non-zero, the
113     /// control yields to the loop entry. If the branch matches the behavior,
114     /// the variable involved in the comparion is returned. This function will
115     /// be called to see if the precondition and postcondition of the loop
116     /// are in desirable form.
117     Value *matchCondition (BranchInst *Br, BasicBlock *NonZeroTarget) const;
118
119     /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
120     /// is set to the instruction counting the pupulation bit. 2) \p CntPhi
121     /// is set to the corresponding phi node. 3) \p Var is set to the value
122     /// whose population bits are being counted.
123     bool detectIdiom
124       (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
125
126     /// Insert ctpop intrinsic function and some obviously dead instructions.
127     void transform (Instruction *CntInst, PHINode *CntPhi, Value *Var);
128
129     /// Create llvm.ctpop.* intrinsic function.
130     CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
131   };
132
133   class LoopIdiomRecognize : public LoopPass {
134     Loop *CurLoop;
135     const DataLayout *TD;
136     DominatorTree *DT;
137     ScalarEvolution *SE;
138     TargetLibraryInfo *TLI;
139     const TargetTransformInfo *TTI;
140   public:
141     static char ID;
142     explicit LoopIdiomRecognize() : LoopPass(ID) {
143       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
144       TD = 0; DT = 0; SE = 0; TLI = 0; TTI = 0;
145     }
146
147     bool runOnLoop(Loop *L, LPPassManager &LPM);
148     bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
149                         SmallVectorImpl<BasicBlock*> &ExitBlocks);
150
151     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
152     bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
153
154     bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
155                                  unsigned StoreAlignment,
156                                  Value *SplatValue, Instruction *TheStore,
157                                  const SCEVAddRecExpr *Ev,
158                                  const SCEV *BECount);
159     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
160                                     const SCEVAddRecExpr *StoreEv,
161                                     const SCEVAddRecExpr *LoadEv,
162                                     const SCEV *BECount);
163
164     /// This transformation requires natural loop information & requires that
165     /// loop preheaders be inserted into the CFG.
166     ///
167     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168       AU.addRequired<LoopInfo>();
169       AU.addPreserved<LoopInfo>();
170       AU.addRequiredID(LoopSimplifyID);
171       AU.addPreservedID(LoopSimplifyID);
172       AU.addRequiredID(LCSSAID);
173       AU.addPreservedID(LCSSAID);
174       AU.addRequired<AliasAnalysis>();
175       AU.addPreserved<AliasAnalysis>();
176       AU.addRequired<ScalarEvolution>();
177       AU.addPreserved<ScalarEvolution>();
178       AU.addPreserved<DominatorTreeWrapperPass>();
179       AU.addRequired<DominatorTreeWrapperPass>();
180       AU.addRequired<TargetLibraryInfo>();
181       AU.addRequired<TargetTransformInfo>();
182     }
183
184     const DataLayout *getDataLayout() {
185       return TD ? TD : TD=getAnalysisIfAvailable<DataLayout>();
186     }
187
188     DominatorTree *getDominatorTree() {
189       return DT ? DT
190                 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
191     }
192
193     ScalarEvolution *getScalarEvolution() {
194       return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
195     }
196
197     TargetLibraryInfo *getTargetLibraryInfo() {
198       return TLI ? TLI : (TLI = &getAnalysis<TargetLibraryInfo>());
199     }
200
201     const TargetTransformInfo *getTargetTransformInfo() {
202       return TTI ? TTI : (TTI = &getAnalysis<TargetTransformInfo>());
203     }
204
205     Loop *getLoop() const { return CurLoop; }
206
207   private:
208     bool runOnNoncountableLoop();
209     bool runOnCountableLoop();
210   };
211 }
212
213 char LoopIdiomRecognize::ID = 0;
214 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
215                       false, false)
216 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
217 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
218 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
219 INITIALIZE_PASS_DEPENDENCY(LCSSA)
220 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
221 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
222 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
223 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
224 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
225                     false, false)
226
227 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
228
229 /// deleteDeadInstruction - Delete this instruction.  Before we do, go through
230 /// and zero out all the operands of this instruction.  If any of them become
231 /// dead, delete them and the computation tree that feeds them.
232 ///
233 static void deleteDeadInstruction(Instruction *I, ScalarEvolution &SE,
234                                   const TargetLibraryInfo *TLI) {
235   SmallVector<Instruction*, 32> NowDeadInsts;
236
237   NowDeadInsts.push_back(I);
238
239   // Before we touch this instruction, remove it from SE!
240   do {
241     Instruction *DeadInst = NowDeadInsts.pop_back_val();
242
243     // This instruction is dead, zap it, in stages.  Start by removing it from
244     // SCEV.
245     SE.forgetValue(DeadInst);
246
247     for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
248       Value *Op = DeadInst->getOperand(op);
249       DeadInst->setOperand(op, 0);
250
251       // If this operand just became dead, add it to the NowDeadInsts list.
252       if (!Op->use_empty()) continue;
253
254       if (Instruction *OpI = dyn_cast<Instruction>(Op))
255         if (isInstructionTriviallyDead(OpI, TLI))
256           NowDeadInsts.push_back(OpI);
257     }
258
259     DeadInst->eraseFromParent();
260
261   } while (!NowDeadInsts.empty());
262 }
263
264 /// deleteIfDeadInstruction - If the specified value is a dead instruction,
265 /// delete it and any recursively used instructions.
266 static void deleteIfDeadInstruction(Value *V, ScalarEvolution &SE,
267                                     const TargetLibraryInfo *TLI) {
268   if (Instruction *I = dyn_cast<Instruction>(V))
269     if (isInstructionTriviallyDead(I, TLI))
270       deleteDeadInstruction(I, SE, TLI);
271 }
272
273 //===----------------------------------------------------------------------===//
274 //
275 //          Implementation of LIRUtil
276 //
277 //===----------------------------------------------------------------------===//
278
279 // This function will return true iff the given block contains nothing but goto.
280 // A typical usage of this function is to check if the preheader function is
281 // "almost" empty such that generated intrinsic functions can be moved across
282 // the preheader and be placed at the end of the precondition block without
283 // the concern of breaking data dependence.
284 bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
285   if (BranchInst *Br = getBranch(BB)) {
286     return Br->isUnconditional() && BB->size() == 1;
287   }
288   return false;
289 }
290
291 Value *LIRUtil::getBrCondtion(BasicBlock *BB) {
292   BranchInst *Br = getBranch(BB);
293   return Br ? Br->getCondition() : 0;
294 }
295
296 BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
297   if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
298     BranchInst *Br = getBranch(BB);
299     return Br && Br->isConditional() ? BB : 0;
300   }
301   return 0;
302 }
303
304 //===----------------------------------------------------------------------===//
305 //
306 //          Implementation of NclPopcountRecognize
307 //
308 //===----------------------------------------------------------------------===//
309
310 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
311   LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(0) {
312 }
313
314 bool NclPopcountRecognize::preliminaryScreen() {
315   const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
316   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
317     return false;
318
319   // Counting population are usually conducted by few arithmetic instructions.
320   // Such instructions can be easilly "absorbed" by vacant slots in a
321   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
322   // in a compact loop.
323
324   // Give up if the loop has multiple blocks or multiple backedges.
325   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
326     return false;
327
328   BasicBlock *LoopBody = *(CurLoop->block_begin());
329   if (LoopBody->size() >= 20) {
330     // The loop is too big, bail out.
331     return false;
332   }
333
334   // It should have a preheader containing nothing but a goto instruction.
335   BasicBlock *PreHead = CurLoop->getLoopPreheader();
336   if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
337     return false;
338
339   // It should have a precondition block where the generated popcount instrinsic
340   // function will be inserted.
341   PreCondBB = LIRUtil::getPrecondBb(PreHead);
342   if (!PreCondBB)
343     return false;
344
345   return true;
346 }
347
348 Value *NclPopcountRecognize::matchCondition (BranchInst *Br,
349                                              BasicBlock *LoopEntry) const {
350   if (!Br || !Br->isConditional())
351     return 0;
352
353   ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
354   if (!Cond)
355     return 0;
356
357   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
358   if (!CmpZero || !CmpZero->isZero())
359     return 0;
360
361   ICmpInst::Predicate Pred = Cond->getPredicate();
362   if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
363       (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
364     return Cond->getOperand(0);
365
366   return 0;
367 }
368
369 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
370                                        PHINode *&CntPhi,
371                                        Value *&Var) const {
372   // Following code tries to detect this idiom:
373   //
374   //    if (x0 != 0)
375   //      goto loop-exit // the precondition of the loop
376   //    cnt0 = init-val;
377   //    do {
378   //       x1 = phi (x0, x2);
379   //       cnt1 = phi(cnt0, cnt2);
380   //
381   //       cnt2 = cnt1 + 1;
382   //        ...
383   //       x2 = x1 & (x1 - 1);
384   //        ...
385   //    } while(x != 0);
386   //
387   // loop-exit:
388   //
389
390   // step 1: Check to see if the look-back branch match this pattern:
391   //    "if (a!=0) goto loop-entry".
392   BasicBlock *LoopEntry;
393   Instruction *DefX2, *CountInst;
394   Value *VarX1, *VarX0;
395   PHINode *PhiX, *CountPhi;
396
397   DefX2 = CountInst = 0;
398   VarX1 = VarX0 = 0;
399   PhiX = CountPhi = 0;
400   LoopEntry = *(CurLoop->block_begin());
401
402   // step 1: Check if the loop-back branch is in desirable form.
403   {
404     if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
405       DefX2 = dyn_cast<Instruction>(T);
406     else
407       return false;
408   }
409
410   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
411   {
412     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
413       return false;
414
415     BinaryOperator *SubOneOp;
416
417     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
418       VarX1 = DefX2->getOperand(1);
419     else {
420       VarX1 = DefX2->getOperand(0);
421       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
422     }
423     if (!SubOneOp)
424       return false;
425
426     Instruction *SubInst = cast<Instruction>(SubOneOp);
427     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
428     if (!Dec ||
429         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
430           (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
431       return false;
432     }
433   }
434
435   // step 3: Check the recurrence of variable X
436   {
437     PhiX = dyn_cast<PHINode>(VarX1);
438     if (!PhiX ||
439         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
440       return false;
441     }
442   }
443
444   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
445   {
446     CountInst = NULL;
447     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
448            IterE = LoopEntry->end(); Iter != IterE; Iter++) {
449       Instruction *Inst = Iter;
450       if (Inst->getOpcode() != Instruction::Add)
451         continue;
452
453       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
454       if (!Inc || !Inc->isOne())
455         continue;
456
457       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
458       if (!Phi || Phi->getParent() != LoopEntry)
459         continue;
460
461       // Check if the result of the instruction is live of the loop.
462       bool LiveOutLoop = false;
463       for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
464              I != E;  I++) {
465         if ((cast<Instruction>(*I))->getParent() != LoopEntry) {
466           LiveOutLoop = true; break;
467         }
468       }
469
470       if (LiveOutLoop) {
471         CountInst = Inst;
472         CountPhi = Phi;
473         break;
474       }
475     }
476
477     if (!CountInst)
478       return false;
479   }
480
481   // step 5: check if the precondition is in this form:
482   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
483   {
484     BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
485     Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
486     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
487       return false;
488
489     CntInst = CountInst;
490     CntPhi = CountPhi;
491     Var = T;
492   }
493
494   return true;
495 }
496
497 void NclPopcountRecognize::transform(Instruction *CntInst,
498                                      PHINode *CntPhi, Value *Var) {
499
500   ScalarEvolution *SE = LIR.getScalarEvolution();
501   TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
502   BasicBlock *PreHead = CurLoop->getLoopPreheader();
503   BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
504   const DebugLoc DL = CntInst->getDebugLoc();
505
506   // Assuming before transformation, the loop is following:
507   //  if (x) // the precondition
508   //     do { cnt++; x &= x - 1; } while(x);
509
510   // Step 1: Insert the ctpop instruction at the end of the precondition block
511   IRBuilderTy Builder(PreCondBr);
512   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
513   {
514     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
515     NewCount = PopCntZext =
516       Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
517
518     if (NewCount != PopCnt)
519       (cast<Instruction>(NewCount))->setDebugLoc(DL);
520
521     // TripCnt is exactly the number of iterations the loop has
522     TripCnt = NewCount;
523
524     // If the population counter's initial value is not zero, insert Add Inst.
525     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
526     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
527     if (!InitConst || !InitConst->isZero()) {
528       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
529       (cast<Instruction>(NewCount))->setDebugLoc(DL);
530     }
531   }
532
533   // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
534   //   "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
535   //   function would be partial dead code, and downstream passes will drag
536   //   it back from the precondition block to the preheader.
537   {
538     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
539
540     Value *Opnd0 = PopCntZext;
541     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
542     if (PreCond->getOperand(0) != Var)
543       std::swap(Opnd0, Opnd1);
544
545     ICmpInst *NewPreCond =
546       cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
547     PreCond->replaceAllUsesWith(NewPreCond);
548
549     deleteDeadInstruction(PreCond, *SE, TLI);
550   }
551
552   // Step 3: Note that the population count is exactly the trip count of the
553   // loop in question, which enble us to to convert the loop from noncountable
554   // loop into a countable one. The benefit is twofold:
555   //
556   //  - If the loop only counts population, the entire loop become dead after
557   //    the transformation. It is lots easier to prove a countable loop dead
558   //    than to prove a noncountable one. (In some C dialects, a infite loop
559   //    isn't dead even if it computes nothing useful. In general, DCE needs
560   //    to prove a noncountable loop finite before safely delete it.)
561   //
562   //  - If the loop also performs something else, it remains alive.
563   //    Since it is transformed to countable form, it can be aggressively
564   //    optimized by some optimizations which are in general not applicable
565   //    to a noncountable loop.
566   //
567   // After this step, this loop (conceptually) would look like following:
568   //   newcnt = __builtin_ctpop(x);
569   //   t = newcnt;
570   //   if (x)
571   //     do { cnt++; x &= x-1; t--) } while (t > 0);
572   BasicBlock *Body = *(CurLoop->block_begin());
573   {
574     BranchInst *LbBr = LIRUtil::getBranch(Body);
575     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
576     Type *Ty = TripCnt->getType();
577
578     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
579
580     Builder.SetInsertPoint(LbCond);
581     Value *Opnd1 = cast<Value>(TcPhi);
582     Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
583     Instruction *TcDec =
584       cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
585
586     TcPhi->addIncoming(TripCnt, PreHead);
587     TcPhi->addIncoming(TcDec, Body);
588
589     CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
590       CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
591     LbCond->setPredicate(Pred);
592     LbCond->setOperand(0, TcDec);
593     LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
594   }
595
596   // Step 4: All the references to the original population counter outside
597   //  the loop are replaced with the NewCount -- the value returned from
598   //  __builtin_ctpop().
599   {
600     SmallVector<Value *, 4> CntUses;
601     for (Value::use_iterator I = CntInst->use_begin(), E = CntInst->use_end();
602          I != E; I++) {
603       if (cast<Instruction>(*I)->getParent() != Body)
604         CntUses.push_back(*I);
605     }
606     for (unsigned Idx = 0; Idx < CntUses.size(); Idx++) {
607       (cast<Instruction>(CntUses[Idx]))->replaceUsesOfWith(CntInst, NewCount);
608     }
609   }
610
611   // step 5: Forget the "non-computable" trip-count SCEV associated with the
612   //   loop. The loop would otherwise not be deleted even if it becomes empty.
613   SE->forgetLoop(CurLoop);
614 }
615
616 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
617                                                       Value *Val, DebugLoc DL) {
618   Value *Ops[] = { Val };
619   Type *Tys[] = { Val->getType() };
620
621   Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
622   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
623   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
624   CI->setDebugLoc(DL);
625
626   return CI;
627 }
628
629 /// recognize - detect population count idiom in a non-countable loop. If
630 ///   detected, transform the relevant code to popcount intrinsic function
631 ///   call, and return true; otherwise, return false.
632 bool NclPopcountRecognize::recognize() {
633
634   if (!LIR.getTargetTransformInfo())
635     return false;
636
637   LIR.getScalarEvolution();
638
639   if (!preliminaryScreen())
640     return false;
641
642   Instruction *CntInst;
643   PHINode *CntPhi;
644   Value *Val;
645   if (!detectIdiom(CntInst, CntPhi, Val))
646     return false;
647
648   transform(CntInst, CntPhi, Val);
649   return true;
650 }
651
652 //===----------------------------------------------------------------------===//
653 //
654 //          Implementation of LoopIdiomRecognize
655 //
656 //===----------------------------------------------------------------------===//
657
658 bool LoopIdiomRecognize::runOnCountableLoop() {
659   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
660   if (isa<SCEVCouldNotCompute>(BECount)) return false;
661
662   // If this loop executes exactly one time, then it should be peeled, not
663   // optimized by this pass.
664   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
665     if (BECst->getValue()->getValue() == 0)
666       return false;
667
668   // We require target data for now.
669   if (!getDataLayout())
670     return false;
671
672   // set DT
673   (void)getDominatorTree();
674
675   LoopInfo &LI = getAnalysis<LoopInfo>();
676   TLI = &getAnalysis<TargetLibraryInfo>();
677
678   // set TLI
679   (void)getTargetLibraryInfo();
680
681   SmallVector<BasicBlock*, 8> ExitBlocks;
682   CurLoop->getUniqueExitBlocks(ExitBlocks);
683
684   DEBUG(dbgs() << "loop-idiom Scanning: F["
685                << CurLoop->getHeader()->getParent()->getName()
686                << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
687
688   bool MadeChange = false;
689   // Scan all the blocks in the loop that are not in subloops.
690   for (Loop::block_iterator BI = CurLoop->block_begin(),
691          E = CurLoop->block_end(); BI != E; ++BI) {
692     // Ignore blocks in subloops.
693     if (LI.getLoopFor(*BI) != CurLoop)
694       continue;
695
696     MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
697   }
698   return MadeChange;
699 }
700
701 bool LoopIdiomRecognize::runOnNoncountableLoop() {
702   NclPopcountRecognize Popcount(*this);
703   if (Popcount.recognize())
704     return true;
705
706   return false;
707 }
708
709 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
710   if (skipOptnoneFunction(L))
711     return false;
712
713   CurLoop = L;
714
715   // If the loop could not be converted to canonical form, it must have an
716   // indirectbr in it, just give up.
717   if (!L->getLoopPreheader())
718     return false;
719
720   // Disable loop idiom recognition if the function's name is a common idiom.
721   StringRef Name = L->getHeader()->getParent()->getName();
722   if (Name == "memset" || Name == "memcpy")
723     return false;
724
725   SE = &getAnalysis<ScalarEvolution>();
726   if (SE->hasLoopInvariantBackedgeTakenCount(L))
727     return runOnCountableLoop();
728   return runOnNoncountableLoop();
729 }
730
731 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
732 /// with the specified backedge count.  This block is known to be in the current
733 /// loop and not in any subloops.
734 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
735                                      SmallVectorImpl<BasicBlock*> &ExitBlocks) {
736   // We can only promote stores in this block if they are unconditionally
737   // executed in the loop.  For a block to be unconditionally executed, it has
738   // to dominate all the exit blocks of the loop.  Verify this now.
739   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
740     if (!DT->dominates(BB, ExitBlocks[i]))
741       return false;
742
743   bool MadeChange = false;
744   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
745     Instruction *Inst = I++;
746     // Look for store instructions, which may be optimized to memset/memcpy.
747     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))  {
748       WeakVH InstPtr(I);
749       if (!processLoopStore(SI, BECount)) continue;
750       MadeChange = true;
751
752       // If processing the store invalidated our iterator, start over from the
753       // top of the block.
754       if (InstPtr == 0)
755         I = BB->begin();
756       continue;
757     }
758
759     // Look for memset instructions, which may be optimized to a larger memset.
760     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst))  {
761       WeakVH InstPtr(I);
762       if (!processLoopMemSet(MSI, BECount)) continue;
763       MadeChange = true;
764
765       // If processing the memset invalidated our iterator, start over from the
766       // top of the block.
767       if (InstPtr == 0)
768         I = BB->begin();
769       continue;
770     }
771   }
772
773   return MadeChange;
774 }
775
776
777 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
778 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
779   if (!SI->isSimple()) return false;
780
781   Value *StoredVal = SI->getValueOperand();
782   Value *StorePtr = SI->getPointerOperand();
783
784   // Reject stores that are so large that they overflow an unsigned.
785   uint64_t SizeInBits = TD->getTypeSizeInBits(StoredVal->getType());
786   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
787     return false;
788
789   // See if the pointer expression is an AddRec like {base,+,1} on the current
790   // loop, which indicates a strided store.  If we have something else, it's a
791   // random store we can't handle.
792   const SCEVAddRecExpr *StoreEv =
793     dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
794   if (StoreEv == 0 || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
795     return false;
796
797   // Check to see if the stride matches the size of the store.  If so, then we
798   // know that every byte is touched in the loop.
799   unsigned StoreSize = (unsigned)SizeInBits >> 3;
800   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
801
802   if (Stride == 0 || StoreSize != Stride->getValue()->getValue()) {
803     // TODO: Could also handle negative stride here someday, that will require
804     // the validity check in mayLoopAccessLocation to be updated though.
805     // Enable this to print exact negative strides.
806     if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
807       dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
808       dbgs() << "BB: " << *SI->getParent();
809     }
810
811     return false;
812   }
813
814   // See if we can optimize just this store in isolation.
815   if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
816                               StoredVal, SI, StoreEv, BECount))
817     return true;
818
819   // If the stored value is a strided load in the same loop with the same stride
820   // this this may be transformable into a memcpy.  This kicks in for stuff like
821   //   for (i) A[i] = B[i];
822   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
823     const SCEVAddRecExpr *LoadEv =
824       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
825     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
826         StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
827       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
828         return true;
829   }
830   //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
831
832   return false;
833 }
834
835 /// processLoopMemSet - See if this memset can be promoted to a large memset.
836 bool LoopIdiomRecognize::
837 processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
838   // We can only handle non-volatile memsets with a constant size.
839   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
840
841   // If we're not allowed to hack on memset, we fail.
842   if (!TLI->has(LibFunc::memset))
843     return false;
844
845   Value *Pointer = MSI->getDest();
846
847   // See if the pointer expression is an AddRec like {base,+,1} on the current
848   // loop, which indicates a strided store.  If we have something else, it's a
849   // random store we can't handle.
850   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
851   if (Ev == 0 || Ev->getLoop() != CurLoop || !Ev->isAffine())
852     return false;
853
854   // Reject memsets that are so large that they overflow an unsigned.
855   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
856   if ((SizeInBytes >> 32) != 0)
857     return false;
858
859   // Check to see if the stride matches the size of the memset.  If so, then we
860   // know that every byte is touched in the loop.
861   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
862
863   // TODO: Could also handle negative stride here someday, that will require the
864   // validity check in mayLoopAccessLocation to be updated though.
865   if (Stride == 0 || MSI->getLength() != Stride->getValue())
866     return false;
867
868   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
869                                  MSI->getAlignment(), MSI->getValue(),
870                                  MSI, Ev, BECount);
871 }
872
873
874 /// mayLoopAccessLocation - Return true if the specified loop might access the
875 /// specified pointer location, which is a loop-strided access.  The 'Access'
876 /// argument specifies what the verboten forms of access are (read or write).
877 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
878                                   Loop *L, const SCEV *BECount,
879                                   unsigned StoreSize, AliasAnalysis &AA,
880                                   Instruction *IgnoredStore) {
881   // Get the location that may be stored across the loop.  Since the access is
882   // strided positively through memory, we say that the modified location starts
883   // at the pointer and has infinite size.
884   uint64_t AccessSize = AliasAnalysis::UnknownSize;
885
886   // If the loop iterates a fixed number of times, we can refine the access size
887   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
888   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
889     AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
890
891   // TODO: For this to be really effective, we have to dive into the pointer
892   // operand in the store.  Store to &A[i] of 100 will always return may alias
893   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
894   // which will then no-alias a store to &A[100].
895   AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
896
897   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
898        ++BI)
899     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
900       if (&*I != IgnoredStore &&
901           (AA.getModRefInfo(I, StoreLoc) & Access))
902         return true;
903
904   return false;
905 }
906
907 /// getMemSetPatternValue - If a strided store of the specified value is safe to
908 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
909 /// be passed in.  Otherwise, return null.
910 ///
911 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
912 /// just replicate their input array and then pass on to memset_pattern16.
913 static Constant *getMemSetPatternValue(Value *V, const DataLayout &TD) {
914   // If the value isn't a constant, we can't promote it to being in a constant
915   // array.  We could theoretically do a store to an alloca or something, but
916   // that doesn't seem worthwhile.
917   Constant *C = dyn_cast<Constant>(V);
918   if (C == 0) return 0;
919
920   // Only handle simple values that are a power of two bytes in size.
921   uint64_t Size = TD.getTypeSizeInBits(V->getType());
922   if (Size == 0 || (Size & 7) || (Size & (Size-1)))
923     return 0;
924
925   // Don't care enough about darwin/ppc to implement this.
926   if (TD.isBigEndian())
927     return 0;
928
929   // Convert to size in bytes.
930   Size /= 8;
931
932   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
933   // if the top and bottom are the same (e.g. for vectors and large integers).
934   if (Size > 16) return 0;
935
936   // If the constant is exactly 16 bytes, just use it.
937   if (Size == 16) return C;
938
939   // Otherwise, we'll use an array of the constants.
940   unsigned ArraySize = 16/Size;
941   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
942   return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
943 }
944
945
946 /// processLoopStridedStore - We see a strided store of some value.  If we can
947 /// transform this into a memset or memset_pattern in the loop preheader, do so.
948 bool LoopIdiomRecognize::
949 processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
950                         unsigned StoreAlignment, Value *StoredVal,
951                         Instruction *TheStore, const SCEVAddRecExpr *Ev,
952                         const SCEV *BECount) {
953
954   // If the stored value is a byte-wise value (like i32 -1), then it may be
955   // turned into a memset of i8 -1, assuming that all the consecutive bytes
956   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
957   // but it can be turned into memset_pattern if the target supports it.
958   Value *SplatValue = isBytewiseValue(StoredVal);
959   Constant *PatternValue = 0;
960
961   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
962
963   // If we're allowed to form a memset, and the stored value would be acceptable
964   // for memset, use it.
965   if (SplatValue && TLI->has(LibFunc::memset) &&
966       // Verify that the stored value is loop invariant.  If not, we can't
967       // promote the memset.
968       CurLoop->isLoopInvariant(SplatValue)) {
969     // Keep and use SplatValue.
970     PatternValue = 0;
971   } else if (DestAS == 0 &&
972              TLI->has(LibFunc::memset_pattern16) &&
973              (PatternValue = getMemSetPatternValue(StoredVal, *TD))) {
974     // Don't create memset_pattern16s with address spaces.
975     // It looks like we can use PatternValue!
976     SplatValue = 0;
977   } else {
978     // Otherwise, this isn't an idiom we can transform.  For example, we can't
979     // do anything with a 3-byte store.
980     return false;
981   }
982
983   // The trip count of the loop and the base pointer of the addrec SCEV is
984   // guaranteed to be loop invariant, which means that it should dominate the
985   // header.  This allows us to insert code for it in the preheader.
986   BasicBlock *Preheader = CurLoop->getLoopPreheader();
987   IRBuilder<> Builder(Preheader->getTerminator());
988   SCEVExpander Expander(*SE, "loop-idiom");
989
990   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
991
992   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
993   // this into a memset in the loop preheader now if we want.  However, this
994   // would be unsafe to do if there is anything else in the loop that may read
995   // or write to the aliased location.  Check for any overlap by generating the
996   // base pointer and checking the region.
997   Value *BasePtr =
998     Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
999                            Preheader->getTerminator());
1000
1001   if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
1002                             CurLoop, BECount,
1003                             StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
1004     Expander.clear();
1005     // If we generated new code for the base pointer, clean up.
1006     deleteIfDeadInstruction(BasePtr, *SE, TLI);
1007     return false;
1008   }
1009
1010   // Okay, everything looks good, insert the memset.
1011
1012   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
1013   // pointer size if it isn't already.
1014   Type *IntPtr = Builder.getIntPtrTy(TD, DestAS);
1015   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
1016
1017   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
1018                                          SCEV::FlagNUW);
1019   if (StoreSize != 1) {
1020     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
1021                                SCEV::FlagNUW);
1022   }
1023
1024   Value *NumBytes =
1025     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
1026
1027   CallInst *NewCall;
1028   if (SplatValue) {
1029     NewCall = Builder.CreateMemSet(BasePtr,
1030                                    SplatValue,
1031                                    NumBytes,
1032                                    StoreAlignment);
1033   } else {
1034     // Everything is emitted in default address space
1035     Type *Int8PtrTy = DestInt8PtrTy;
1036
1037     Module *M = TheStore->getParent()->getParent()->getParent();
1038     Value *MSP = M->getOrInsertFunction("memset_pattern16",
1039                                         Builder.getVoidTy(),
1040                                         Int8PtrTy,
1041                                         Int8PtrTy,
1042                                         IntPtr,
1043                                         (void*)0);
1044
1045     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
1046     // an constant array of 16-bytes.  Plop the value into a mergable global.
1047     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1048                                             GlobalValue::InternalLinkage,
1049                                             PatternValue, ".memset_pattern");
1050     GV->setUnnamedAddr(true); // Ok to merge these.
1051     GV->setAlignment(16);
1052     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
1053     NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
1054   }
1055
1056   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
1057                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
1058   NewCall->setDebugLoc(TheStore->getDebugLoc());
1059
1060   // Okay, the memset has been formed.  Zap the original store and anything that
1061   // feeds into it.
1062   deleteDeadInstruction(TheStore, *SE, TLI);
1063   ++NumMemSet;
1064   return true;
1065 }
1066
1067 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
1068 /// same-strided load.
1069 bool LoopIdiomRecognize::
1070 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
1071                            const SCEVAddRecExpr *StoreEv,
1072                            const SCEVAddRecExpr *LoadEv,
1073                            const SCEV *BECount) {
1074   // If we're not allowed to form memcpy, we fail.
1075   if (!TLI->has(LibFunc::memcpy))
1076     return false;
1077
1078   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1079
1080   // The trip count of the loop and the base pointer of the addrec SCEV is
1081   // guaranteed to be loop invariant, which means that it should dominate the
1082   // header.  This allows us to insert code for it in the preheader.
1083   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1084   IRBuilder<> Builder(Preheader->getTerminator());
1085   SCEVExpander Expander(*SE, "loop-idiom");
1086
1087   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
1088   // this into a memcpy in the loop preheader now if we want.  However, this
1089   // would be unsafe to do if there is anything else in the loop that may read
1090   // or write the memory region we're storing to.  This includes the load that
1091   // feeds the stores.  Check for an alias by generating the base address and
1092   // checking everything.
1093   Value *StoreBasePtr =
1094     Expander.expandCodeFor(StoreEv->getStart(),
1095                            Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
1096                            Preheader->getTerminator());
1097
1098   if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
1099                             CurLoop, BECount, StoreSize,
1100                             getAnalysis<AliasAnalysis>(), SI)) {
1101     Expander.clear();
1102     // If we generated new code for the base pointer, clean up.
1103     deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1104     return false;
1105   }
1106
1107   // For a memcpy, we have to make sure that the input array is not being
1108   // mutated by the loop.
1109   Value *LoadBasePtr =
1110     Expander.expandCodeFor(LoadEv->getStart(),
1111                            Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
1112                            Preheader->getTerminator());
1113
1114   if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
1115                             StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
1116     Expander.clear();
1117     // If we generated new code for the base pointer, clean up.
1118     deleteIfDeadInstruction(LoadBasePtr, *SE, TLI);
1119     deleteIfDeadInstruction(StoreBasePtr, *SE, TLI);
1120     return false;
1121   }
1122
1123   // Okay, everything is safe, we can transform this!
1124
1125
1126   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
1127   // pointer size if it isn't already.
1128   Type *IntPtrTy = Builder.getIntPtrTy(TD, SI->getPointerAddressSpace());
1129   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
1130
1131   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
1132                                          SCEV::FlagNUW);
1133   if (StoreSize != 1)
1134     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
1135                                SCEV::FlagNUW);
1136
1137   Value *NumBytes =
1138     Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1139
1140   CallInst *NewCall =
1141     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
1142                          std::min(SI->getAlignment(), LI->getAlignment()));
1143   NewCall->setDebugLoc(SI->getDebugLoc());
1144
1145   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
1146                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1147                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
1148
1149
1150   // Okay, the memset has been formed.  Zap the original store and anything that
1151   // feeds into it.
1152   deleteDeadInstruction(SI, *SE, TLI);
1153   ++NumMemCpy;
1154   return true;
1155 }