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