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