LLVM API Documentation

LoopIdiomRecognize.cpp
Go to the documentation of this file.
00001 //===-- LoopIdiomRecognize.cpp - Loop idiom recognition -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass implements an idiom recognizer that transforms simple loops into a
00011 // non-loop form.  In cases that this kicks in, it can be a significant
00012 // performance win.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 //
00016 // TODO List:
00017 //
00018 // Future loop memory idioms to recognize:
00019 //   memcmp, memmove, strlen, etc.
00020 // Future floating point idioms to recognize in -ffast-math mode:
00021 //   fpowi
00022 // Future integer operation idioms to recognize:
00023 //   ctpop, ctlz, cttz
00024 //
00025 // Beware that isel's default lowering for ctpop is highly inefficient for
00026 // i64 and larger types when i64 is legal and the value has few bits set.  It
00027 // would be good to enhance isel to emit a loop for ctpop in this case.
00028 //
00029 // We should enhance the memset/memcpy recognition to handle multiple stores in
00030 // the loop.  This would handle things like:
00031 //   void foo(_Complex float *P)
00032 //     for (i) { __real__(*P) = 0;  __imag__(*P) = 0; }
00033 //
00034 // We should enhance this to handle negative strides through memory.
00035 // Alternatively (and perhaps better) we could rely on an earlier pass to force
00036 // forward iteration through memory, which is generally better for cache
00037 // behavior.  Negative strides *do* happen for memset/memcpy loops.
00038 //
00039 // This could recognize common matrix multiplies and dot product idioms and
00040 // replace them with calls to BLAS (if linked in??).
00041 //
00042 //===----------------------------------------------------------------------===//
00043 
00044 #include "llvm/Transforms/Scalar.h"
00045 #include "llvm/ADT/Statistic.h"
00046 #include "llvm/Analysis/AliasAnalysis.h"
00047 #include "llvm/Analysis/LoopPass.h"
00048 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00049 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00050 #include "llvm/Analysis/TargetTransformInfo.h"
00051 #include "llvm/Analysis/ValueTracking.h"
00052 #include "llvm/IR/DataLayout.h"
00053 #include "llvm/IR/Dominators.h"
00054 #include "llvm/IR/IRBuilder.h"
00055 #include "llvm/IR/IntrinsicInst.h"
00056 #include "llvm/IR/Module.h"
00057 #include "llvm/Support/Debug.h"
00058 #include "llvm/Support/raw_ostream.h"
00059 #include "llvm/Analysis/TargetLibraryInfo.h"
00060 #include "llvm/Transforms/Utils/Local.h"
00061 using namespace llvm;
00062 
00063 #define DEBUG_TYPE "loop-idiom"
00064 
00065 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
00066 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
00067 
00068 namespace {
00069 
00070   class LoopIdiomRecognize;
00071 
00072   /// This class defines some utility functions for loop idiom recognization.
00073   class LIRUtil {
00074   public:
00075     /// Return true iff the block contains nothing but an uncondition branch
00076     /// (aka goto instruction).
00077     static bool isAlmostEmpty(BasicBlock *);
00078 
00079     static BranchInst *getBranch(BasicBlock *BB) {
00080       return dyn_cast<BranchInst>(BB->getTerminator());
00081     }
00082 
00083     /// Derive the precondition block (i.e the block that guards the loop
00084     /// preheader) from the given preheader.
00085     static BasicBlock *getPrecondBb(BasicBlock *PreHead);
00086   };
00087 
00088   /// This class is to recoginize idioms of population-count conducted in
00089   /// a noncountable loop. Currently it only recognizes this pattern:
00090   /// \code
00091   ///   while(x) {cnt++; ...; x &= x - 1; ...}
00092   /// \endcode
00093   class NclPopcountRecognize {
00094     LoopIdiomRecognize &LIR;
00095     Loop *CurLoop;
00096     BasicBlock *PreCondBB;
00097 
00098     typedef IRBuilder<> IRBuilderTy;
00099 
00100   public:
00101     explicit NclPopcountRecognize(LoopIdiomRecognize &TheLIR);
00102     bool recognize();
00103 
00104   private:
00105     /// Take a glimpse of the loop to see if we need to go ahead recoginizing
00106     /// the idiom.
00107     bool preliminaryScreen();
00108 
00109     /// Check if the given conditional branch is based on the comparison
00110     /// between a variable and zero, and if the variable is non-zero, the
00111     /// control yields to the loop entry. If the branch matches the behavior,
00112     /// the variable involved in the comparion is returned. This function will
00113     /// be called to see if the precondition and postcondition of the loop
00114     /// are in desirable form.
00115     Value *matchCondition(BranchInst *Br, BasicBlock *NonZeroTarget) const;
00116 
00117     /// Return true iff the idiom is detected in the loop. and 1) \p CntInst
00118     /// is set to the instruction counting the population bit. 2) \p CntPhi
00119     /// is set to the corresponding phi node. 3) \p Var is set to the value
00120     /// whose population bits are being counted.
00121     bool detectIdiom
00122       (Instruction *&CntInst, PHINode *&CntPhi, Value *&Var) const;
00123 
00124     /// Insert ctpop intrinsic function and some obviously dead instructions.
00125     void transform(Instruction *CntInst, PHINode *CntPhi, Value *Var);
00126 
00127     /// Create llvm.ctpop.* intrinsic function.
00128     CallInst *createPopcntIntrinsic(IRBuilderTy &IRB, Value *Val, DebugLoc DL);
00129   };
00130 
00131   class LoopIdiomRecognize : public LoopPass {
00132     Loop *CurLoop;
00133     DominatorTree *DT;
00134     ScalarEvolution *SE;
00135     TargetLibraryInfo *TLI;
00136     const TargetTransformInfo *TTI;
00137   public:
00138     static char ID;
00139     explicit LoopIdiomRecognize() : LoopPass(ID) {
00140       initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
00141       DT = nullptr;
00142       SE = nullptr;
00143       TLI = nullptr;
00144       TTI = nullptr;
00145     }
00146 
00147     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00148     bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
00149                         SmallVectorImpl<BasicBlock*> &ExitBlocks);
00150 
00151     bool processLoopStore(StoreInst *SI, const SCEV *BECount);
00152     bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
00153 
00154     bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
00155                                  unsigned StoreAlignment,
00156                                  Value *SplatValue, Instruction *TheStore,
00157                                  const SCEVAddRecExpr *Ev,
00158                                  const SCEV *BECount);
00159     bool processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
00160                                     const SCEVAddRecExpr *StoreEv,
00161                                     const SCEVAddRecExpr *LoadEv,
00162                                     const SCEV *BECount);
00163 
00164     /// This transformation requires natural loop information & requires that
00165     /// loop preheaders be inserted into the CFG.
00166     ///
00167     void getAnalysisUsage(AnalysisUsage &AU) const override {
00168       AU.addRequired<LoopInfoWrapperPass>();
00169       AU.addPreserved<LoopInfoWrapperPass>();
00170       AU.addRequiredID(LoopSimplifyID);
00171       AU.addPreservedID(LoopSimplifyID);
00172       AU.addRequiredID(LCSSAID);
00173       AU.addPreservedID(LCSSAID);
00174       AU.addRequired<AliasAnalysis>();
00175       AU.addPreserved<AliasAnalysis>();
00176       AU.addRequired<ScalarEvolution>();
00177       AU.addPreserved<ScalarEvolution>();
00178       AU.addPreserved<DominatorTreeWrapperPass>();
00179       AU.addRequired<DominatorTreeWrapperPass>();
00180       AU.addRequired<TargetLibraryInfoWrapperPass>();
00181       AU.addRequired<TargetTransformInfoWrapperPass>();
00182     }
00183 
00184     DominatorTree *getDominatorTree() {
00185       return DT ? DT
00186                 : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
00187     }
00188 
00189     ScalarEvolution *getScalarEvolution() {
00190       return SE ? SE : (SE = &getAnalysis<ScalarEvolution>());
00191     }
00192 
00193     TargetLibraryInfo *getTargetLibraryInfo() {
00194       if (!TLI)
00195         TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00196 
00197       return TLI;
00198     }
00199 
00200     const TargetTransformInfo *getTargetTransformInfo() {
00201       return TTI ? TTI
00202                  : (TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
00203                         *CurLoop->getHeader()->getParent()));
00204     }
00205 
00206     Loop *getLoop() const { return CurLoop; }
00207 
00208   private:
00209     bool runOnNoncountableLoop();
00210     bool runOnCountableLoop();
00211   };
00212 }
00213 
00214 char LoopIdiomRecognize::ID = 0;
00215 INITIALIZE_PASS_BEGIN(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
00216                       false, false)
00217 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00218 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00219 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00220 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00221 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
00222 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00223 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00224 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
00225 INITIALIZE_PASS_END(LoopIdiomRecognize, "loop-idiom", "Recognize loop idioms",
00226                     false, false)
00227 
00228 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognize(); }
00229 
00230 /// deleteDeadInstruction - Delete this instruction.  Before we do, go through
00231 /// and zero out all the operands of this instruction.  If any of them become
00232 /// dead, delete them and the computation tree that feeds them.
00233 ///
00234 static void deleteDeadInstruction(Instruction *I,
00235                                   const TargetLibraryInfo *TLI) {
00236   SmallVector<Value *, 16> Operands(I->value_op_begin(), I->value_op_end());
00237   I->replaceAllUsesWith(UndefValue::get(I->getType()));
00238   I->eraseFromParent();
00239   for (Value *Op : Operands)
00240     RecursivelyDeleteTriviallyDeadInstructions(Op, TLI);
00241 }
00242 
00243 //===----------------------------------------------------------------------===//
00244 //
00245 //          Implementation of LIRUtil
00246 //
00247 //===----------------------------------------------------------------------===//
00248 
00249 // This function will return true iff the given block contains nothing but goto.
00250 // A typical usage of this function is to check if the preheader function is
00251 // "almost" empty such that generated intrinsic functions can be moved across
00252 // the preheader and be placed at the end of the precondition block without
00253 // the concern of breaking data dependence.
00254 bool LIRUtil::isAlmostEmpty(BasicBlock *BB) {
00255   if (BranchInst *Br = getBranch(BB)) {
00256     return Br->isUnconditional() && Br == BB->begin();
00257   }
00258   return false;
00259 }
00260 
00261 BasicBlock *LIRUtil::getPrecondBb(BasicBlock *PreHead) {
00262   if (BasicBlock *BB = PreHead->getSinglePredecessor()) {
00263     BranchInst *Br = getBranch(BB);
00264     return Br && Br->isConditional() ? BB : nullptr;
00265   }
00266   return nullptr;
00267 }
00268 
00269 //===----------------------------------------------------------------------===//
00270 //
00271 //          Implementation of NclPopcountRecognize
00272 //
00273 //===----------------------------------------------------------------------===//
00274 
00275 NclPopcountRecognize::NclPopcountRecognize(LoopIdiomRecognize &TheLIR):
00276   LIR(TheLIR), CurLoop(TheLIR.getLoop()), PreCondBB(nullptr) {
00277 }
00278 
00279 bool NclPopcountRecognize::preliminaryScreen() {
00280   const TargetTransformInfo *TTI = LIR.getTargetTransformInfo();
00281   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
00282     return false;
00283 
00284   // Counting population are usually conducted by few arithmetic instructions.
00285   // Such instructions can be easilly "absorbed" by vacant slots in a
00286   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
00287   // in a compact loop.
00288 
00289   // Give up if the loop has multiple blocks or multiple backedges.
00290   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
00291     return false;
00292 
00293   BasicBlock *LoopBody = *(CurLoop->block_begin());
00294   if (LoopBody->size() >= 20) {
00295     // The loop is too big, bail out.
00296     return false;
00297   }
00298 
00299   // It should have a preheader containing nothing but a goto instruction.
00300   BasicBlock *PreHead = CurLoop->getLoopPreheader();
00301   if (!PreHead || !LIRUtil::isAlmostEmpty(PreHead))
00302     return false;
00303 
00304   // It should have a precondition block where the generated popcount instrinsic
00305   // function will be inserted.
00306   PreCondBB = LIRUtil::getPrecondBb(PreHead);
00307   if (!PreCondBB)
00308     return false;
00309 
00310   return true;
00311 }
00312 
00313 Value *NclPopcountRecognize::matchCondition(BranchInst *Br,
00314                                             BasicBlock *LoopEntry) const {
00315   if (!Br || !Br->isConditional())
00316     return nullptr;
00317 
00318   ICmpInst *Cond = dyn_cast<ICmpInst>(Br->getCondition());
00319   if (!Cond)
00320     return nullptr;
00321 
00322   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
00323   if (!CmpZero || !CmpZero->isZero())
00324     return nullptr;
00325 
00326   ICmpInst::Predicate Pred = Cond->getPredicate();
00327   if ((Pred == ICmpInst::ICMP_NE && Br->getSuccessor(0) == LoopEntry) ||
00328       (Pred == ICmpInst::ICMP_EQ && Br->getSuccessor(1) == LoopEntry))
00329     return Cond->getOperand(0);
00330 
00331   return nullptr;
00332 }
00333 
00334 bool NclPopcountRecognize::detectIdiom(Instruction *&CntInst,
00335                                        PHINode *&CntPhi,
00336                                        Value *&Var) const {
00337   // Following code tries to detect this idiom:
00338   //
00339   //    if (x0 != 0)
00340   //      goto loop-exit // the precondition of the loop
00341   //    cnt0 = init-val;
00342   //    do {
00343   //       x1 = phi (x0, x2);
00344   //       cnt1 = phi(cnt0, cnt2);
00345   //
00346   //       cnt2 = cnt1 + 1;
00347   //        ...
00348   //       x2 = x1 & (x1 - 1);
00349   //        ...
00350   //    } while(x != 0);
00351   //
00352   // loop-exit:
00353   //
00354 
00355   // step 1: Check to see if the look-back branch match this pattern:
00356   //    "if (a!=0) goto loop-entry".
00357   BasicBlock *LoopEntry;
00358   Instruction *DefX2, *CountInst;
00359   Value *VarX1, *VarX0;
00360   PHINode *PhiX, *CountPhi;
00361 
00362   DefX2 = CountInst = nullptr;
00363   VarX1 = VarX0 = nullptr;
00364   PhiX = CountPhi = nullptr;
00365   LoopEntry = *(CurLoop->block_begin());
00366 
00367   // step 1: Check if the loop-back branch is in desirable form.
00368   {
00369     if (Value *T = matchCondition (LIRUtil::getBranch(LoopEntry), LoopEntry))
00370       DefX2 = dyn_cast<Instruction>(T);
00371     else
00372       return false;
00373   }
00374 
00375   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
00376   {
00377     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
00378       return false;
00379 
00380     BinaryOperator *SubOneOp;
00381 
00382     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
00383       VarX1 = DefX2->getOperand(1);
00384     else {
00385       VarX1 = DefX2->getOperand(0);
00386       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
00387     }
00388     if (!SubOneOp)
00389       return false;
00390 
00391     Instruction *SubInst = cast<Instruction>(SubOneOp);
00392     ConstantInt *Dec = dyn_cast<ConstantInt>(SubInst->getOperand(1));
00393     if (!Dec ||
00394         !((SubInst->getOpcode() == Instruction::Sub && Dec->isOne()) ||
00395           (SubInst->getOpcode() == Instruction::Add && Dec->isAllOnesValue()))) {
00396       return false;
00397     }
00398   }
00399 
00400   // step 3: Check the recurrence of variable X
00401   {
00402     PhiX = dyn_cast<PHINode>(VarX1);
00403     if (!PhiX ||
00404         (PhiX->getOperand(0) != DefX2 && PhiX->getOperand(1) != DefX2)) {
00405       return false;
00406     }
00407   }
00408 
00409   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
00410   {
00411     CountInst = nullptr;
00412     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI(),
00413            IterE = LoopEntry->end(); Iter != IterE; Iter++) {
00414       Instruction *Inst = Iter;
00415       if (Inst->getOpcode() != Instruction::Add)
00416         continue;
00417 
00418       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
00419       if (!Inc || !Inc->isOne())
00420         continue;
00421 
00422       PHINode *Phi = dyn_cast<PHINode>(Inst->getOperand(0));
00423       if (!Phi || Phi->getParent() != LoopEntry)
00424         continue;
00425 
00426       // Check if the result of the instruction is live of the loop.
00427       bool LiveOutLoop = false;
00428       for (User *U : Inst->users()) {
00429         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
00430           LiveOutLoop = true; break;
00431         }
00432       }
00433 
00434       if (LiveOutLoop) {
00435         CountInst = Inst;
00436         CountPhi = Phi;
00437         break;
00438       }
00439     }
00440 
00441     if (!CountInst)
00442       return false;
00443   }
00444 
00445   // step 5: check if the precondition is in this form:
00446   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
00447   {
00448     BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
00449     Value *T = matchCondition (PreCondBr, CurLoop->getLoopPreheader());
00450     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
00451       return false;
00452 
00453     CntInst = CountInst;
00454     CntPhi = CountPhi;
00455     Var = T;
00456   }
00457 
00458   return true;
00459 }
00460 
00461 void NclPopcountRecognize::transform(Instruction *CntInst,
00462                                      PHINode *CntPhi, Value *Var) {
00463 
00464   ScalarEvolution *SE = LIR.getScalarEvolution();
00465   TargetLibraryInfo *TLI = LIR.getTargetLibraryInfo();
00466   BasicBlock *PreHead = CurLoop->getLoopPreheader();
00467   BranchInst *PreCondBr = LIRUtil::getBranch(PreCondBB);
00468   const DebugLoc DL = CntInst->getDebugLoc();
00469 
00470   // Assuming before transformation, the loop is following:
00471   //  if (x) // the precondition
00472   //     do { cnt++; x &= x - 1; } while(x);
00473 
00474   // Step 1: Insert the ctpop instruction at the end of the precondition block
00475   IRBuilderTy Builder(PreCondBr);
00476   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
00477   {
00478     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
00479     NewCount = PopCntZext =
00480       Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
00481 
00482     if (NewCount != PopCnt)
00483       (cast<Instruction>(NewCount))->setDebugLoc(DL);
00484 
00485     // TripCnt is exactly the number of iterations the loop has
00486     TripCnt = NewCount;
00487 
00488     // If the population counter's initial value is not zero, insert Add Inst.
00489     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
00490     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
00491     if (!InitConst || !InitConst->isZero()) {
00492       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
00493       (cast<Instruction>(NewCount))->setDebugLoc(DL);
00494     }
00495   }
00496 
00497   // Step 2: Replace the precondition from "if(x == 0) goto loop-exit" to
00498   //   "if(NewCount == 0) loop-exit". Withtout this change, the intrinsic
00499   //   function would be partial dead code, and downstream passes will drag
00500   //   it back from the precondition block to the preheader.
00501   {
00502     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
00503 
00504     Value *Opnd0 = PopCntZext;
00505     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
00506     if (PreCond->getOperand(0) != Var)
00507       std::swap(Opnd0, Opnd1);
00508 
00509     ICmpInst *NewPreCond =
00510       cast<ICmpInst>(Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
00511     PreCond->replaceAllUsesWith(NewPreCond);
00512 
00513     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
00514   }
00515 
00516   // Step 3: Note that the population count is exactly the trip count of the
00517   // loop in question, which enble us to to convert the loop from noncountable
00518   // loop into a countable one. The benefit is twofold:
00519   //
00520   //  - If the loop only counts population, the entire loop become dead after
00521   //    the transformation. It is lots easier to prove a countable loop dead
00522   //    than to prove a noncountable one. (In some C dialects, a infite loop
00523   //    isn't dead even if it computes nothing useful. In general, DCE needs
00524   //    to prove a noncountable loop finite before safely delete it.)
00525   //
00526   //  - If the loop also performs something else, it remains alive.
00527   //    Since it is transformed to countable form, it can be aggressively
00528   //    optimized by some optimizations which are in general not applicable
00529   //    to a noncountable loop.
00530   //
00531   // After this step, this loop (conceptually) would look like following:
00532   //   newcnt = __builtin_ctpop(x);
00533   //   t = newcnt;
00534   //   if (x)
00535   //     do { cnt++; x &= x-1; t--) } while (t > 0);
00536   BasicBlock *Body = *(CurLoop->block_begin());
00537   {
00538     BranchInst *LbBr = LIRUtil::getBranch(Body);
00539     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
00540     Type *Ty = TripCnt->getType();
00541 
00542     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", Body->begin());
00543 
00544     Builder.SetInsertPoint(LbCond);
00545     Value *Opnd1 = cast<Value>(TcPhi);
00546     Value *Opnd2 = cast<Value>(ConstantInt::get(Ty, 1));
00547     Instruction *TcDec =
00548       cast<Instruction>(Builder.CreateSub(Opnd1, Opnd2, "tcdec", false, true));
00549 
00550     TcPhi->addIncoming(TripCnt, PreHead);
00551     TcPhi->addIncoming(TcDec, Body);
00552 
00553     CmpInst::Predicate Pred = (LbBr->getSuccessor(0) == Body) ?
00554       CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
00555     LbCond->setPredicate(Pred);
00556     LbCond->setOperand(0, TcDec);
00557     LbCond->setOperand(1, cast<Value>(ConstantInt::get(Ty, 0)));
00558   }
00559 
00560   // Step 4: All the references to the original population counter outside
00561   //  the loop are replaced with the NewCount -- the value returned from
00562   //  __builtin_ctpop().
00563   CntInst->replaceUsesOutsideBlock(NewCount, Body);
00564 
00565   // step 5: Forget the "non-computable" trip-count SCEV associated with the
00566   //   loop. The loop would otherwise not be deleted even if it becomes empty.
00567   SE->forgetLoop(CurLoop);
00568 }
00569 
00570 CallInst *NclPopcountRecognize::createPopcntIntrinsic(IRBuilderTy &IRBuilder,
00571                                                       Value *Val, DebugLoc DL) {
00572   Value *Ops[] = { Val };
00573   Type *Tys[] = { Val->getType() };
00574 
00575   Module *M = (*(CurLoop->block_begin()))->getParent()->getParent();
00576   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
00577   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
00578   CI->setDebugLoc(DL);
00579 
00580   return CI;
00581 }
00582 
00583 /// recognize - detect population count idiom in a non-countable loop. If
00584 ///   detected, transform the relevant code to popcount intrinsic function
00585 ///   call, and return true; otherwise, return false.
00586 bool NclPopcountRecognize::recognize() {
00587 
00588   if (!LIR.getTargetTransformInfo())
00589     return false;
00590 
00591   LIR.getScalarEvolution();
00592 
00593   if (!preliminaryScreen())
00594     return false;
00595 
00596   Instruction *CntInst;
00597   PHINode *CntPhi;
00598   Value *Val;
00599   if (!detectIdiom(CntInst, CntPhi, Val))
00600     return false;
00601 
00602   transform(CntInst, CntPhi, Val);
00603   return true;
00604 }
00605 
00606 //===----------------------------------------------------------------------===//
00607 //
00608 //          Implementation of LoopIdiomRecognize
00609 //
00610 //===----------------------------------------------------------------------===//
00611 
00612 bool LoopIdiomRecognize::runOnCountableLoop() {
00613   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
00614   if (isa<SCEVCouldNotCompute>(BECount)) return false;
00615 
00616   // If this loop executes exactly one time, then it should be peeled, not
00617   // optimized by this pass.
00618   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
00619     if (BECst->getValue()->getValue() == 0)
00620       return false;
00621 
00622   // set DT
00623   (void)getDominatorTree();
00624 
00625   LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00626   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00627 
00628   // set TLI
00629   (void)getTargetLibraryInfo();
00630 
00631   SmallVector<BasicBlock*, 8> ExitBlocks;
00632   CurLoop->getUniqueExitBlocks(ExitBlocks);
00633 
00634   DEBUG(dbgs() << "loop-idiom Scanning: F["
00635                << CurLoop->getHeader()->getParent()->getName()
00636                << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
00637 
00638   bool MadeChange = false;
00639   // Scan all the blocks in the loop that are not in subloops.
00640   for (Loop::block_iterator BI = CurLoop->block_begin(),
00641          E = CurLoop->block_end(); BI != E; ++BI) {
00642     // Ignore blocks in subloops.
00643     if (LI.getLoopFor(*BI) != CurLoop)
00644       continue;
00645 
00646     MadeChange |= runOnLoopBlock(*BI, BECount, ExitBlocks);
00647   }
00648   return MadeChange;
00649 }
00650 
00651 bool LoopIdiomRecognize::runOnNoncountableLoop() {
00652   NclPopcountRecognize Popcount(*this);
00653   if (Popcount.recognize())
00654     return true;
00655 
00656   return false;
00657 }
00658 
00659 bool LoopIdiomRecognize::runOnLoop(Loop *L, LPPassManager &LPM) {
00660   if (skipOptnoneFunction(L))
00661     return false;
00662 
00663   CurLoop = L;
00664 
00665   // If the loop could not be converted to canonical form, it must have an
00666   // indirectbr in it, just give up.
00667   if (!L->getLoopPreheader())
00668     return false;
00669 
00670   // Disable loop idiom recognition if the function's name is a common idiom.
00671   StringRef Name = L->getHeader()->getParent()->getName();
00672   if (Name == "memset" || Name == "memcpy")
00673     return false;
00674 
00675   SE = &getAnalysis<ScalarEvolution>();
00676   if (SE->hasLoopInvariantBackedgeTakenCount(L))
00677     return runOnCountableLoop();
00678   return runOnNoncountableLoop();
00679 }
00680 
00681 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
00682 /// with the specified backedge count.  This block is known to be in the current
00683 /// loop and not in any subloops.
00684 bool LoopIdiomRecognize::runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
00685                                      SmallVectorImpl<BasicBlock*> &ExitBlocks) {
00686   // We can only promote stores in this block if they are unconditionally
00687   // executed in the loop.  For a block to be unconditionally executed, it has
00688   // to dominate all the exit blocks of the loop.  Verify this now.
00689   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00690     if (!DT->dominates(BB, ExitBlocks[i]))
00691       return false;
00692 
00693   bool MadeChange = false;
00694   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
00695     Instruction *Inst = I++;
00696     // Look for store instructions, which may be optimized to memset/memcpy.
00697     if (StoreInst *SI = dyn_cast<StoreInst>(Inst))  {
00698       WeakVH InstPtr(I);
00699       if (!processLoopStore(SI, BECount)) continue;
00700       MadeChange = true;
00701 
00702       // If processing the store invalidated our iterator, start over from the
00703       // top of the block.
00704       if (!InstPtr)
00705         I = BB->begin();
00706       continue;
00707     }
00708 
00709     // Look for memset instructions, which may be optimized to a larger memset.
00710     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst))  {
00711       WeakVH InstPtr(I);
00712       if (!processLoopMemSet(MSI, BECount)) continue;
00713       MadeChange = true;
00714 
00715       // If processing the memset invalidated our iterator, start over from the
00716       // top of the block.
00717       if (!InstPtr)
00718         I = BB->begin();
00719       continue;
00720     }
00721   }
00722 
00723   return MadeChange;
00724 }
00725 
00726 
00727 /// processLoopStore - See if this store can be promoted to a memset or memcpy.
00728 bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
00729   if (!SI->isSimple()) return false;
00730 
00731   Value *StoredVal = SI->getValueOperand();
00732   Value *StorePtr = SI->getPointerOperand();
00733 
00734   // Reject stores that are so large that they overflow an unsigned.
00735   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
00736   uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
00737   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
00738     return false;
00739 
00740   // See if the pointer expression is an AddRec like {base,+,1} on the current
00741   // loop, which indicates a strided store.  If we have something else, it's a
00742   // random store we can't handle.
00743   const SCEVAddRecExpr *StoreEv =
00744     dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
00745   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
00746     return false;
00747 
00748   // Check to see if the stride matches the size of the store.  If so, then we
00749   // know that every byte is touched in the loop.
00750   unsigned StoreSize = (unsigned)SizeInBits >> 3;
00751   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
00752 
00753   if (!Stride || StoreSize != Stride->getValue()->getValue()) {
00754     // TODO: Could also handle negative stride here someday, that will require
00755     // the validity check in mayLoopAccessLocation to be updated though.
00756     // Enable this to print exact negative strides.
00757     if (0 && Stride && StoreSize == -Stride->getValue()->getValue()) {
00758       dbgs() << "NEGATIVE STRIDE: " << *SI << "\n";
00759       dbgs() << "BB: " << *SI->getParent();
00760     }
00761 
00762     return false;
00763   }
00764 
00765   // See if we can optimize just this store in isolation.
00766   if (processLoopStridedStore(StorePtr, StoreSize, SI->getAlignment(),
00767                               StoredVal, SI, StoreEv, BECount))
00768     return true;
00769 
00770   // If the stored value is a strided load in the same loop with the same stride
00771   // this this may be transformable into a memcpy.  This kicks in for stuff like
00772   //   for (i) A[i] = B[i];
00773   if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
00774     const SCEVAddRecExpr *LoadEv =
00775       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getOperand(0)));
00776     if (LoadEv && LoadEv->getLoop() == CurLoop && LoadEv->isAffine() &&
00777         StoreEv->getOperand(1) == LoadEv->getOperand(1) && LI->isSimple())
00778       if (processLoopStoreOfLoopLoad(SI, StoreSize, StoreEv, LoadEv, BECount))
00779         return true;
00780   }
00781   //errs() << "UNHANDLED strided store: " << *StoreEv << " - " << *SI << "\n";
00782 
00783   return false;
00784 }
00785 
00786 /// processLoopMemSet - See if this memset can be promoted to a large memset.
00787 bool LoopIdiomRecognize::
00788 processLoopMemSet(MemSetInst *MSI, const SCEV *BECount) {
00789   // We can only handle non-volatile memsets with a constant size.
00790   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength())) return false;
00791 
00792   // If we're not allowed to hack on memset, we fail.
00793   if (!TLI->has(LibFunc::memset))
00794     return false;
00795 
00796   Value *Pointer = MSI->getDest();
00797 
00798   // See if the pointer expression is an AddRec like {base,+,1} on the current
00799   // loop, which indicates a strided store.  If we have something else, it's a
00800   // random store we can't handle.
00801   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
00802   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
00803     return false;
00804 
00805   // Reject memsets that are so large that they overflow an unsigned.
00806   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
00807   if ((SizeInBytes >> 32) != 0)
00808     return false;
00809 
00810   // Check to see if the stride matches the size of the memset.  If so, then we
00811   // know that every byte is touched in the loop.
00812   const SCEVConstant *Stride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
00813 
00814   // TODO: Could also handle negative stride here someday, that will require the
00815   // validity check in mayLoopAccessLocation to be updated though.
00816   if (!Stride || MSI->getLength() != Stride->getValue())
00817     return false;
00818 
00819   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
00820                                  MSI->getAlignment(), MSI->getValue(),
00821                                  MSI, Ev, BECount);
00822 }
00823 
00824 
00825 /// mayLoopAccessLocation - Return true if the specified loop might access the
00826 /// specified pointer location, which is a loop-strided access.  The 'Access'
00827 /// argument specifies what the verboten forms of access are (read or write).
00828 static bool mayLoopAccessLocation(Value *Ptr,AliasAnalysis::ModRefResult Access,
00829                                   Loop *L, const SCEV *BECount,
00830                                   unsigned StoreSize, AliasAnalysis &AA,
00831                                   Instruction *IgnoredStore) {
00832   // Get the location that may be stored across the loop.  Since the access is
00833   // strided positively through memory, we say that the modified location starts
00834   // at the pointer and has infinite size.
00835   uint64_t AccessSize = AliasAnalysis::UnknownSize;
00836 
00837   // If the loop iterates a fixed number of times, we can refine the access size
00838   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
00839   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
00840     AccessSize = (BECst->getValue()->getZExtValue()+1)*StoreSize;
00841 
00842   // TODO: For this to be really effective, we have to dive into the pointer
00843   // operand in the store.  Store to &A[i] of 100 will always return may alias
00844   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
00845   // which will then no-alias a store to &A[100].
00846   AliasAnalysis::Location StoreLoc(Ptr, AccessSize);
00847 
00848   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
00849        ++BI)
00850     for (BasicBlock::iterator I = (*BI)->begin(), E = (*BI)->end(); I != E; ++I)
00851       if (&*I != IgnoredStore &&
00852           (AA.getModRefInfo(I, StoreLoc) & Access))
00853         return true;
00854 
00855   return false;
00856 }
00857 
00858 /// getMemSetPatternValue - If a strided store of the specified value is safe to
00859 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
00860 /// be passed in.  Otherwise, return null.
00861 ///
00862 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
00863 /// just replicate their input array and then pass on to memset_pattern16.
00864 static Constant *getMemSetPatternValue(Value *V, const DataLayout &DL) {
00865   // If the value isn't a constant, we can't promote it to being in a constant
00866   // array.  We could theoretically do a store to an alloca or something, but
00867   // that doesn't seem worthwhile.
00868   Constant *C = dyn_cast<Constant>(V);
00869   if (!C) return nullptr;
00870 
00871   // Only handle simple values that are a power of two bytes in size.
00872   uint64_t Size = DL.getTypeSizeInBits(V->getType());
00873   if (Size == 0 || (Size & 7) || (Size & (Size-1)))
00874     return nullptr;
00875 
00876   // Don't care enough about darwin/ppc to implement this.
00877   if (DL.isBigEndian())
00878     return nullptr;
00879 
00880   // Convert to size in bytes.
00881   Size /= 8;
00882 
00883   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
00884   // if the top and bottom are the same (e.g. for vectors and large integers).
00885   if (Size > 16) return nullptr;
00886 
00887   // If the constant is exactly 16 bytes, just use it.
00888   if (Size == 16) return C;
00889 
00890   // Otherwise, we'll use an array of the constants.
00891   unsigned ArraySize = 16/Size;
00892   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
00893   return ConstantArray::get(AT, std::vector<Constant*>(ArraySize, C));
00894 }
00895 
00896 
00897 /// processLoopStridedStore - We see a strided store of some value.  If we can
00898 /// transform this into a memset or memset_pattern in the loop preheader, do so.
00899 bool LoopIdiomRecognize::
00900 processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
00901                         unsigned StoreAlignment, Value *StoredVal,
00902                         Instruction *TheStore, const SCEVAddRecExpr *Ev,
00903                         const SCEV *BECount) {
00904 
00905   // If the stored value is a byte-wise value (like i32 -1), then it may be
00906   // turned into a memset of i8 -1, assuming that all the consecutive bytes
00907   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
00908   // but it can be turned into memset_pattern if the target supports it.
00909   Value *SplatValue = isBytewiseValue(StoredVal);
00910   Constant *PatternValue = nullptr;
00911   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
00912   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
00913 
00914   // If we're allowed to form a memset, and the stored value would be acceptable
00915   // for memset, use it.
00916   if (SplatValue && TLI->has(LibFunc::memset) &&
00917       // Verify that the stored value is loop invariant.  If not, we can't
00918       // promote the memset.
00919       CurLoop->isLoopInvariant(SplatValue)) {
00920     // Keep and use SplatValue.
00921     PatternValue = nullptr;
00922   } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
00923              (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
00924     // Don't create memset_pattern16s with address spaces.
00925     // It looks like we can use PatternValue!
00926     SplatValue = nullptr;
00927   } else {
00928     // Otherwise, this isn't an idiom we can transform.  For example, we can't
00929     // do anything with a 3-byte store.
00930     return false;
00931   }
00932 
00933   // The trip count of the loop and the base pointer of the addrec SCEV is
00934   // guaranteed to be loop invariant, which means that it should dominate the
00935   // header.  This allows us to insert code for it in the preheader.
00936   BasicBlock *Preheader = CurLoop->getLoopPreheader();
00937   IRBuilder<> Builder(Preheader->getTerminator());
00938   SCEVExpander Expander(*SE, "loop-idiom");
00939 
00940   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
00941 
00942   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
00943   // this into a memset in the loop preheader now if we want.  However, this
00944   // would be unsafe to do if there is anything else in the loop that may read
00945   // or write to the aliased location.  Check for any overlap by generating the
00946   // base pointer and checking the region.
00947   Value *BasePtr =
00948     Expander.expandCodeFor(Ev->getStart(), DestInt8PtrTy,
00949                            Preheader->getTerminator());
00950 
00951   if (mayLoopAccessLocation(BasePtr, AliasAnalysis::ModRef,
00952                             CurLoop, BECount,
00953                             StoreSize, getAnalysis<AliasAnalysis>(), TheStore)) {
00954     Expander.clear();
00955     // If we generated new code for the base pointer, clean up.
00956     RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
00957     return false;
00958   }
00959 
00960   // Okay, everything looks good, insert the memset.
00961 
00962   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
00963   // pointer size if it isn't already.
00964   Type *IntPtr = Builder.getIntPtrTy(&DL, DestAS);
00965   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
00966 
00967   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
00968                                          SCEV::FlagNUW);
00969   if (StoreSize != 1) {
00970     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
00971                                SCEV::FlagNUW);
00972   }
00973 
00974   Value *NumBytes =
00975     Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
00976 
00977   CallInst *NewCall;
00978   if (SplatValue) {
00979     NewCall = Builder.CreateMemSet(BasePtr,
00980                                    SplatValue,
00981                                    NumBytes,
00982                                    StoreAlignment);
00983   } else {
00984     // Everything is emitted in default address space
00985     Type *Int8PtrTy = DestInt8PtrTy;
00986 
00987     Module *M = TheStore->getParent()->getParent()->getParent();
00988     Value *MSP = M->getOrInsertFunction("memset_pattern16",
00989                                         Builder.getVoidTy(),
00990                                         Int8PtrTy,
00991                                         Int8PtrTy,
00992                                         IntPtr,
00993                                         (void*)nullptr);
00994 
00995     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
00996     // an constant array of 16-bytes.  Plop the value into a mergable global.
00997     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
00998                                             GlobalValue::PrivateLinkage,
00999                                             PatternValue, ".memset_pattern");
01000     GV->setUnnamedAddr(true); // Ok to merge these.
01001     GV->setAlignment(16);
01002     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
01003     NewCall = Builder.CreateCall3(MSP, BasePtr, PatternPtr, NumBytes);
01004   }
01005 
01006   DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
01007                << "    from store to: " << *Ev << " at: " << *TheStore << "\n");
01008   NewCall->setDebugLoc(TheStore->getDebugLoc());
01009 
01010   // Okay, the memset has been formed.  Zap the original store and anything that
01011   // feeds into it.
01012   deleteDeadInstruction(TheStore, TLI);
01013   ++NumMemSet;
01014   return true;
01015 }
01016 
01017 /// processLoopStoreOfLoopLoad - We see a strided store whose value is a
01018 /// same-strided load.
01019 bool LoopIdiomRecognize::
01020 processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
01021                            const SCEVAddRecExpr *StoreEv,
01022                            const SCEVAddRecExpr *LoadEv,
01023                            const SCEV *BECount) {
01024   // If we're not allowed to form memcpy, we fail.
01025   if (!TLI->has(LibFunc::memcpy))
01026     return false;
01027 
01028   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
01029 
01030   // The trip count of the loop and the base pointer of the addrec SCEV is
01031   // guaranteed to be loop invariant, which means that it should dominate the
01032   // header.  This allows us to insert code for it in the preheader.
01033   BasicBlock *Preheader = CurLoop->getLoopPreheader();
01034   IRBuilder<> Builder(Preheader->getTerminator());
01035   SCEVExpander Expander(*SE, "loop-idiom");
01036 
01037   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
01038   // this into a memcpy in the loop preheader now if we want.  However, this
01039   // would be unsafe to do if there is anything else in the loop that may read
01040   // or write the memory region we're storing to.  This includes the load that
01041   // feeds the stores.  Check for an alias by generating the base address and
01042   // checking everything.
01043   Value *StoreBasePtr =
01044     Expander.expandCodeFor(StoreEv->getStart(),
01045                            Builder.getInt8PtrTy(SI->getPointerAddressSpace()),
01046                            Preheader->getTerminator());
01047 
01048   if (mayLoopAccessLocation(StoreBasePtr, AliasAnalysis::ModRef,
01049                             CurLoop, BECount, StoreSize,
01050                             getAnalysis<AliasAnalysis>(), SI)) {
01051     Expander.clear();
01052     // If we generated new code for the base pointer, clean up.
01053     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
01054     return false;
01055   }
01056 
01057   // For a memcpy, we have to make sure that the input array is not being
01058   // mutated by the loop.
01059   Value *LoadBasePtr =
01060     Expander.expandCodeFor(LoadEv->getStart(),
01061                            Builder.getInt8PtrTy(LI->getPointerAddressSpace()),
01062                            Preheader->getTerminator());
01063 
01064   if (mayLoopAccessLocation(LoadBasePtr, AliasAnalysis::Mod, CurLoop, BECount,
01065                             StoreSize, getAnalysis<AliasAnalysis>(), SI)) {
01066     Expander.clear();
01067     // If we generated new code for the base pointer, clean up.
01068     RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
01069     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
01070     return false;
01071   }
01072 
01073   // Okay, everything is safe, we can transform this!
01074 
01075 
01076   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
01077   // pointer size if it isn't already.
01078   auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
01079   Type *IntPtrTy = Builder.getIntPtrTy(&DL, SI->getPointerAddressSpace());
01080   BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
01081 
01082   const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),
01083                                          SCEV::FlagNUW);
01084   if (StoreSize != 1)
01085     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
01086                                SCEV::FlagNUW);
01087 
01088   Value *NumBytes =
01089     Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
01090 
01091   CallInst *NewCall =
01092     Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes,
01093                          std::min(SI->getAlignment(), LI->getAlignment()));
01094   NewCall->setDebugLoc(SI->getDebugLoc());
01095 
01096   DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
01097                << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
01098                << "    from store ptr=" << *StoreEv << " at: " << *SI << "\n");
01099 
01100 
01101   // Okay, the memset has been formed.  Zap the original store and anything that
01102   // feeds into it.
01103   deleteDeadInstruction(SI, TLI);
01104   ++NumMemCpy;
01105   return true;
01106 }