1 //===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements an idiom recognizer that transforms simple loops into a
11 // non-loop form.  In cases that this kicks in, it can be a significant
12 // performance win.
13 //
14 // If compiling for code size we avoid idiom recognition if the resulting
15 // code could be larger than the code for the original loop. One way this could
16 // happen is if the loop is not removable after idiom recognition due to the
17 // presence of non-idiom instructions. The initial implementation of the
18 // heuristics applies to idioms in multi-block loops.
19 //
20 //===----------------------------------------------------------------------===//
21 //
22 // TODO List:
23 //
24 // Future loop memory idioms to recognize:
25 //   memcmp, memmove, strlen, etc.
26 // Future floating point idioms to recognize in -ffast-math mode:
27 //   fpowi
28 // Future integer operation idioms to recognize:
29 //   ctpop, ctlz, cttz
30 //
31 // Beware that isel's default lowering for ctpop is highly inefficient for
32 // i64 and larger types when i64 is legal and the value has few bits set.  It
33 // would be good to enhance isel to emit a loop for ctpop in this case.
34 //
35 // This could recognize common matrix multiplies and dot product idioms and
36 // replace them with calls to BLAS (if linked in??).
37 //
38 //===----------------------------------------------------------------------===//
39 
40 #include "llvm/ADT/APInt.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/MapVector.h"
44 #include "llvm/ADT/SetVector.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/ADT/StringRef.h"
49 #include "llvm/Analysis/AliasAnalysis.h"
50 #include "llvm/Analysis/LoopAccessAnalysis.h"
51 #include "llvm/Analysis/LoopInfo.h"
52 #include "llvm/Analysis/LoopPass.h"
53 #include "llvm/Analysis/MemoryLocation.h"
54 #include "llvm/Analysis/ScalarEvolution.h"
55 #include "llvm/Analysis/ScalarEvolutionExpander.h"
56 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
57 #include "llvm/Analysis/TargetLibraryInfo.h"
58 #include "llvm/Analysis/TargetTransformInfo.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include "llvm/Analysis/ValueTracking.h"
61 #include "llvm/IR/Attributes.h"
62 #include "llvm/IR/BasicBlock.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugLoc.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/Dominators.h"
69 #include "llvm/IR/GlobalValue.h"
70 #include "llvm/IR/GlobalVariable.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/InstrTypes.h"
73 #include "llvm/IR/Instruction.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/LLVMContext.h"
78 #include "llvm/IR/Module.h"
79 #include "llvm/IR/PassManager.h"
80 #include "llvm/IR/Type.h"
81 #include "llvm/IR/User.h"
82 #include "llvm/IR/Value.h"
83 #include "llvm/IR/ValueHandle.h"
84 #include "llvm/Pass.h"
85 #include "llvm/Support/Casting.h"
86 #include "llvm/Support/CommandLine.h"
87 #include "llvm/Support/Debug.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Scalar.h"
90 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
91 #include "llvm/Transforms/Utils/BuildLibCalls.h"
92 #include "llvm/Transforms/Utils/LoopUtils.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <utility>
97 #include <vector>
98 
99 using namespace llvm;
100 
101 #define DEBUG_TYPE "loop-idiom"
102 
103 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
104 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
105 
106 static cl::opt<bool> UseLIRCodeSizeHeurs(
107     "use-lir-code-size-heurs",
108     cl::desc("Use loop idiom recognition code size heuristics when compiling"
109              "with -Os/-Oz"),
110     cl::init(true), cl::Hidden);
111 
112 namespace {
113 
114 class LoopIdiomRecognize {
115   Loop *CurLoop = nullptr;
116   AliasAnalysis *AA;
117   DominatorTree *DT;
118   LoopInfo *LI;
119   ScalarEvolution *SE;
120   TargetLibraryInfo *TLI;
121   const TargetTransformInfo *TTI;
122   const DataLayout *DL;
123   bool ApplyCodeSizeHeuristics;
124 
125 public:
126   explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
127                               LoopInfo *LI, ScalarEvolution *SE,
128                               TargetLibraryInfo *TLI,
129                               const TargetTransformInfo *TTI,
130                               const DataLayout *DL)
131       : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL) {}
132 
133   bool runOnLoop(Loop *L);
134 
135 private:
136   using StoreList = SmallVector<StoreInst *, 8>;
137   using StoreListMap = MapVector<Value *, StoreList>;
138 
139   StoreListMap StoreRefsForMemset;
140   StoreListMap StoreRefsForMemsetPattern;
141   StoreList StoreRefsForMemcpy;
142   bool HasMemset;
143   bool HasMemsetPattern;
144   bool HasMemcpy;
145 
146   /// Return code for isLegalStore()
147   enum LegalStoreKind {
148     None = 0,
149     Memset,
150     MemsetPattern,
151     Memcpy,
152     UnorderedAtomicMemcpy,
153     DontUse // Dummy retval never to be used. Allows catching errors in retval
154             // handling.
155   };
156 
157   /// \name Countable Loop Idiom Handling
158   /// @{
159 
160   bool runOnCountableLoop();
161   bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
162                       SmallVectorImpl<BasicBlock *> &ExitBlocks);
163 
164   void collectStores(BasicBlock *BB);
165   LegalStoreKind isLegalStore(StoreInst *SI);
166   enum class ForMemset { No, Yes };
167   bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
168                          ForMemset For);
169   bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
170 
171   bool processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
172                                unsigned StoreAlignment, Value *StoredVal,
173                                Instruction *TheStore,
174                                SmallPtrSetImpl<Instruction *> &Stores,
175                                const SCEVAddRecExpr *Ev, const SCEV *BECount,
176                                bool NegStride, bool IsLoopMemset = false);
177   bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
178   bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
179                                  bool IsLoopMemset = false);
180 
181   /// @}
182   /// \name Noncountable Loop Idiom Handling
183   /// @{
184 
185   bool runOnNoncountableLoop();
186 
187   bool recognizePopcount();
188   void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
189                                PHINode *CntPhi, Value *Var);
190   bool recognizeAndInsertCTLZ();
191   void transformLoopToCountable(BasicBlock *PreCondBB, Instruction *CntInst,
192                                 PHINode *CntPhi, Value *Var, Instruction *DefX,
193                                 const DebugLoc &DL, bool ZeroCheck,
194                                 bool IsCntPhiUsedOutsideLoop);
195 
196   /// @}
197 };
198 
199 class LoopIdiomRecognizeLegacyPass : public LoopPass {
200 public:
201   static char ID;
202 
203   explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
204     initializeLoopIdiomRecognizeLegacyPassPass(
205         *PassRegistry::getPassRegistry());
206   }
207 
208   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
209     if (skipLoop(L))
210       return false;
211 
212     AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
213     DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
214     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
215     ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
216     TargetLibraryInfo *TLI =
217         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
218     const TargetTransformInfo *TTI =
219         &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
220             *L->getHeader()->getParent());
221     const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
222 
223     LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
224     return LIR.runOnLoop(L);
225   }
226 
227   /// This transformation requires natural loop information & requires that
228   /// loop preheaders be inserted into the CFG.
229   void getAnalysisUsage(AnalysisUsage &AU) const override {
230     AU.addRequired<TargetLibraryInfoWrapperPass>();
231     AU.addRequired<TargetTransformInfoWrapperPass>();
232     getLoopAnalysisUsage(AU);
233   }
234 };
235 
236 } // end anonymous namespace
237 
238 char LoopIdiomRecognizeLegacyPass::ID = 0;
239 
240 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
241                                               LoopStandardAnalysisResults &AR,
242                                               LPMUpdater &) {
243   const auto *DL = &L.getHeader()->getModule()->getDataLayout();
244 
245   LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI, DL);
246   if (!LIR.runOnLoop(&L))
247     return PreservedAnalyses::all();
248 
249   return getLoopPassPreservedAnalyses();
250 }
251 
252 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
253                       "Recognize loop idioms", false, false)
254 INITIALIZE_PASS_DEPENDENCY(LoopPass)
255 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
256 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
257 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
258                     "Recognize loop idioms", false, false)
259 
260 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
261 
262 static void deleteDeadInstruction(Instruction *I) {
263   I->replaceAllUsesWith(UndefValue::get(I->getType()));
264   I->eraseFromParent();
265 }
266 
267 //===----------------------------------------------------------------------===//
268 //
269 //          Implementation of LoopIdiomRecognize
270 //
271 //===----------------------------------------------------------------------===//
272 
273 bool LoopIdiomRecognize::runOnLoop(Loop *L) {
274   CurLoop = L;
275   // If the loop could not be converted to canonical form, it must have an
276   // indirectbr in it, just give up.
277   if (!L->getLoopPreheader())
278     return false;
279 
280   // Disable loop idiom recognition if the function's name is a common idiom.
281   StringRef Name = L->getHeader()->getParent()->getName();
282   if (Name == "memset" || Name == "memcpy")
283     return false;
284 
285   // Determine if code size heuristics need to be applied.
286   ApplyCodeSizeHeuristics =
287       L->getHeader()->getParent()->optForSize() && UseLIRCodeSizeHeurs;
288 
289   HasMemset = TLI->has(LibFunc_memset);
290   HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
291   HasMemcpy = TLI->has(LibFunc_memcpy);
292 
293   if (HasMemset || HasMemsetPattern || HasMemcpy)
294     if (SE->hasLoopInvariantBackedgeTakenCount(L))
295       return runOnCountableLoop();
296 
297   return runOnNoncountableLoop();
298 }
299 
300 bool LoopIdiomRecognize::runOnCountableLoop() {
301   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
302   assert(!isa<SCEVCouldNotCompute>(BECount) &&
303          "runOnCountableLoop() called on a loop without a predictable"
304          "backedge-taken count");
305 
306   // If this loop executes exactly one time, then it should be peeled, not
307   // optimized by this pass.
308   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
309     if (BECst->getAPInt() == 0)
310       return false;
311 
312   SmallVector<BasicBlock *, 8> ExitBlocks;
313   CurLoop->getUniqueExitBlocks(ExitBlocks);
314 
315   LLVM_DEBUG(dbgs() << "loop-idiom Scanning: F["
316                     << CurLoop->getHeader()->getParent()->getName()
317                     << "] Loop %" << CurLoop->getHeader()->getName() << "\n");
318 
319   bool MadeChange = false;
320 
321   // The following transforms hoist stores/memsets into the loop pre-header.
322   // Give up if the loop has instructions may throw.
323   LoopSafetyInfo SafetyInfo;
324   SafetyInfo.computeLoopSafetyInfo(CurLoop);
325   if (SafetyInfo.anyBlockMayThrow())
326     return MadeChange;
327 
328   // Scan all the blocks in the loop that are not in subloops.
329   for (auto *BB : CurLoop->getBlocks()) {
330     // Ignore blocks in subloops.
331     if (LI->getLoopFor(BB) != CurLoop)
332       continue;
333 
334     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
335   }
336   return MadeChange;
337 }
338 
339 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
340   const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
341   return ConstStride->getAPInt();
342 }
343 
344 /// getMemSetPatternValue - If a strided store of the specified value is safe to
345 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
346 /// be passed in.  Otherwise, return null.
347 ///
348 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
349 /// just replicate their input array and then pass on to memset_pattern16.
350 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
351   // FIXME: This could check for UndefValue because it can be merged into any
352   // other valid pattern.
353 
354   // If the value isn't a constant, we can't promote it to being in a constant
355   // array.  We could theoretically do a store to an alloca or something, but
356   // that doesn't seem worthwhile.
357   Constant *C = dyn_cast<Constant>(V);
358   if (!C)
359     return nullptr;
360 
361   // Only handle simple values that are a power of two bytes in size.
362   uint64_t Size = DL->getTypeSizeInBits(V->getType());
363   if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
364     return nullptr;
365 
366   // Don't care enough about darwin/ppc to implement this.
367   if (DL->isBigEndian())
368     return nullptr;
369 
370   // Convert to size in bytes.
371   Size /= 8;
372 
373   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
374   // if the top and bottom are the same (e.g. for vectors and large integers).
375   if (Size > 16)
376     return nullptr;
377 
378   // If the constant is exactly 16 bytes, just use it.
379   if (Size == 16)
380     return C;
381 
382   // Otherwise, we'll use an array of the constants.
383   unsigned ArraySize = 16 / Size;
384   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
385   return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
386 }
387 
388 LoopIdiomRecognize::LegalStoreKind
389 LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
390   // Don't touch volatile stores.
391   if (SI->isVolatile())
392     return LegalStoreKind::None;
393   // We only want simple or unordered-atomic stores.
394   if (!SI->isUnordered())
395     return LegalStoreKind::None;
396 
397   // Don't convert stores of non-integral pointer types to memsets (which stores
398   // integers).
399   if (DL->isNonIntegralPointerType(SI->getValueOperand()->getType()))
400     return LegalStoreKind::None;
401 
402   // Avoid merging nontemporal stores.
403   if (SI->getMetadata(LLVMContext::MD_nontemporal))
404     return LegalStoreKind::None;
405 
406   Value *StoredVal = SI->getValueOperand();
407   Value *StorePtr = SI->getPointerOperand();
408 
409   // Reject stores that are so large that they overflow an unsigned.
410   uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
411   if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
412     return LegalStoreKind::None;
413 
414   // See if the pointer expression is an AddRec like {base,+,1} on the current
415   // loop, which indicates a strided store.  If we have something else, it's a
416   // random store we can't handle.
417   const SCEVAddRecExpr *StoreEv =
418       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
419   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
420     return LegalStoreKind::None;
421 
422   // Check to see if we have a constant stride.
423   if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
424     return LegalStoreKind::None;
425 
426   // See if the store can be turned into a memset.
427 
428   // If the stored value is a byte-wise value (like i32 -1), then it may be
429   // turned into a memset of i8 -1, assuming that all the consecutive bytes
430   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
431   // but it can be turned into memset_pattern if the target supports it.
432   Value *SplatValue = isBytewiseValue(StoredVal);
433   Constant *PatternValue = nullptr;
434 
435   // Note: memset and memset_pattern on unordered-atomic is yet not supported
436   bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
437 
438   // If we're allowed to form a memset, and the stored value would be
439   // acceptable for memset, use it.
440   if (!UnorderedAtomic && HasMemset && SplatValue &&
441       // Verify that the stored value is loop invariant.  If not, we can't
442       // promote the memset.
443       CurLoop->isLoopInvariant(SplatValue)) {
444     // It looks like we can use SplatValue.
445     return LegalStoreKind::Memset;
446   } else if (!UnorderedAtomic && HasMemsetPattern &&
447              // Don't create memset_pattern16s with address spaces.
448              StorePtr->getType()->getPointerAddressSpace() == 0 &&
449              (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
450     // It looks like we can use PatternValue!
451     return LegalStoreKind::MemsetPattern;
452   }
453 
454   // Otherwise, see if the store can be turned into a memcpy.
455   if (HasMemcpy) {
456     // Check to see if the stride matches the size of the store.  If so, then we
457     // know that every byte is touched in the loop.
458     APInt Stride = getStoreStride(StoreEv);
459     unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
460     if (StoreSize != Stride && StoreSize != -Stride)
461       return LegalStoreKind::None;
462 
463     // The store must be feeding a non-volatile load.
464     LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
465 
466     // Only allow non-volatile loads
467     if (!LI || LI->isVolatile())
468       return LegalStoreKind::None;
469     // Only allow simple or unordered-atomic loads
470     if (!LI->isUnordered())
471       return LegalStoreKind::None;
472 
473     // See if the pointer expression is an AddRec like {base,+,1} on the current
474     // loop, which indicates a strided load.  If we have something else, it's a
475     // random load we can't handle.
476     const SCEVAddRecExpr *LoadEv =
477         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
478     if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
479       return LegalStoreKind::None;
480 
481     // The store and load must share the same stride.
482     if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
483       return LegalStoreKind::None;
484 
485     // Success.  This store can be converted into a memcpy.
486     UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
487     return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
488                            : LegalStoreKind::Memcpy;
489   }
490   // This store can't be transformed into a memset/memcpy.
491   return LegalStoreKind::None;
492 }
493 
494 void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
495   StoreRefsForMemset.clear();
496   StoreRefsForMemsetPattern.clear();
497   StoreRefsForMemcpy.clear();
498   for (Instruction &I : *BB) {
499     StoreInst *SI = dyn_cast<StoreInst>(&I);
500     if (!SI)
501       continue;
502 
503     // Make sure this is a strided store with a constant stride.
504     switch (isLegalStore(SI)) {
505     case LegalStoreKind::None:
506       // Nothing to do
507       break;
508     case LegalStoreKind::Memset: {
509       // Find the base pointer.
510       Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
511       StoreRefsForMemset[Ptr].push_back(SI);
512     } break;
513     case LegalStoreKind::MemsetPattern: {
514       // Find the base pointer.
515       Value *Ptr = GetUnderlyingObject(SI->getPointerOperand(), *DL);
516       StoreRefsForMemsetPattern[Ptr].push_back(SI);
517     } break;
518     case LegalStoreKind::Memcpy:
519     case LegalStoreKind::UnorderedAtomicMemcpy:
520       StoreRefsForMemcpy.push_back(SI);
521       break;
522     default:
523       assert(false && "unhandled return value");
524       break;
525     }
526   }
527 }
528 
529 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
530 /// with the specified backedge count.  This block is known to be in the current
531 /// loop and not in any subloops.
532 bool LoopIdiomRecognize::runOnLoopBlock(
533     BasicBlock *BB, const SCEV *BECount,
534     SmallVectorImpl<BasicBlock *> &ExitBlocks) {
535   // We can only promote stores in this block if they are unconditionally
536   // executed in the loop.  For a block to be unconditionally executed, it has
537   // to dominate all the exit blocks of the loop.  Verify this now.
538   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
539     if (!DT->dominates(BB, ExitBlocks[i]))
540       return false;
541 
542   bool MadeChange = false;
543   // Look for store instructions, which may be optimized to memset/memcpy.
544   collectStores(BB);
545 
546   // Look for a single store or sets of stores with a common base, which can be
547   // optimized into a memset (memset_pattern).  The latter most commonly happens
548   // with structs and handunrolled loops.
549   for (auto &SL : StoreRefsForMemset)
550     MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
551 
552   for (auto &SL : StoreRefsForMemsetPattern)
553     MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
554 
555   // Optimize the store into a memcpy, if it feeds an similarly strided load.
556   for (auto &SI : StoreRefsForMemcpy)
557     MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
558 
559   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
560     Instruction *Inst = &*I++;
561     // Look for memset instructions, which may be optimized to a larger memset.
562     if (MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
563       WeakTrackingVH InstPtr(&*I);
564       if (!processLoopMemSet(MSI, BECount))
565         continue;
566       MadeChange = true;
567 
568       // If processing the memset invalidated our iterator, start over from the
569       // top of the block.
570       if (!InstPtr)
571         I = BB->begin();
572       continue;
573     }
574   }
575 
576   return MadeChange;
577 }
578 
579 /// See if this store(s) can be promoted to a memset.
580 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
581                                            const SCEV *BECount, ForMemset For) {
582   // Try to find consecutive stores that can be transformed into memsets.
583   SetVector<StoreInst *> Heads, Tails;
584   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
585 
586   // Do a quadratic search on all of the given stores and find
587   // all of the pairs of stores that follow each other.
588   SmallVector<unsigned, 16> IndexQueue;
589   for (unsigned i = 0, e = SL.size(); i < e; ++i) {
590     assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
591 
592     Value *FirstStoredVal = SL[i]->getValueOperand();
593     Value *FirstStorePtr = SL[i]->getPointerOperand();
594     const SCEVAddRecExpr *FirstStoreEv =
595         cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
596     APInt FirstStride = getStoreStride(FirstStoreEv);
597     unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
598 
599     // See if we can optimize just this store in isolation.
600     if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
601       Heads.insert(SL[i]);
602       continue;
603     }
604 
605     Value *FirstSplatValue = nullptr;
606     Constant *FirstPatternValue = nullptr;
607 
608     if (For == ForMemset::Yes)
609       FirstSplatValue = isBytewiseValue(FirstStoredVal);
610     else
611       FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
612 
613     assert((FirstSplatValue || FirstPatternValue) &&
614            "Expected either splat value or pattern value.");
615 
616     IndexQueue.clear();
617     // If a store has multiple consecutive store candidates, search Stores
618     // array according to the sequence: from i+1 to e, then from i-1 to 0.
619     // This is because usually pairing with immediate succeeding or preceding
620     // candidate create the best chance to find memset opportunity.
621     unsigned j = 0;
622     for (j = i + 1; j < e; ++j)
623       IndexQueue.push_back(j);
624     for (j = i; j > 0; --j)
625       IndexQueue.push_back(j - 1);
626 
627     for (auto &k : IndexQueue) {
628       assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
629       Value *SecondStorePtr = SL[k]->getPointerOperand();
630       const SCEVAddRecExpr *SecondStoreEv =
631           cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
632       APInt SecondStride = getStoreStride(SecondStoreEv);
633 
634       if (FirstStride != SecondStride)
635         continue;
636 
637       Value *SecondStoredVal = SL[k]->getValueOperand();
638       Value *SecondSplatValue = nullptr;
639       Constant *SecondPatternValue = nullptr;
640 
641       if (For == ForMemset::Yes)
642         SecondSplatValue = isBytewiseValue(SecondStoredVal);
643       else
644         SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
645 
646       assert((SecondSplatValue || SecondPatternValue) &&
647              "Expected either splat value or pattern value.");
648 
649       if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
650         if (For == ForMemset::Yes) {
651           if (isa<UndefValue>(FirstSplatValue))
652             FirstSplatValue = SecondSplatValue;
653           if (FirstSplatValue != SecondSplatValue)
654             continue;
655         } else {
656           if (isa<UndefValue>(FirstPatternValue))
657             FirstPatternValue = SecondPatternValue;
658           if (FirstPatternValue != SecondPatternValue)
659             continue;
660         }
661         Tails.insert(SL[k]);
662         Heads.insert(SL[i]);
663         ConsecutiveChain[SL[i]] = SL[k];
664         break;
665       }
666     }
667   }
668 
669   // We may run into multiple chains that merge into a single chain. We mark the
670   // stores that we transformed so that we don't visit the same store twice.
671   SmallPtrSet<Value *, 16> TransformedStores;
672   bool Changed = false;
673 
674   // For stores that start but don't end a link in the chain:
675   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
676        it != e; ++it) {
677     if (Tails.count(*it))
678       continue;
679 
680     // We found a store instr that starts a chain. Now follow the chain and try
681     // to transform it.
682     SmallPtrSet<Instruction *, 8> AdjacentStores;
683     StoreInst *I = *it;
684 
685     StoreInst *HeadStore = I;
686     unsigned StoreSize = 0;
687 
688     // Collect the chain into a list.
689     while (Tails.count(I) || Heads.count(I)) {
690       if (TransformedStores.count(I))
691         break;
692       AdjacentStores.insert(I);
693 
694       StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
695       // Move to the next value in the chain.
696       I = ConsecutiveChain[I];
697     }
698 
699     Value *StoredVal = HeadStore->getValueOperand();
700     Value *StorePtr = HeadStore->getPointerOperand();
701     const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
702     APInt Stride = getStoreStride(StoreEv);
703 
704     // Check to see if the stride matches the size of the stores.  If so, then
705     // we know that every byte is touched in the loop.
706     if (StoreSize != Stride && StoreSize != -Stride)
707       continue;
708 
709     bool NegStride = StoreSize == -Stride;
710 
711     if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->getAlignment(),
712                                 StoredVal, HeadStore, AdjacentStores, StoreEv,
713                                 BECount, NegStride)) {
714       TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
715       Changed = true;
716     }
717   }
718 
719   return Changed;
720 }
721 
722 /// processLoopMemSet - See if this memset can be promoted to a large memset.
723 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
724                                            const SCEV *BECount) {
725   // We can only handle non-volatile memsets with a constant size.
726   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
727     return false;
728 
729   // If we're not allowed to hack on memset, we fail.
730   if (!HasMemset)
731     return false;
732 
733   Value *Pointer = MSI->getDest();
734 
735   // See if the pointer expression is an AddRec like {base,+,1} on the current
736   // loop, which indicates a strided store.  If we have something else, it's a
737   // random store we can't handle.
738   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
739   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
740     return false;
741 
742   // Reject memsets that are so large that they overflow an unsigned.
743   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
744   if ((SizeInBytes >> 32) != 0)
745     return false;
746 
747   // Check to see if the stride matches the size of the memset.  If so, then we
748   // know that every byte is touched in the loop.
749   const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
750   if (!ConstStride)
751     return false;
752 
753   APInt Stride = ConstStride->getAPInt();
754   if (SizeInBytes != Stride && SizeInBytes != -Stride)
755     return false;
756 
757   // Verify that the memset value is loop invariant.  If not, we can't promote
758   // the memset.
759   Value *SplatValue = MSI->getValue();
760   if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
761     return false;
762 
763   SmallPtrSet<Instruction *, 1> MSIs;
764   MSIs.insert(MSI);
765   bool NegStride = SizeInBytes == -Stride;
766   return processLoopStridedStore(Pointer, (unsigned)SizeInBytes,
767                                  MSI->getDestAlignment(), SplatValue, MSI, MSIs,
768                                  Ev, BECount, NegStride, /*IsLoopMemset=*/true);
769 }
770 
771 /// mayLoopAccessLocation - Return true if the specified loop might access the
772 /// specified pointer location, which is a loop-strided access.  The 'Access'
773 /// argument specifies what the verboten forms of access are (read or write).
774 static bool
775 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
776                       const SCEV *BECount, unsigned StoreSize,
777                       AliasAnalysis &AA,
778                       SmallPtrSetImpl<Instruction *> &IgnoredStores) {
779   // Get the location that may be stored across the loop.  Since the access is
780   // strided positively through memory, we say that the modified location starts
781   // at the pointer and has infinite size.
782   uint64_t AccessSize = MemoryLocation::UnknownSize;
783 
784   // If the loop iterates a fixed number of times, we can refine the access size
785   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
786   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
787     AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
788 
789   // TODO: For this to be really effective, we have to dive into the pointer
790   // operand in the store.  Store to &A[i] of 100 will always return may alias
791   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
792   // which will then no-alias a store to &A[100].
793   MemoryLocation StoreLoc(Ptr, AccessSize);
794 
795   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
796        ++BI)
797     for (Instruction &I : **BI)
798       if (IgnoredStores.count(&I) == 0 &&
799           isModOrRefSet(
800               intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
801         return true;
802 
803   return false;
804 }
805 
806 // If we have a negative stride, Start refers to the end of the memory location
807 // we're trying to memset.  Therefore, we need to recompute the base pointer,
808 // which is just Start - BECount*Size.
809 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
810                                         Type *IntPtr, unsigned StoreSize,
811                                         ScalarEvolution *SE) {
812   const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
813   if (StoreSize != 1)
814     Index = SE->getMulExpr(Index, SE->getConstant(IntPtr, StoreSize),
815                            SCEV::FlagNUW);
816   return SE->getMinusSCEV(Start, Index);
817 }
818 
819 /// Compute the number of bytes as a SCEV from the backedge taken count.
820 ///
821 /// This also maps the SCEV into the provided type and tries to handle the
822 /// computation in a way that will fold cleanly.
823 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
824                                unsigned StoreSize, Loop *CurLoop,
825                                const DataLayout *DL, ScalarEvolution *SE) {
826   const SCEV *NumBytesS;
827   // The # stored bytes is (BECount+1)*Size.  Expand the trip count out to
828   // pointer size if it isn't already.
829   //
830   // If we're going to need to zero extend the BE count, check if we can add
831   // one to it prior to zero extending without overflow. Provided this is safe,
832   // it allows better simplification of the +1.
833   if (DL->getTypeSizeInBits(BECount->getType()) <
834           DL->getTypeSizeInBits(IntPtr) &&
835       SE->isLoopEntryGuardedByCond(
836           CurLoop, ICmpInst::ICMP_NE, BECount,
837           SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
838     NumBytesS = SE->getZeroExtendExpr(
839         SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
840         IntPtr);
841   } else {
842     NumBytesS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
843                                SE->getOne(IntPtr), SCEV::FlagNUW);
844   }
845 
846   // And scale it based on the store size.
847   if (StoreSize != 1) {
848     NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtr, StoreSize),
849                                SCEV::FlagNUW);
850   }
851   return NumBytesS;
852 }
853 
854 /// processLoopStridedStore - We see a strided store of some value.  If we can
855 /// transform this into a memset or memset_pattern in the loop preheader, do so.
856 bool LoopIdiomRecognize::processLoopStridedStore(
857     Value *DestPtr, unsigned StoreSize, unsigned StoreAlignment,
858     Value *StoredVal, Instruction *TheStore,
859     SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
860     const SCEV *BECount, bool NegStride, bool IsLoopMemset) {
861   Value *SplatValue = isBytewiseValue(StoredVal);
862   Constant *PatternValue = nullptr;
863 
864   if (!SplatValue)
865     PatternValue = getMemSetPatternValue(StoredVal, DL);
866 
867   assert((SplatValue || PatternValue) &&
868          "Expected either splat value or pattern value.");
869 
870   // The trip count of the loop and the base pointer of the addrec SCEV is
871   // guaranteed to be loop invariant, which means that it should dominate the
872   // header.  This allows us to insert code for it in the preheader.
873   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
874   BasicBlock *Preheader = CurLoop->getLoopPreheader();
875   IRBuilder<> Builder(Preheader->getTerminator());
876   SCEVExpander Expander(*SE, *DL, "loop-idiom");
877 
878   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
879   Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
880 
881   const SCEV *Start = Ev->getStart();
882   // Handle negative strided loops.
883   if (NegStride)
884     Start = getStartForNegStride(Start, BECount, IntPtr, StoreSize, SE);
885 
886   // TODO: ideally we should still be able to generate memset if SCEV expander
887   // is taught to generate the dependencies at the latest point.
888   if (!isSafeToExpand(Start, *SE))
889     return false;
890 
891   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
892   // this into a memset in the loop preheader now if we want.  However, this
893   // would be unsafe to do if there is anything else in the loop that may read
894   // or write to the aliased location.  Check for any overlap by generating the
895   // base pointer and checking the region.
896   Value *BasePtr =
897       Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
898   if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
899                             StoreSize, *AA, Stores)) {
900     Expander.clear();
901     // If we generated new code for the base pointer, clean up.
902     RecursivelyDeleteTriviallyDeadInstructions(BasePtr, TLI);
903     return false;
904   }
905 
906   if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
907     return false;
908 
909   // Okay, everything looks good, insert the memset.
910 
911   const SCEV *NumBytesS =
912       getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE);
913 
914   // TODO: ideally we should still be able to generate memset if SCEV expander
915   // is taught to generate the dependencies at the latest point.
916   if (!isSafeToExpand(NumBytesS, *SE))
917     return false;
918 
919   Value *NumBytes =
920       Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->getTerminator());
921 
922   CallInst *NewCall;
923   if (SplatValue) {
924     NewCall =
925         Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
926   } else {
927     // Everything is emitted in default address space
928     Type *Int8PtrTy = DestInt8PtrTy;
929 
930     Module *M = TheStore->getModule();
931     Value *MSP =
932         M->getOrInsertFunction("memset_pattern16", Builder.getVoidTy(),
933                                Int8PtrTy, Int8PtrTy, IntPtr);
934     inferLibFuncAttributes(M->getFunction("memset_pattern16"), *TLI);
935 
936     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
937     // an constant array of 16-bytes.  Plop the value into a mergable global.
938     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
939                                             GlobalValue::PrivateLinkage,
940                                             PatternValue, ".memset_pattern");
941     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
942     GV->setAlignment(16);
943     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
944     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
945   }
946 
947   LLVM_DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
948                     << "    from store to: " << *Ev << " at: " << *TheStore
949                     << "\n");
950   NewCall->setDebugLoc(TheStore->getDebugLoc());
951 
952   // Okay, the memset has been formed.  Zap the original store and anything that
953   // feeds into it.
954   for (auto *I : Stores)
955     deleteDeadInstruction(I);
956   ++NumMemSet;
957   return true;
958 }
959 
960 /// If the stored value is a strided load in the same loop with the same stride
961 /// this may be transformable into a memcpy.  This kicks in for stuff like
962 /// for (i) A[i] = B[i];
963 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
964                                                     const SCEV *BECount) {
965   assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
966 
967   Value *StorePtr = SI->getPointerOperand();
968   const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
969   APInt Stride = getStoreStride(StoreEv);
970   unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
971   bool NegStride = StoreSize == -Stride;
972 
973   // The store must be feeding a non-volatile load.
974   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
975   assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
976 
977   // See if the pointer expression is an AddRec like {base,+,1} on the current
978   // loop, which indicates a strided load.  If we have something else, it's a
979   // random load we can't handle.
980   const SCEVAddRecExpr *LoadEv =
981       cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
982 
983   // The trip count of the loop and the base pointer of the addrec SCEV is
984   // guaranteed to be loop invariant, which means that it should dominate the
985   // header.  This allows us to insert code for it in the preheader.
986   BasicBlock *Preheader = CurLoop->getLoopPreheader();
987   IRBuilder<> Builder(Preheader->getTerminator());
988   SCEVExpander Expander(*SE, *DL, "loop-idiom");
989 
990   const SCEV *StrStart = StoreEv->getStart();
991   unsigned StrAS = SI->getPointerAddressSpace();
992   Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
993 
994   // Handle negative strided loops.
995   if (NegStride)
996     StrStart = getStartForNegStride(StrStart, BECount, IntPtrTy, StoreSize, SE);
997 
998   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
999   // this into a memcpy in the loop preheader now if we want.  However, this
1000   // would be unsafe to do if there is anything else in the loop that may read
1001   // or write the memory region we're storing to.  This includes the load that
1002   // feeds the stores.  Check for an alias by generating the base address and
1003   // checking everything.
1004   Value *StoreBasePtr = Expander.expandCodeFor(
1005       StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
1006 
1007   SmallPtrSet<Instruction *, 1> Stores;
1008   Stores.insert(SI);
1009   if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1010                             StoreSize, *AA, Stores)) {
1011     Expander.clear();
1012     // If we generated new code for the base pointer, clean up.
1013     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1014     return false;
1015   }
1016 
1017   const SCEV *LdStart = LoadEv->getStart();
1018   unsigned LdAS = LI->getPointerAddressSpace();
1019 
1020   // Handle negative strided loops.
1021   if (NegStride)
1022     LdStart = getStartForNegStride(LdStart, BECount, IntPtrTy, StoreSize, SE);
1023 
1024   // For a memcpy, we have to make sure that the input array is not being
1025   // mutated by the loop.
1026   Value *LoadBasePtr = Expander.expandCodeFor(
1027       LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
1028 
1029   if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1030                             StoreSize, *AA, Stores)) {
1031     Expander.clear();
1032     // If we generated new code for the base pointer, clean up.
1033     RecursivelyDeleteTriviallyDeadInstructions(LoadBasePtr, TLI);
1034     RecursivelyDeleteTriviallyDeadInstructions(StoreBasePtr, TLI);
1035     return false;
1036   }
1037 
1038   if (avoidLIRForMultiBlockLoop())
1039     return false;
1040 
1041   // Okay, everything is safe, we can transform this!
1042 
1043   const SCEV *NumBytesS =
1044       getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE);
1045 
1046   Value *NumBytes =
1047       Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->getTerminator());
1048 
1049   CallInst *NewCall = nullptr;
1050   // Check whether to generate an unordered atomic memcpy:
1051   //  If the load or store are atomic, then they must necessarily be unordered
1052   //  by previous checks.
1053   if (!SI->isAtomic() && !LI->isAtomic())
1054     NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->getAlignment(),
1055                                    LoadBasePtr, LI->getAlignment(), NumBytes);
1056   else {
1057     // We cannot allow unaligned ops for unordered load/store, so reject
1058     // anything where the alignment isn't at least the element size.
1059     unsigned Align = std::min(SI->getAlignment(), LI->getAlignment());
1060     if (Align < StoreSize)
1061       return false;
1062 
1063     // If the element.atomic memcpy is not lowered into explicit
1064     // loads/stores later, then it will be lowered into an element-size
1065     // specific lib call. If the lib call doesn't exist for our store size, then
1066     // we shouldn't generate the memcpy.
1067     if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1068       return false;
1069 
1070     // Create the call.
1071     // Note that unordered atomic loads/stores are *required* by the spec to
1072     // have an alignment but non-atomic loads/stores may not.
1073     NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1074         StoreBasePtr, SI->getAlignment(), LoadBasePtr, LI->getAlignment(),
1075         NumBytes, StoreSize);
1076   }
1077   NewCall->setDebugLoc(SI->getDebugLoc());
1078 
1079   LLVM_DEBUG(dbgs() << "  Formed memcpy: " << *NewCall << "\n"
1080                     << "    from load ptr=" << *LoadEv << " at: " << *LI << "\n"
1081                     << "    from store ptr=" << *StoreEv << " at: " << *SI
1082                     << "\n");
1083 
1084   // Okay, the memcpy has been formed.  Zap the original store and anything that
1085   // feeds into it.
1086   deleteDeadInstruction(SI);
1087   ++NumMemCpy;
1088   return true;
1089 }
1090 
1091 // When compiling for codesize we avoid idiom recognition for a multi-block loop
1092 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1093 //
1094 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1095                                                    bool IsLoopMemset) {
1096   if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1097     if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1098       LLVM_DEBUG(dbgs() << "  " << CurLoop->getHeader()->getParent()->getName()
1099                         << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1100                         << " avoided: multi-block top-level loop\n");
1101       return true;
1102     }
1103   }
1104 
1105   return false;
1106 }
1107 
1108 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1109   return recognizePopcount() || recognizeAndInsertCTLZ();
1110 }
1111 
1112 /// Check if the given conditional branch is based on the comparison between
1113 /// a variable and zero, and if the variable is non-zero, the control yields to
1114 /// the loop entry. If the branch matches the behavior, the variable involved
1115 /// in the comparison is returned. This function will be called to see if the
1116 /// precondition and postcondition of the loop are in desirable form.
1117 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry) {
1118   if (!BI || !BI->isConditional())
1119     return nullptr;
1120 
1121   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1122   if (!Cond)
1123     return nullptr;
1124 
1125   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1126   if (!CmpZero || !CmpZero->isZero())
1127     return nullptr;
1128 
1129   ICmpInst::Predicate Pred = Cond->getPredicate();
1130   if ((Pred == ICmpInst::ICMP_NE && BI->getSuccessor(0) == LoopEntry) ||
1131       (Pred == ICmpInst::ICMP_EQ && BI->getSuccessor(1) == LoopEntry))
1132     return Cond->getOperand(0);
1133 
1134   return nullptr;
1135 }
1136 
1137 // Check if the recurrence variable `VarX` is in the right form to create
1138 // the idiom. Returns the value coerced to a PHINode if so.
1139 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1140                                  BasicBlock *LoopEntry) {
1141   auto *PhiX = dyn_cast<PHINode>(VarX);
1142   if (PhiX && PhiX->getParent() == LoopEntry &&
1143       (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1144     return PhiX;
1145   return nullptr;
1146 }
1147 
1148 /// Return true iff the idiom is detected in the loop.
1149 ///
1150 /// Additionally:
1151 /// 1) \p CntInst is set to the instruction counting the population bit.
1152 /// 2) \p CntPhi is set to the corresponding phi node.
1153 /// 3) \p Var is set to the value whose population bits are being counted.
1154 ///
1155 /// The core idiom we are trying to detect is:
1156 /// \code
1157 ///    if (x0 != 0)
1158 ///      goto loop-exit // the precondition of the loop
1159 ///    cnt0 = init-val;
1160 ///    do {
1161 ///       x1 = phi (x0, x2);
1162 ///       cnt1 = phi(cnt0, cnt2);
1163 ///
1164 ///       cnt2 = cnt1 + 1;
1165 ///        ...
1166 ///       x2 = x1 & (x1 - 1);
1167 ///        ...
1168 ///    } while(x != 0);
1169 ///
1170 /// loop-exit:
1171 /// \endcode
1172 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1173                                 Instruction *&CntInst, PHINode *&CntPhi,
1174                                 Value *&Var) {
1175   // step 1: Check to see if the look-back branch match this pattern:
1176   //    "if (a!=0) goto loop-entry".
1177   BasicBlock *LoopEntry;
1178   Instruction *DefX2, *CountInst;
1179   Value *VarX1, *VarX0;
1180   PHINode *PhiX, *CountPhi;
1181 
1182   DefX2 = CountInst = nullptr;
1183   VarX1 = VarX0 = nullptr;
1184   PhiX = CountPhi = nullptr;
1185   LoopEntry = *(CurLoop->block_begin());
1186 
1187   // step 1: Check if the loop-back branch is in desirable form.
1188   {
1189     if (Value *T = matchCondition(
1190             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1191       DefX2 = dyn_cast<Instruction>(T);
1192     else
1193       return false;
1194   }
1195 
1196   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1197   {
1198     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1199       return false;
1200 
1201     BinaryOperator *SubOneOp;
1202 
1203     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1204       VarX1 = DefX2->getOperand(1);
1205     else {
1206       VarX1 = DefX2->getOperand(0);
1207       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1208     }
1209     if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
1210       return false;
1211 
1212     ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
1213     if (!Dec ||
1214         !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1215           (SubOneOp->getOpcode() == Instruction::Add &&
1216            Dec->isMinusOne()))) {
1217       return false;
1218     }
1219   }
1220 
1221   // step 3: Check the recurrence of variable X
1222   PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1223   if (!PhiX)
1224     return false;
1225 
1226   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1227   {
1228     CountInst = nullptr;
1229     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1230                               IterE = LoopEntry->end();
1231          Iter != IterE; Iter++) {
1232       Instruction *Inst = &*Iter;
1233       if (Inst->getOpcode() != Instruction::Add)
1234         continue;
1235 
1236       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1237       if (!Inc || !Inc->isOne())
1238         continue;
1239 
1240       PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1241       if (!Phi)
1242         continue;
1243 
1244       // Check if the result of the instruction is live of the loop.
1245       bool LiveOutLoop = false;
1246       for (User *U : Inst->users()) {
1247         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1248           LiveOutLoop = true;
1249           break;
1250         }
1251       }
1252 
1253       if (LiveOutLoop) {
1254         CountInst = Inst;
1255         CountPhi = Phi;
1256         break;
1257       }
1258     }
1259 
1260     if (!CountInst)
1261       return false;
1262   }
1263 
1264   // step 5: check if the precondition is in this form:
1265   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1266   {
1267     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1268     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1269     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1270       return false;
1271 
1272     CntInst = CountInst;
1273     CntPhi = CountPhi;
1274     Var = T;
1275   }
1276 
1277   return true;
1278 }
1279 
1280 /// Return true if the idiom is detected in the loop.
1281 ///
1282 /// Additionally:
1283 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1284 ///       or nullptr if there is no such.
1285 /// 2) \p CntPhi is set to the corresponding phi node
1286 ///       or nullptr if there is no such.
1287 /// 3) \p Var is set to the value whose CTLZ could be used.
1288 /// 4) \p DefX is set to the instruction calculating Loop exit condition.
1289 ///
1290 /// The core idiom we are trying to detect is:
1291 /// \code
1292 ///    if (x0 == 0)
1293 ///      goto loop-exit // the precondition of the loop
1294 ///    cnt0 = init-val;
1295 ///    do {
1296 ///       x = phi (x0, x.next);   //PhiX
1297 ///       cnt = phi(cnt0, cnt.next);
1298 ///
1299 ///       cnt.next = cnt + 1;
1300 ///        ...
1301 ///       x.next = x >> 1;   // DefX
1302 ///        ...
1303 ///    } while(x.next != 0);
1304 ///
1305 /// loop-exit:
1306 /// \endcode
1307 static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX,
1308                             Instruction *&CntInst, PHINode *&CntPhi,
1309                             Instruction *&DefX) {
1310   BasicBlock *LoopEntry;
1311   Value *VarX = nullptr;
1312 
1313   DefX = nullptr;
1314   PhiX = nullptr;
1315   CntInst = nullptr;
1316   CntPhi = nullptr;
1317   LoopEntry = *(CurLoop->block_begin());
1318 
1319   // step 1: Check if the loop-back branch is in desirable form.
1320   if (Value *T = matchCondition(
1321           dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1322     DefX = dyn_cast<Instruction>(T);
1323   else
1324     return false;
1325 
1326   // step 2: detect instructions corresponding to "x.next = x >> 1"
1327   if (!DefX || (DefX->getOpcode() != Instruction::AShr &&
1328                 DefX->getOpcode() != Instruction::LShr))
1329     return false;
1330   ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1331   if (!Shft || !Shft->isOne())
1332     return false;
1333   VarX = DefX->getOperand(0);
1334 
1335   // step 3: Check the recurrence of variable X
1336   PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1337   if (!PhiX)
1338     return false;
1339 
1340   // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1341   // TODO: We can skip the step. If loop trip count is known (CTLZ),
1342   //       then all uses of "cnt.next" could be optimized to the trip count
1343   //       plus "cnt0". Currently it is not optimized.
1344   //       This step could be used to detect POPCNT instruction:
1345   //       cnt.next = cnt + (x.next & 1)
1346   for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1347                             IterE = LoopEntry->end();
1348        Iter != IterE; Iter++) {
1349     Instruction *Inst = &*Iter;
1350     if (Inst->getOpcode() != Instruction::Add)
1351       continue;
1352 
1353     ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1354     if (!Inc || !Inc->isOne())
1355       continue;
1356 
1357     PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1358     if (!Phi)
1359       continue;
1360 
1361     CntInst = Inst;
1362     CntPhi = Phi;
1363     break;
1364   }
1365   if (!CntInst)
1366     return false;
1367 
1368   return true;
1369 }
1370 
1371 /// Recognize CTLZ idiom in a non-countable loop and convert the loop
1372 /// to countable (with CTLZ trip count).
1373 /// If CTLZ inserted as a new trip count returns true; otherwise, returns false.
1374 bool LoopIdiomRecognize::recognizeAndInsertCTLZ() {
1375   // Give up if the loop has multiple blocks or multiple backedges.
1376   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1377     return false;
1378 
1379   Instruction *CntInst, *DefX;
1380   PHINode *CntPhi, *PhiX;
1381   if (!detectCTLZIdiom(CurLoop, PhiX, CntInst, CntPhi, DefX))
1382     return false;
1383 
1384   bool IsCntPhiUsedOutsideLoop = false;
1385   for (User *U : CntPhi->users())
1386     if (!CurLoop->contains(cast<Instruction>(U))) {
1387       IsCntPhiUsedOutsideLoop = true;
1388       break;
1389     }
1390   bool IsCntInstUsedOutsideLoop = false;
1391   for (User *U : CntInst->users())
1392     if (!CurLoop->contains(cast<Instruction>(U))) {
1393       IsCntInstUsedOutsideLoop = true;
1394       break;
1395     }
1396   // If both CntInst and CntPhi are used outside the loop the profitability
1397   // is questionable.
1398   if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1399     return false;
1400 
1401   // For some CPUs result of CTLZ(X) intrinsic is undefined
1402   // when X is 0. If we can not guarantee X != 0, we need to check this
1403   // when expand.
1404   bool ZeroCheck = false;
1405   // It is safe to assume Preheader exist as it was checked in
1406   // parent function RunOnLoop.
1407   BasicBlock *PH = CurLoop->getLoopPreheader();
1408   Value *InitX = PhiX->getIncomingValueForBlock(PH);
1409 
1410   // Make sure the initial value can't be negative otherwise the ashr in the
1411   // loop might never reach zero which would make the loop infinite.
1412   if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, *DL))
1413     return false;
1414 
1415   // If we are using the count instruction outside the loop, make sure we
1416   // have a zero check as a precondition. Without the check the loop would run
1417   // one iteration for before any check of the input value. This means 0 and 1
1418   // would have identical behavior in the original loop and thus
1419   if (!IsCntPhiUsedOutsideLoop) {
1420     auto *PreCondBB = PH->getSinglePredecessor();
1421     if (!PreCondBB)
1422       return false;
1423     auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1424     if (!PreCondBI)
1425       return false;
1426     if (matchCondition(PreCondBI, PH) != InitX)
1427       return false;
1428     ZeroCheck = true;
1429   }
1430 
1431   // Check if CTLZ intrinsic is profitable. Assume it is always profitable
1432   // if we delete the loop (the loop has only 6 instructions):
1433   //  %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1434   //  %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1435   //  %shr = ashr %n.addr.0, 1
1436   //  %tobool = icmp eq %shr, 0
1437   //  %inc = add nsw %i.0, 1
1438   //  br i1 %tobool
1439 
1440   const Value *Args[] =
1441       {InitX, ZeroCheck ? ConstantInt::getTrue(InitX->getContext())
1442                         : ConstantInt::getFalse(InitX->getContext())};
1443   if (CurLoop->getHeader()->size() != 6 &&
1444       TTI->getIntrinsicCost(Intrinsic::ctlz, InitX->getType(), Args) >
1445           TargetTransformInfo::TCC_Basic)
1446     return false;
1447 
1448   transformLoopToCountable(PH, CntInst, CntPhi, InitX, DefX,
1449                            DefX->getDebugLoc(), ZeroCheck,
1450                            IsCntPhiUsedOutsideLoop);
1451   return true;
1452 }
1453 
1454 /// Recognizes a population count idiom in a non-countable loop.
1455 ///
1456 /// If detected, transforms the relevant code to issue the popcount intrinsic
1457 /// function call, and returns true; otherwise, returns false.
1458 bool LoopIdiomRecognize::recognizePopcount() {
1459   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1460     return false;
1461 
1462   // Counting population are usually conducted by few arithmetic instructions.
1463   // Such instructions can be easily "absorbed" by vacant slots in a
1464   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1465   // in a compact loop.
1466 
1467   // Give up if the loop has multiple blocks or multiple backedges.
1468   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1469     return false;
1470 
1471   BasicBlock *LoopBody = *(CurLoop->block_begin());
1472   if (LoopBody->size() >= 20) {
1473     // The loop is too big, bail out.
1474     return false;
1475   }
1476 
1477   // It should have a preheader containing nothing but an unconditional branch.
1478   BasicBlock *PH = CurLoop->getLoopPreheader();
1479   if (!PH || &PH->front() != PH->getTerminator())
1480     return false;
1481   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1482   if (!EntryBI || EntryBI->isConditional())
1483     return false;
1484 
1485   // It should have a precondition block where the generated popcount intrinsic
1486   // function can be inserted.
1487   auto *PreCondBB = PH->getSinglePredecessor();
1488   if (!PreCondBB)
1489     return false;
1490   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1491   if (!PreCondBI || PreCondBI->isUnconditional())
1492     return false;
1493 
1494   Instruction *CntInst;
1495   PHINode *CntPhi;
1496   Value *Val;
1497   if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1498     return false;
1499 
1500   transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1501   return true;
1502 }
1503 
1504 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1505                                        const DebugLoc &DL) {
1506   Value *Ops[] = {Val};
1507   Type *Tys[] = {Val->getType()};
1508 
1509   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1510   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1511   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1512   CI->setDebugLoc(DL);
1513 
1514   return CI;
1515 }
1516 
1517 static CallInst *createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1518                                      const DebugLoc &DL, bool ZeroCheck) {
1519   Value *Ops[] = {Val, ZeroCheck ? IRBuilder.getTrue() : IRBuilder.getFalse()};
1520   Type *Tys[] = {Val->getType()};
1521 
1522   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1523   Value *Func = Intrinsic::getDeclaration(M, Intrinsic::ctlz, Tys);
1524   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1525   CI->setDebugLoc(DL);
1526 
1527   return CI;
1528 }
1529 
1530 /// Transform the following loop:
1531 /// loop:
1532 ///   CntPhi = PHI [Cnt0, CntInst]
1533 ///   PhiX = PHI [InitX, DefX]
1534 ///   CntInst = CntPhi + 1
1535 ///   DefX = PhiX >> 1
1536 ///   LOOP_BODY
1537 ///   Br: loop if (DefX != 0)
1538 /// Use(CntPhi) or Use(CntInst)
1539 ///
1540 /// Into:
1541 /// If CntPhi used outside the loop:
1542 ///   CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1543 ///   Count = CountPrev + 1
1544 /// else
1545 ///   Count = BitWidth(InitX) - CTLZ(InitX)
1546 /// loop:
1547 ///   CntPhi = PHI [Cnt0, CntInst]
1548 ///   PhiX = PHI [InitX, DefX]
1549 ///   PhiCount = PHI [Count, Dec]
1550 ///   CntInst = CntPhi + 1
1551 ///   DefX = PhiX >> 1
1552 ///   Dec = PhiCount - 1
1553 ///   LOOP_BODY
1554 ///   Br: loop if (Dec != 0)
1555 /// Use(CountPrev + Cnt0) // Use(CntPhi)
1556 /// or
1557 /// Use(Count + Cnt0) // Use(CntInst)
1558 ///
1559 /// If LOOP_BODY is empty the loop will be deleted.
1560 /// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1561 void LoopIdiomRecognize::transformLoopToCountable(
1562     BasicBlock *Preheader, Instruction *CntInst, PHINode *CntPhi, Value *InitX,
1563     Instruction *DefX, const DebugLoc &DL, bool ZeroCheck,
1564     bool IsCntPhiUsedOutsideLoop) {
1565   BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
1566 
1567   // Step 1: Insert the CTLZ instruction at the end of the preheader block
1568   //   Count = BitWidth - CTLZ(InitX);
1569   // If there are uses of CntPhi create:
1570   //   CountPrev = BitWidth - CTLZ(InitX >> 1);
1571   IRBuilder<> Builder(PreheaderBr);
1572   Builder.SetCurrentDebugLocation(DL);
1573   Value *CTLZ, *Count, *CountPrev, *NewCount, *InitXNext;
1574 
1575   if (IsCntPhiUsedOutsideLoop) {
1576     if (DefX->getOpcode() == Instruction::AShr)
1577       InitXNext =
1578           Builder.CreateAShr(InitX, ConstantInt::get(InitX->getType(), 1));
1579     else if (DefX->getOpcode() == Instruction::LShr)
1580       InitXNext =
1581           Builder.CreateLShr(InitX, ConstantInt::get(InitX->getType(), 1));
1582     else
1583       llvm_unreachable("Unexpected opcode!");
1584   } else
1585     InitXNext = InitX;
1586   CTLZ = createCTLZIntrinsic(Builder, InitXNext, DL, ZeroCheck);
1587   Count = Builder.CreateSub(
1588       ConstantInt::get(CTLZ->getType(),
1589                        CTLZ->getType()->getIntegerBitWidth()),
1590       CTLZ);
1591   if (IsCntPhiUsedOutsideLoop) {
1592     CountPrev = Count;
1593     Count = Builder.CreateAdd(
1594         CountPrev,
1595         ConstantInt::get(CountPrev->getType(), 1));
1596   }
1597   if (IsCntPhiUsedOutsideLoop)
1598     NewCount = Builder.CreateZExtOrTrunc(CountPrev,
1599         cast<IntegerType>(CntInst->getType()));
1600   else
1601     NewCount = Builder.CreateZExtOrTrunc(Count,
1602         cast<IntegerType>(CntInst->getType()));
1603 
1604   // If the CTLZ counter's initial value is not zero, insert Add Inst.
1605   Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1606   ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1607   if (!InitConst || !InitConst->isZero())
1608     NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1609 
1610   // Step 2: Insert new IV and loop condition:
1611   // loop:
1612   //   ...
1613   //   PhiCount = PHI [Count, Dec]
1614   //   ...
1615   //   Dec = PhiCount - 1
1616   //   ...
1617   //   Br: loop if (Dec != 0)
1618   BasicBlock *Body = *(CurLoop->block_begin());
1619   auto *LbBr = cast<BranchInst>(Body->getTerminator());
1620   ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1621   Type *Ty = Count->getType();
1622 
1623   PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1624 
1625   Builder.SetInsertPoint(LbCond);
1626   Instruction *TcDec = cast<Instruction>(
1627       Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1628                         "tcdec", false, true));
1629 
1630   TcPhi->addIncoming(Count, Preheader);
1631   TcPhi->addIncoming(TcDec, Body);
1632 
1633   CmpInst::Predicate Pred =
1634       (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
1635   LbCond->setPredicate(Pred);
1636   LbCond->setOperand(0, TcDec);
1637   LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1638 
1639   // Step 3: All the references to the original counter outside
1640   //  the loop are replaced with the NewCount -- the value returned from
1641   //  __builtin_ctlz(x).
1642   if (IsCntPhiUsedOutsideLoop)
1643     CntPhi->replaceUsesOutsideBlock(NewCount, Body);
1644   else
1645     CntInst->replaceUsesOutsideBlock(NewCount, Body);
1646 
1647   // step 4: Forget the "non-computable" trip-count SCEV associated with the
1648   //   loop. The loop would otherwise not be deleted even if it becomes empty.
1649   SE->forgetLoop(CurLoop);
1650 }
1651 
1652 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
1653                                                  Instruction *CntInst,
1654                                                  PHINode *CntPhi, Value *Var) {
1655   BasicBlock *PreHead = CurLoop->getLoopPreheader();
1656   auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
1657   const DebugLoc &DL = CntInst->getDebugLoc();
1658 
1659   // Assuming before transformation, the loop is following:
1660   //  if (x) // the precondition
1661   //     do { cnt++; x &= x - 1; } while(x);
1662 
1663   // Step 1: Insert the ctpop instruction at the end of the precondition block
1664   IRBuilder<> Builder(PreCondBr);
1665   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1666   {
1667     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
1668     NewCount = PopCntZext =
1669         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
1670 
1671     if (NewCount != PopCnt)
1672       (cast<Instruction>(NewCount))->setDebugLoc(DL);
1673 
1674     // TripCnt is exactly the number of iterations the loop has
1675     TripCnt = NewCount;
1676 
1677     // If the population counter's initial value is not zero, insert Add Inst.
1678     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
1679     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1680     if (!InitConst || !InitConst->isZero()) {
1681       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1682       (cast<Instruction>(NewCount))->setDebugLoc(DL);
1683     }
1684   }
1685 
1686   // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
1687   //   "if (NewCount == 0) loop-exit". Without this change, the intrinsic
1688   //   function would be partial dead code, and downstream passes will drag
1689   //   it back from the precondition block to the preheader.
1690   {
1691     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1692 
1693     Value *Opnd0 = PopCntZext;
1694     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
1695     if (PreCond->getOperand(0) != Var)
1696       std::swap(Opnd0, Opnd1);
1697 
1698     ICmpInst *NewPreCond = cast<ICmpInst>(
1699         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
1700     PreCondBr->setCondition(NewPreCond);
1701 
1702     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
1703   }
1704 
1705   // Step 3: Note that the population count is exactly the trip count of the
1706   // loop in question, which enable us to convert the loop from noncountable
1707   // loop into a countable one. The benefit is twofold:
1708   //
1709   //  - If the loop only counts population, the entire loop becomes dead after
1710   //    the transformation. It is a lot easier to prove a countable loop dead
1711   //    than to prove a noncountable one. (In some C dialects, an infinite loop
1712   //    isn't dead even if it computes nothing useful. In general, DCE needs
1713   //    to prove a noncountable loop finite before safely delete it.)
1714   //
1715   //  - If the loop also performs something else, it remains alive.
1716   //    Since it is transformed to countable form, it can be aggressively
1717   //    optimized by some optimizations which are in general not applicable
1718   //    to a noncountable loop.
1719   //
1720   // After this step, this loop (conceptually) would look like following:
1721   //   newcnt = __builtin_ctpop(x);
1722   //   t = newcnt;
1723   //   if (x)
1724   //     do { cnt++; x &= x-1; t--) } while (t > 0);
1725   BasicBlock *Body = *(CurLoop->block_begin());
1726   {
1727     auto *LbBr = cast<BranchInst>(Body->getTerminator());
1728     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1729     Type *Ty = TripCnt->getType();
1730 
1731     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
1732 
1733     Builder.SetInsertPoint(LbCond);
1734     Instruction *TcDec = cast<Instruction>(
1735         Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
1736                           "tcdec", false, true));
1737 
1738     TcPhi->addIncoming(TripCnt, PreHead);
1739     TcPhi->addIncoming(TcDec, Body);
1740 
1741     CmpInst::Predicate Pred =
1742         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
1743     LbCond->setPredicate(Pred);
1744     LbCond->setOperand(0, TcDec);
1745     LbCond->setOperand(1, ConstantInt::get(Ty, 0));
1746   }
1747 
1748   // Step 4: All the references to the original population counter outside
1749   //  the loop are replaced with the NewCount -- the value returned from
1750   //  __builtin_ctpop().
1751   CntInst->replaceUsesOutsideBlock(NewCount, Body);
1752 
1753   // step 5: Forget the "non-computable" trip-count SCEV associated with the
1754   //   loop. The loop would otherwise not be deleted even if it becomes empty.
1755   SE->forgetLoop(CurLoop);
1756 }
1757