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