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