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