1 //===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements an idiom recognizer that transforms simple loops into a
10 // non-loop form.  In cases that this kicks in, it can be a significant
11 // performance win.
12 //
13 // If compiling for code size we avoid idiom recognition if the resulting
14 // code could be larger than the code for the original loop. One way this could
15 // happen is if the loop is not removable after idiom recognition due to the
16 // presence of non-idiom instructions. The initial implementation of the
17 // heuristics applies to idioms in multi-block loops.
18 //
19 //===----------------------------------------------------------------------===//
20 //
21 // TODO List:
22 //
23 // Future loop memory idioms to recognize:
24 //   memcmp, strlen, etc.
25 // Future floating point idioms to recognize in -ffast-math mode:
26 //   fpowi
27 // Future integer operation idioms to recognize:
28 //   ctpop
29 //
30 // Beware that isel's default lowering for ctpop is highly inefficient for
31 // i64 and larger types when i64 is legal and the value has few bits set.  It
32 // would be good to enhance isel to emit a loop for ctpop in this case.
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/LoopIdiomRecognize.h"
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/CmpInstAnalysis.h"
51 #include "llvm/Analysis/LoopAccessAnalysis.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Analysis/MemoryLocation.h"
55 #include "llvm/Analysis/MemorySSA.h"
56 #include "llvm/Analysis/MemorySSAUpdater.h"
57 #include "llvm/Analysis/MustExecute.h"
58 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
59 #include "llvm/Analysis/ScalarEvolution.h"
60 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
61 #include "llvm/Analysis/TargetLibraryInfo.h"
62 #include "llvm/Analysis/TargetTransformInfo.h"
63 #include "llvm/Analysis/ValueTracking.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/BasicBlock.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/GlobalValue.h"
73 #include "llvm/IR/GlobalVariable.h"
74 #include "llvm/IR/IRBuilder.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instruction.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/Intrinsics.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PassManager.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/IR/ValueHandle.h"
88 #include "llvm/InitializePasses.h"
89 #include "llvm/Pass.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/InstructionCost.h"
94 #include "llvm/Support/raw_ostream.h"
95 #include "llvm/Transforms/Scalar.h"
96 #include "llvm/Transforms/Utils/BuildLibCalls.h"
97 #include "llvm/Transforms/Utils/Local.h"
98 #include "llvm/Transforms/Utils/LoopUtils.h"
99 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
100 #include <algorithm>
101 #include <cassert>
102 #include <cstdint>
103 #include <utility>
104 #include <vector>
105 
106 using namespace llvm;
107 
108 #define DEBUG_TYPE "loop-idiom"
109 
110 STATISTIC(NumMemSet, "Number of memset's formed from loop stores");
111 STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");
112 STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores");
113 STATISTIC(
114     NumShiftUntilBitTest,
115     "Number of uncountable loops recognized as 'shift until bitttest' idiom");
116 STATISTIC(NumShiftUntilZero,
117           "Number of uncountable loops recognized as 'shift until zero' idiom");
118 
119 bool DisableLIRP::All;
120 static cl::opt<bool, true>
121     DisableLIRPAll("disable-" DEBUG_TYPE "-all",
122                    cl::desc("Options to disable Loop Idiom Recognize Pass."),
123                    cl::location(DisableLIRP::All), cl::init(false),
124                    cl::ReallyHidden);
125 
126 bool DisableLIRP::Memset;
127 static cl::opt<bool, true>
128     DisableLIRPMemset("disable-" DEBUG_TYPE "-memset",
129                       cl::desc("Proceed with loop idiom recognize pass, but do "
130                                "not convert loop(s) to memset."),
131                       cl::location(DisableLIRP::Memset), cl::init(false),
132                       cl::ReallyHidden);
133 
134 bool DisableLIRP::Memcpy;
135 static cl::opt<bool, true>
136     DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy",
137                       cl::desc("Proceed with loop idiom recognize pass, but do "
138                                "not convert loop(s) to memcpy."),
139                       cl::location(DisableLIRP::Memcpy), cl::init(false),
140                       cl::ReallyHidden);
141 
142 static cl::opt<bool> UseLIRCodeSizeHeurs(
143     "use-lir-code-size-heurs",
144     cl::desc("Use loop idiom recognition code size heuristics when compiling"
145              "with -Os/-Oz"),
146     cl::init(true), cl::Hidden);
147 
148 namespace {
149 
150 class LoopIdiomRecognize {
151   Loop *CurLoop = nullptr;
152   AliasAnalysis *AA;
153   DominatorTree *DT;
154   LoopInfo *LI;
155   ScalarEvolution *SE;
156   TargetLibraryInfo *TLI;
157   const TargetTransformInfo *TTI;
158   const DataLayout *DL;
159   OptimizationRemarkEmitter &ORE;
160   bool ApplyCodeSizeHeuristics;
161   std::unique_ptr<MemorySSAUpdater> MSSAU;
162 
163 public:
164   explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,
165                               LoopInfo *LI, ScalarEvolution *SE,
166                               TargetLibraryInfo *TLI,
167                               const TargetTransformInfo *TTI, MemorySSA *MSSA,
168                               const DataLayout *DL,
169                               OptimizationRemarkEmitter &ORE)
170       : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) {
171     if (MSSA)
172       MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
173   }
174 
175   bool runOnLoop(Loop *L);
176 
177 private:
178   using StoreList = SmallVector<StoreInst *, 8>;
179   using StoreListMap = MapVector<Value *, StoreList>;
180 
181   StoreListMap StoreRefsForMemset;
182   StoreListMap StoreRefsForMemsetPattern;
183   StoreList StoreRefsForMemcpy;
184   bool HasMemset;
185   bool HasMemsetPattern;
186   bool HasMemcpy;
187 
188   /// Return code for isLegalStore()
189   enum LegalStoreKind {
190     None = 0,
191     Memset,
192     MemsetPattern,
193     Memcpy,
194     UnorderedAtomicMemcpy,
195     DontUse // Dummy retval never to be used. Allows catching errors in retval
196             // handling.
197   };
198 
199   /// \name Countable Loop Idiom Handling
200   /// @{
201 
202   bool runOnCountableLoop();
203   bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,
204                       SmallVectorImpl<BasicBlock *> &ExitBlocks);
205 
206   void collectStores(BasicBlock *BB);
207   LegalStoreKind isLegalStore(StoreInst *SI);
208   enum class ForMemset { No, Yes };
209   bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,
210                          ForMemset For);
211 
212   template <typename MemInst>
213   bool processLoopMemIntrinsic(
214       BasicBlock *BB,
215       bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
216       const SCEV *BECount);
217   bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount);
218   bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);
219 
220   bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV,
221                                MaybeAlign StoreAlignment, Value *StoredVal,
222                                Instruction *TheStore,
223                                SmallPtrSetImpl<Instruction *> &Stores,
224                                const SCEVAddRecExpr *Ev, const SCEV *BECount,
225                                bool IsNegStride, bool IsLoopMemset = false);
226   bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);
227   bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr,
228                                   unsigned StoreSize, MaybeAlign StoreAlign,
229                                   MaybeAlign LoadAlign, Instruction *TheStore,
230                                   Instruction *TheLoad,
231                                   const SCEVAddRecExpr *StoreEv,
232                                   const SCEVAddRecExpr *LoadEv,
233                                   const SCEV *BECount);
234   bool avoidLIRForMultiBlockLoop(bool IsMemset = false,
235                                  bool IsLoopMemset = false);
236 
237   /// @}
238   /// \name Noncountable Loop Idiom Handling
239   /// @{
240 
241   bool runOnNoncountableLoop();
242 
243   bool recognizePopcount();
244   void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,
245                                PHINode *CntPhi, Value *Var);
246   bool recognizeAndInsertFFS();  /// Find First Set: ctlz or cttz
247   void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,
248                                 Instruction *CntInst, PHINode *CntPhi,
249                                 Value *Var, Instruction *DefX,
250                                 const DebugLoc &DL, bool ZeroCheck,
251                                 bool IsCntPhiUsedOutsideLoop);
252 
253   bool recognizeShiftUntilBitTest();
254   bool recognizeShiftUntilZero();
255 
256   /// @}
257 };
258 
259 class LoopIdiomRecognizeLegacyPass : public LoopPass {
260 public:
261   static char ID;
262 
263   explicit LoopIdiomRecognizeLegacyPass() : LoopPass(ID) {
264     initializeLoopIdiomRecognizeLegacyPassPass(
265         *PassRegistry::getPassRegistry());
266   }
267 
268   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
269     if (DisableLIRP::All)
270       return false;
271 
272     if (skipLoop(L))
273       return false;
274 
275     AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
276     DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
277     LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
278     ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
279     TargetLibraryInfo *TLI =
280         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
281             *L->getHeader()->getParent());
282     const TargetTransformInfo *TTI =
283         &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
284             *L->getHeader()->getParent());
285     const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
286     auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
287     MemorySSA *MSSA = nullptr;
288     if (MSSAAnalysis)
289       MSSA = &MSSAAnalysis->getMSSA();
290 
291     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
292     // pass.  Function analyses need to be preserved across loop transformations
293     // but ORE cannot be preserved (see comment before the pass definition).
294     OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
295 
296     LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, MSSA, DL, ORE);
297     return LIR.runOnLoop(L);
298   }
299 
300   /// This transformation requires natural loop information & requires that
301   /// loop preheaders be inserted into the CFG.
302   void getAnalysisUsage(AnalysisUsage &AU) const override {
303     AU.addRequired<TargetLibraryInfoWrapperPass>();
304     AU.addRequired<TargetTransformInfoWrapperPass>();
305     AU.addPreserved<MemorySSAWrapperPass>();
306     getLoopAnalysisUsage(AU);
307   }
308 };
309 
310 } // end anonymous namespace
311 
312 char LoopIdiomRecognizeLegacyPass::ID = 0;
313 
314 PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,
315                                               LoopStandardAnalysisResults &AR,
316                                               LPMUpdater &) {
317   if (DisableLIRP::All)
318     return PreservedAnalyses::all();
319 
320   const auto *DL = &L.getHeader()->getModule()->getDataLayout();
321 
322   // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
323   // pass.  Function analyses need to be preserved across loop transformations
324   // but ORE cannot be preserved (see comment before the pass definition).
325   OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
326 
327   LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI,
328                          AR.MSSA, DL, ORE);
329   if (!LIR.runOnLoop(&L))
330     return PreservedAnalyses::all();
331 
332   auto PA = getLoopPassPreservedAnalyses();
333   if (AR.MSSA)
334     PA.preserve<MemorySSAAnalysis>();
335   return PA;
336 }
337 
338 INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom",
339                       "Recognize loop idioms", false, false)
340 INITIALIZE_PASS_DEPENDENCY(LoopPass)
341 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
342 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
343 INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass, "loop-idiom",
344                     "Recognize loop idioms", false, false)
345 
346 Pass *llvm::createLoopIdiomPass() { return new LoopIdiomRecognizeLegacyPass(); }
347 
348 static void deleteDeadInstruction(Instruction *I) {
349   I->replaceAllUsesWith(UndefValue::get(I->getType()));
350   I->eraseFromParent();
351 }
352 
353 //===----------------------------------------------------------------------===//
354 //
355 //          Implementation of LoopIdiomRecognize
356 //
357 //===----------------------------------------------------------------------===//
358 
359 bool LoopIdiomRecognize::runOnLoop(Loop *L) {
360   CurLoop = L;
361   // If the loop could not be converted to canonical form, it must have an
362   // indirectbr in it, just give up.
363   if (!L->getLoopPreheader())
364     return false;
365 
366   // Disable loop idiom recognition if the function's name is a common idiom.
367   StringRef Name = L->getHeader()->getParent()->getName();
368   if (Name == "memset" || Name == "memcpy")
369     return false;
370 
371   // Determine if code size heuristics need to be applied.
372   ApplyCodeSizeHeuristics =
373       L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs;
374 
375   HasMemset = TLI->has(LibFunc_memset);
376   HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);
377   HasMemcpy = TLI->has(LibFunc_memcpy);
378 
379   if (HasMemset || HasMemsetPattern || HasMemcpy)
380     if (SE->hasLoopInvariantBackedgeTakenCount(L))
381       return runOnCountableLoop();
382 
383   return runOnNoncountableLoop();
384 }
385 
386 bool LoopIdiomRecognize::runOnCountableLoop() {
387   const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);
388   assert(!isa<SCEVCouldNotCompute>(BECount) &&
389          "runOnCountableLoop() called on a loop without a predictable"
390          "backedge-taken count");
391 
392   // If this loop executes exactly one time, then it should be peeled, not
393   // optimized by this pass.
394   if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
395     if (BECst->getAPInt() == 0)
396       return false;
397 
398   SmallVector<BasicBlock *, 8> ExitBlocks;
399   CurLoop->getUniqueExitBlocks(ExitBlocks);
400 
401   LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
402                     << CurLoop->getHeader()->getParent()->getName()
403                     << "] Countable Loop %" << CurLoop->getHeader()->getName()
404                     << "\n");
405 
406   // The following transforms hoist stores/memsets into the loop pre-header.
407   // Give up if the loop has instructions that may throw.
408   SimpleLoopSafetyInfo SafetyInfo;
409   SafetyInfo.computeLoopSafetyInfo(CurLoop);
410   if (SafetyInfo.anyBlockMayThrow())
411     return false;
412 
413   bool MadeChange = false;
414 
415   // Scan all the blocks in the loop that are not in subloops.
416   for (auto *BB : CurLoop->getBlocks()) {
417     // Ignore blocks in subloops.
418     if (LI->getLoopFor(BB) != CurLoop)
419       continue;
420 
421     MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
422   }
423   return MadeChange;
424 }
425 
426 static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {
427   const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));
428   return ConstStride->getAPInt();
429 }
430 
431 /// getMemSetPatternValue - If a strided store of the specified value is safe to
432 /// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should
433 /// be passed in.  Otherwise, return null.
434 ///
435 /// Note that we don't ever attempt to use memset_pattern8 or 4, because these
436 /// just replicate their input array and then pass on to memset_pattern16.
437 static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {
438   // FIXME: This could check for UndefValue because it can be merged into any
439   // other valid pattern.
440 
441   // If the value isn't a constant, we can't promote it to being in a constant
442   // array.  We could theoretically do a store to an alloca or something, but
443   // that doesn't seem worthwhile.
444   Constant *C = dyn_cast<Constant>(V);
445   if (!C)
446     return nullptr;
447 
448   // Only handle simple values that are a power of two bytes in size.
449   uint64_t Size = DL->getTypeSizeInBits(V->getType());
450   if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
451     return nullptr;
452 
453   // Don't care enough about darwin/ppc to implement this.
454   if (DL->isBigEndian())
455     return nullptr;
456 
457   // Convert to size in bytes.
458   Size /= 8;
459 
460   // TODO: If CI is larger than 16-bytes, we can try slicing it in half to see
461   // if the top and bottom are the same (e.g. for vectors and large integers).
462   if (Size > 16)
463     return nullptr;
464 
465   // If the constant is exactly 16 bytes, just use it.
466   if (Size == 16)
467     return C;
468 
469   // Otherwise, we'll use an array of the constants.
470   unsigned ArraySize = 16 / Size;
471   ArrayType *AT = ArrayType::get(V->getType(), ArraySize);
472   return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));
473 }
474 
475 LoopIdiomRecognize::LegalStoreKind
476 LoopIdiomRecognize::isLegalStore(StoreInst *SI) {
477   // Don't touch volatile stores.
478   if (SI->isVolatile())
479     return LegalStoreKind::None;
480   // We only want simple or unordered-atomic stores.
481   if (!SI->isUnordered())
482     return LegalStoreKind::None;
483 
484   // Avoid merging nontemporal stores.
485   if (SI->getMetadata(LLVMContext::MD_nontemporal))
486     return LegalStoreKind::None;
487 
488   Value *StoredVal = SI->getValueOperand();
489   Value *StorePtr = SI->getPointerOperand();
490 
491   // Don't convert stores of non-integral pointer types to memsets (which stores
492   // integers).
493   if (DL->isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
494     return LegalStoreKind::None;
495 
496   // Reject stores that are so large that they overflow an unsigned.
497   // When storing out scalable vectors we bail out for now, since the code
498   // below currently only works for constant strides.
499   TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());
500   if (SizeInBits.isScalable() || (SizeInBits.getFixedSize() & 7) ||
501       (SizeInBits.getFixedSize() >> 32) != 0)
502     return LegalStoreKind::None;
503 
504   // See if the pointer expression is an AddRec like {base,+,1} on the current
505   // loop, which indicates a strided store.  If we have something else, it's a
506   // random store we can't handle.
507   const SCEVAddRecExpr *StoreEv =
508       dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
509   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
510     return LegalStoreKind::None;
511 
512   // Check to see if we have a constant stride.
513   if (!isa<SCEVConstant>(StoreEv->getOperand(1)))
514     return LegalStoreKind::None;
515 
516   // See if the store can be turned into a memset.
517 
518   // If the stored value is a byte-wise value (like i32 -1), then it may be
519   // turned into a memset of i8 -1, assuming that all the consecutive bytes
520   // are stored.  A store of i32 0x01020304 can never be turned into a memset,
521   // but it can be turned into memset_pattern if the target supports it.
522   Value *SplatValue = isBytewiseValue(StoredVal, *DL);
523 
524   // Note: memset and memset_pattern on unordered-atomic is yet not supported
525   bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();
526 
527   // If we're allowed to form a memset, and the stored value would be
528   // acceptable for memset, use it.
529   if (!UnorderedAtomic && HasMemset && SplatValue && !DisableLIRP::Memset &&
530       // Verify that the stored value is loop invariant.  If not, we can't
531       // promote the memset.
532       CurLoop->isLoopInvariant(SplatValue)) {
533     // It looks like we can use SplatValue.
534     return LegalStoreKind::Memset;
535   }
536   if (!UnorderedAtomic && HasMemsetPattern && !DisableLIRP::Memset &&
537       // Don't create memset_pattern16s with address spaces.
538       StorePtr->getType()->getPointerAddressSpace() == 0 &&
539       getMemSetPatternValue(StoredVal, DL)) {
540     // It looks like we can use PatternValue!
541     return LegalStoreKind::MemsetPattern;
542   }
543 
544   // Otherwise, see if the store can be turned into a memcpy.
545   if (HasMemcpy && !DisableLIRP::Memcpy) {
546     // Check to see if the stride matches the size of the store.  If so, then we
547     // know that every byte is touched in the loop.
548     APInt Stride = getStoreStride(StoreEv);
549     unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
550     if (StoreSize != Stride && StoreSize != -Stride)
551       return LegalStoreKind::None;
552 
553     // The store must be feeding a non-volatile load.
554     LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());
555 
556     // Only allow non-volatile loads
557     if (!LI || LI->isVolatile())
558       return LegalStoreKind::None;
559     // Only allow simple or unordered-atomic loads
560     if (!LI->isUnordered())
561       return LegalStoreKind::None;
562 
563     // See if the pointer expression is an AddRec like {base,+,1} on the current
564     // loop, which indicates a strided load.  If we have something else, it's a
565     // random load we can't handle.
566     const SCEVAddRecExpr *LoadEv =
567         dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));
568     if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
569       return LegalStoreKind::None;
570 
571     // The store and load must share the same stride.
572     if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
573       return LegalStoreKind::None;
574 
575     // Success.  This store can be converted into a memcpy.
576     UnorderedAtomic = UnorderedAtomic || LI->isAtomic();
577     return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
578                            : LegalStoreKind::Memcpy;
579   }
580   // This store can't be transformed into a memset/memcpy.
581   return LegalStoreKind::None;
582 }
583 
584 void LoopIdiomRecognize::collectStores(BasicBlock *BB) {
585   StoreRefsForMemset.clear();
586   StoreRefsForMemsetPattern.clear();
587   StoreRefsForMemcpy.clear();
588   for (Instruction &I : *BB) {
589     StoreInst *SI = dyn_cast<StoreInst>(&I);
590     if (!SI)
591       continue;
592 
593     // Make sure this is a strided store with a constant stride.
594     switch (isLegalStore(SI)) {
595     case LegalStoreKind::None:
596       // Nothing to do
597       break;
598     case LegalStoreKind::Memset: {
599       // Find the base pointer.
600       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
601       StoreRefsForMemset[Ptr].push_back(SI);
602     } break;
603     case LegalStoreKind::MemsetPattern: {
604       // Find the base pointer.
605       Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
606       StoreRefsForMemsetPattern[Ptr].push_back(SI);
607     } break;
608     case LegalStoreKind::Memcpy:
609     case LegalStoreKind::UnorderedAtomicMemcpy:
610       StoreRefsForMemcpy.push_back(SI);
611       break;
612     default:
613       assert(false && "unhandled return value");
614       break;
615     }
616   }
617 }
618 
619 /// runOnLoopBlock - Process the specified block, which lives in a counted loop
620 /// with the specified backedge count.  This block is known to be in the current
621 /// loop and not in any subloops.
622 bool LoopIdiomRecognize::runOnLoopBlock(
623     BasicBlock *BB, const SCEV *BECount,
624     SmallVectorImpl<BasicBlock *> &ExitBlocks) {
625   // We can only promote stores in this block if they are unconditionally
626   // executed in the loop.  For a block to be unconditionally executed, it has
627   // to dominate all the exit blocks of the loop.  Verify this now.
628   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
629     if (!DT->dominates(BB, ExitBlocks[i]))
630       return false;
631 
632   bool MadeChange = false;
633   // Look for store instructions, which may be optimized to memset/memcpy.
634   collectStores(BB);
635 
636   // Look for a single store or sets of stores with a common base, which can be
637   // optimized into a memset (memset_pattern).  The latter most commonly happens
638   // with structs and handunrolled loops.
639   for (auto &SL : StoreRefsForMemset)
640     MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);
641 
642   for (auto &SL : StoreRefsForMemsetPattern)
643     MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);
644 
645   // Optimize the store into a memcpy, if it feeds an similarly strided load.
646   for (auto &SI : StoreRefsForMemcpy)
647     MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
648 
649   MadeChange |= processLoopMemIntrinsic<MemCpyInst>(
650       BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);
651   MadeChange |= processLoopMemIntrinsic<MemSetInst>(
652       BB, &LoopIdiomRecognize::processLoopMemSet, BECount);
653 
654   return MadeChange;
655 }
656 
657 /// See if this store(s) can be promoted to a memset.
658 bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,
659                                            const SCEV *BECount, ForMemset For) {
660   // Try to find consecutive stores that can be transformed into memsets.
661   SetVector<StoreInst *> Heads, Tails;
662   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
663 
664   // Do a quadratic search on all of the given stores and find
665   // all of the pairs of stores that follow each other.
666   SmallVector<unsigned, 16> IndexQueue;
667   for (unsigned i = 0, e = SL.size(); i < e; ++i) {
668     assert(SL[i]->isSimple() && "Expected only non-volatile stores.");
669 
670     Value *FirstStoredVal = SL[i]->getValueOperand();
671     Value *FirstStorePtr = SL[i]->getPointerOperand();
672     const SCEVAddRecExpr *FirstStoreEv =
673         cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));
674     APInt FirstStride = getStoreStride(FirstStoreEv);
675     unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());
676 
677     // See if we can optimize just this store in isolation.
678     if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
679       Heads.insert(SL[i]);
680       continue;
681     }
682 
683     Value *FirstSplatValue = nullptr;
684     Constant *FirstPatternValue = nullptr;
685 
686     if (For == ForMemset::Yes)
687       FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);
688     else
689       FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);
690 
691     assert((FirstSplatValue || FirstPatternValue) &&
692            "Expected either splat value or pattern value.");
693 
694     IndexQueue.clear();
695     // If a store has multiple consecutive store candidates, search Stores
696     // array according to the sequence: from i+1 to e, then from i-1 to 0.
697     // This is because usually pairing with immediate succeeding or preceding
698     // candidate create the best chance to find memset opportunity.
699     unsigned j = 0;
700     for (j = i + 1; j < e; ++j)
701       IndexQueue.push_back(j);
702     for (j = i; j > 0; --j)
703       IndexQueue.push_back(j - 1);
704 
705     for (auto &k : IndexQueue) {
706       assert(SL[k]->isSimple() && "Expected only non-volatile stores.");
707       Value *SecondStorePtr = SL[k]->getPointerOperand();
708       const SCEVAddRecExpr *SecondStoreEv =
709           cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));
710       APInt SecondStride = getStoreStride(SecondStoreEv);
711 
712       if (FirstStride != SecondStride)
713         continue;
714 
715       Value *SecondStoredVal = SL[k]->getValueOperand();
716       Value *SecondSplatValue = nullptr;
717       Constant *SecondPatternValue = nullptr;
718 
719       if (For == ForMemset::Yes)
720         SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);
721       else
722         SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);
723 
724       assert((SecondSplatValue || SecondPatternValue) &&
725              "Expected either splat value or pattern value.");
726 
727       if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {
728         if (For == ForMemset::Yes) {
729           if (isa<UndefValue>(FirstSplatValue))
730             FirstSplatValue = SecondSplatValue;
731           if (FirstSplatValue != SecondSplatValue)
732             continue;
733         } else {
734           if (isa<UndefValue>(FirstPatternValue))
735             FirstPatternValue = SecondPatternValue;
736           if (FirstPatternValue != SecondPatternValue)
737             continue;
738         }
739         Tails.insert(SL[k]);
740         Heads.insert(SL[i]);
741         ConsecutiveChain[SL[i]] = SL[k];
742         break;
743       }
744     }
745   }
746 
747   // We may run into multiple chains that merge into a single chain. We mark the
748   // stores that we transformed so that we don't visit the same store twice.
749   SmallPtrSet<Value *, 16> TransformedStores;
750   bool Changed = false;
751 
752   // For stores that start but don't end a link in the chain:
753   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
754        it != e; ++it) {
755     if (Tails.count(*it))
756       continue;
757 
758     // We found a store instr that starts a chain. Now follow the chain and try
759     // to transform it.
760     SmallPtrSet<Instruction *, 8> AdjacentStores;
761     StoreInst *I = *it;
762 
763     StoreInst *HeadStore = I;
764     unsigned StoreSize = 0;
765 
766     // Collect the chain into a list.
767     while (Tails.count(I) || Heads.count(I)) {
768       if (TransformedStores.count(I))
769         break;
770       AdjacentStores.insert(I);
771 
772       StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
773       // Move to the next value in the chain.
774       I = ConsecutiveChain[I];
775     }
776 
777     Value *StoredVal = HeadStore->getValueOperand();
778     Value *StorePtr = HeadStore->getPointerOperand();
779     const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
780     APInt Stride = getStoreStride(StoreEv);
781 
782     // Check to see if the stride matches the size of the stores.  If so, then
783     // we know that every byte is touched in the loop.
784     if (StoreSize != Stride && StoreSize != -Stride)
785       continue;
786 
787     bool IsNegStride = StoreSize == -Stride;
788 
789     const SCEV *StoreSizeSCEV = SE->getConstant(BECount->getType(), StoreSize);
790     if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
791                                 MaybeAlign(HeadStore->getAlignment()),
792                                 StoredVal, HeadStore, AdjacentStores, StoreEv,
793                                 BECount, IsNegStride)) {
794       TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
795       Changed = true;
796     }
797   }
798 
799   return Changed;
800 }
801 
802 /// processLoopMemIntrinsic - Template function for calling different processor
803 /// functions based on mem instrinsic type.
804 template <typename MemInst>
805 bool LoopIdiomRecognize::processLoopMemIntrinsic(
806     BasicBlock *BB,
807     bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
808     const SCEV *BECount) {
809   bool MadeChange = false;
810   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
811     Instruction *Inst = &*I++;
812     // Look for memory instructions, which may be optimized to a larger one.
813     if (MemInst *MI = dyn_cast<MemInst>(Inst)) {
814       WeakTrackingVH InstPtr(&*I);
815       if (!(this->*Processor)(MI, BECount))
816         continue;
817       MadeChange = true;
818 
819       // If processing the instruction invalidated our iterator, start over from
820       // the top of the block.
821       if (!InstPtr)
822         I = BB->begin();
823     }
824   }
825   return MadeChange;
826 }
827 
828 /// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy
829 bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,
830                                            const SCEV *BECount) {
831   // We can only handle non-volatile memcpys with a constant size.
832   if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))
833     return false;
834 
835   // If we're not allowed to hack on memcpy, we fail.
836   if ((!HasMemcpy && !isa<MemCpyInlineInst>(MCI)) || DisableLIRP::Memcpy)
837     return false;
838 
839   Value *Dest = MCI->getDest();
840   Value *Source = MCI->getSource();
841   if (!Dest || !Source)
842     return false;
843 
844   // See if the load and store pointer expressions are AddRec like {base,+,1} on
845   // the current loop, which indicates a strided load and store.  If we have
846   // something else, it's a random load or store we can't handle.
847   const SCEVAddRecExpr *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Dest));
848   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
849     return false;
850   const SCEVAddRecExpr *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Source));
851   if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
852     return false;
853 
854   // Reject memcpys that are so large that they overflow an unsigned.
855   uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();
856   if ((SizeInBytes >> 32) != 0)
857     return false;
858 
859   // Check if the stride matches the size of the memcpy. If so, then we know
860   // that every byte is touched in the loop.
861   const SCEVConstant *StoreStride =
862       dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
863   const SCEVConstant *LoadStride =
864       dyn_cast<SCEVConstant>(LoadEv->getOperand(1));
865   if (!StoreStride || !LoadStride)
866     return false;
867 
868   APInt StoreStrideValue = StoreStride->getAPInt();
869   APInt LoadStrideValue = LoadStride->getAPInt();
870   // Huge stride value - give up
871   if (StoreStrideValue.getBitWidth() > 64 || LoadStrideValue.getBitWidth() > 64)
872     return false;
873 
874   if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) {
875     ORE.emit([&]() {
876       return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI)
877              << ore::NV("Inst", "memcpy") << " in "
878              << ore::NV("Function", MCI->getFunction())
879              << " function will not be hoised: "
880              << ore::NV("Reason", "memcpy size is not equal to stride");
881     });
882     return false;
883   }
884 
885   int64_t StoreStrideInt = StoreStrideValue.getSExtValue();
886   int64_t LoadStrideInt = LoadStrideValue.getSExtValue();
887   // Check if the load stride matches the store stride.
888   if (StoreStrideInt != LoadStrideInt)
889     return false;
890 
891   return processLoopStoreOfLoopLoad(Dest, Source, (unsigned)SizeInBytes,
892                                     MCI->getDestAlign(), MCI->getSourceAlign(),
893                                     MCI, MCI, StoreEv, LoadEv, BECount);
894 }
895 
896 /// processLoopMemSet - See if this memset can be promoted to a large memset.
897 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
898                                            const SCEV *BECount) {
899   // We can only handle non-volatile memsets with a constant size.
900   if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
901     return false;
902 
903   // If we're not allowed to hack on memset, we fail.
904   if (!HasMemset || DisableLIRP::Memset)
905     return false;
906 
907   Value *Pointer = MSI->getDest();
908 
909   // See if the pointer expression is an AddRec like {base,+,1} on the current
910   // loop, which indicates a strided store.  If we have something else, it's a
911   // random store we can't handle.
912   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
913   if (!Ev || Ev->getLoop() != CurLoop || !Ev->isAffine())
914     return false;
915 
916   // Reject memsets that are so large that they overflow an unsigned.
917   uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
918   if ((SizeInBytes >> 32) != 0)
919     return false;
920 
921   // Check to see if the stride matches the size of the memset.  If so, then we
922   // know that every byte is touched in the loop.
923   const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
924   if (!ConstStride)
925     return false;
926 
927   APInt Stride = ConstStride->getAPInt();
928   if (SizeInBytes != Stride && SizeInBytes != -Stride)
929     return false;
930 
931   // Verify that the memset value is loop invariant.  If not, we can't promote
932   // the memset.
933   Value *SplatValue = MSI->getValue();
934   if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
935     return false;
936 
937   SmallPtrSet<Instruction *, 1> MSIs;
938   MSIs.insert(MSI);
939   bool IsNegStride = SizeInBytes == -Stride;
940   return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()),
941                                  MaybeAlign(MSI->getDestAlignment()),
942                                  SplatValue, MSI, MSIs, Ev, BECount,
943                                  IsNegStride, /*IsLoopMemset=*/true);
944 }
945 
946 /// mayLoopAccessLocation - Return true if the specified loop might access the
947 /// specified pointer location, which is a loop-strided access.  The 'Access'
948 /// argument specifies what the verboten forms of access are (read or write).
949 static bool
950 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
951                       const SCEV *BECount, const SCEV *StoreSizeSCEV,
952                       AliasAnalysis &AA,
953                       SmallPtrSetImpl<Instruction *> &IgnoredStores) {
954   // Get the location that may be stored across the loop.  Since the access is
955   // strided positively through memory, we say that the modified location starts
956   // at the pointer and has infinite size.
957   LocationSize AccessSize = LocationSize::afterPointer();
958 
959   // If the loop iterates a fixed number of times, we can refine the access size
960   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
961   const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount);
962   const SCEVConstant *ConstSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
963   if (BECst && ConstSize)
964     AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
965                                        ConstSize->getValue()->getZExtValue());
966 
967   // TODO: For this to be really effective, we have to dive into the pointer
968   // operand in the store.  Store to &A[i] of 100 will always return may alias
969   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
970   // which will then no-alias a store to &A[100].
971   MemoryLocation StoreLoc(Ptr, AccessSize);
972 
973   for (Loop::block_iterator BI = L->block_begin(), E = L->block_end(); BI != E;
974        ++BI)
975     for (Instruction &I : **BI)
976       if (IgnoredStores.count(&I) == 0 &&
977           isModOrRefSet(
978               intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
979         return true;
980   return false;
981 }
982 
983 // If we have a negative stride, Start refers to the end of the memory location
984 // we're trying to memset.  Therefore, we need to recompute the base pointer,
985 // which is just Start - BECount*Size.
986 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
987                                         Type *IntPtr, const SCEV *StoreSizeSCEV,
988                                         ScalarEvolution *SE) {
989   const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
990   if (!StoreSizeSCEV->isOne()) {
991     // index = back edge count * store size
992     Index = SE->getMulExpr(Index,
993                            SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
994                            SCEV::FlagNUW);
995   }
996   // base pointer = start - index * store size
997   return SE->getMinusSCEV(Start, Index);
998 }
999 
1000 /// Compute trip count from the backedge taken count.
1001 static const SCEV *getTripCount(const SCEV *BECount, Type *IntPtr,
1002                                 Loop *CurLoop, const DataLayout *DL,
1003                                 ScalarEvolution *SE) {
1004   const SCEV *TripCountS = nullptr;
1005   // The # stored bytes is (BECount+1).  Expand the trip count out to
1006   // pointer size if it isn't already.
1007   //
1008   // If we're going to need to zero extend the BE count, check if we can add
1009   // one to it prior to zero extending without overflow. Provided this is safe,
1010   // it allows better simplification of the +1.
1011   if (DL->getTypeSizeInBits(BECount->getType()) <
1012           DL->getTypeSizeInBits(IntPtr) &&
1013       SE->isLoopEntryGuardedByCond(
1014           CurLoop, ICmpInst::ICMP_NE, BECount,
1015           SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
1016     TripCountS = SE->getZeroExtendExpr(
1017         SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
1018         IntPtr);
1019   } else {
1020     TripCountS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
1021                                 SE->getOne(IntPtr), SCEV::FlagNUW);
1022   }
1023 
1024   return TripCountS;
1025 }
1026 
1027 /// Compute the number of bytes as a SCEV from the backedge taken count.
1028 ///
1029 /// This also maps the SCEV into the provided type and tries to handle the
1030 /// computation in a way that will fold cleanly.
1031 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
1032                                unsigned StoreSize, Loop *CurLoop,
1033                                const DataLayout *DL, ScalarEvolution *SE) {
1034   const SCEV *TripCountSCEV = getTripCount(BECount, IntPtr, CurLoop, DL, SE);
1035 
1036   // And scale it based on the store size.
1037   if (StoreSize != 1) {
1038     return SE->getMulExpr(TripCountSCEV, SE->getConstant(IntPtr, StoreSize),
1039                           SCEV::FlagNUW);
1040   }
1041   return TripCountSCEV;
1042 }
1043 
1044 /// getNumBytes that takes StoreSize as a SCEV
1045 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
1046                                const SCEV *StoreSizeSCEV, Loop *CurLoop,
1047                                const DataLayout *DL, ScalarEvolution *SE) {
1048   const SCEV *TripCountSCEV = getTripCount(BECount, IntPtr, CurLoop, DL, SE);
1049 
1050   return SE->getMulExpr(TripCountSCEV,
1051                         SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1052                         SCEV::FlagNUW);
1053 }
1054 
1055 /// processLoopStridedStore - We see a strided store of some value.  If we can
1056 /// transform this into a memset or memset_pattern in the loop preheader, do so.
1057 bool LoopIdiomRecognize::processLoopStridedStore(
1058     Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment,
1059     Value *StoredVal, Instruction *TheStore,
1060     SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
1061     const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) {
1062   Value *SplatValue = isBytewiseValue(StoredVal, *DL);
1063   Constant *PatternValue = nullptr;
1064 
1065   if (!SplatValue)
1066     PatternValue = getMemSetPatternValue(StoredVal, DL);
1067 
1068   assert((SplatValue || PatternValue) &&
1069          "Expected either splat value or pattern value.");
1070 
1071   // The trip count of the loop and the base pointer of the addrec SCEV is
1072   // guaranteed to be loop invariant, which means that it should dominate the
1073   // header.  This allows us to insert code for it in the preheader.
1074   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
1075   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1076   IRBuilder<> Builder(Preheader->getTerminator());
1077   SCEVExpander Expander(*SE, *DL, "loop-idiom");
1078   SCEVExpanderCleaner ExpCleaner(Expander, *DT);
1079 
1080   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
1081   Type *IntIdxTy = DL->getIndexType(DestPtr->getType());
1082 
1083   bool Changed = false;
1084   const SCEV *Start = Ev->getStart();
1085   // Handle negative strided loops.
1086   if (IsNegStride)
1087     Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE);
1088 
1089   // TODO: ideally we should still be able to generate memset if SCEV expander
1090   // is taught to generate the dependencies at the latest point.
1091   if (!isSafeToExpand(Start, *SE))
1092     return Changed;
1093 
1094   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
1095   // this into a memset in the loop preheader now if we want.  However, this
1096   // would be unsafe to do if there is anything else in the loop that may read
1097   // or write to the aliased location.  Check for any overlap by generating the
1098   // base pointer and checking the region.
1099   Value *BasePtr =
1100       Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
1101 
1102   // From here on out, conservatively report to the pass manager that we've
1103   // changed the IR, even if we later clean up these added instructions. There
1104   // may be structural differences e.g. in the order of use lists not accounted
1105   // for in just a textual dump of the IR. This is written as a variable, even
1106   // though statically all the places this dominates could be replaced with
1107   // 'true', with the hope that anyone trying to be clever / "more precise" with
1108   // the return value will read this comment, and leave them alone.
1109   Changed = true;
1110 
1111   if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1112                             StoreSizeSCEV, *AA, Stores))
1113     return Changed;
1114 
1115   if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
1116     return Changed;
1117 
1118   // Okay, everything looks good, insert the memset.
1119 
1120   const SCEV *NumBytesS =
1121       getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1122 
1123   // TODO: ideally we should still be able to generate memset if SCEV expander
1124   // is taught to generate the dependencies at the latest point.
1125   if (!isSafeToExpand(NumBytesS, *SE))
1126     return Changed;
1127 
1128   Value *NumBytes =
1129       Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1130 
1131   CallInst *NewCall;
1132   if (SplatValue) {
1133     NewCall = Builder.CreateMemSet(BasePtr, SplatValue, NumBytes,
1134                                    MaybeAlign(StoreAlignment));
1135   } else {
1136     // Everything is emitted in default address space
1137     Type *Int8PtrTy = DestInt8PtrTy;
1138 
1139     Module *M = TheStore->getModule();
1140     StringRef FuncName = "memset_pattern16";
1141     FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(),
1142                                                 Int8PtrTy, Int8PtrTy, IntIdxTy);
1143     inferLibFuncAttributes(M, FuncName, *TLI);
1144 
1145     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
1146     // an constant array of 16-bytes.  Plop the value into a mergable global.
1147     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1148                                             GlobalValue::PrivateLinkage,
1149                                             PatternValue, ".memset_pattern");
1150     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
1151     GV->setAlignment(Align(16));
1152     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
1153     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
1154   }
1155   NewCall->setDebugLoc(TheStore->getDebugLoc());
1156 
1157   if (MSSAU) {
1158     MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1159         NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1160     MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1161   }
1162 
1163   LLVM_DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
1164                     << "    from store to: " << *Ev << " at: " << *TheStore
1165                     << "\n");
1166 
1167   ORE.emit([&]() {
1168     return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStridedStore",
1169                               NewCall->getDebugLoc(), Preheader)
1170            << "Transformed loop-strided store in "
1171            << ore::NV("Function", TheStore->getFunction())
1172            << " function into a call to "
1173            << ore::NV("NewFunction", NewCall->getCalledFunction())
1174            << "() intrinsic";
1175   });
1176 
1177   // Okay, the memset has been formed.  Zap the original store and anything that
1178   // feeds into it.
1179   for (auto *I : Stores) {
1180     if (MSSAU)
1181       MSSAU->removeMemoryAccess(I, true);
1182     deleteDeadInstruction(I);
1183   }
1184   if (MSSAU && VerifyMemorySSA)
1185     MSSAU->getMemorySSA()->verifyMemorySSA();
1186   ++NumMemSet;
1187   ExpCleaner.markResultUsed();
1188   return true;
1189 }
1190 
1191 /// If the stored value is a strided load in the same loop with the same stride
1192 /// this may be transformable into a memcpy.  This kicks in for stuff like
1193 /// for (i) A[i] = B[i];
1194 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
1195                                                     const SCEV *BECount) {
1196   assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
1197 
1198   Value *StorePtr = SI->getPointerOperand();
1199   const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1200   unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1201 
1202   // The store must be feeding a non-volatile load.
1203   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1204   assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
1205 
1206   // See if the pointer expression is an AddRec like {base,+,1} on the current
1207   // loop, which indicates a strided load.  If we have something else, it's a
1208   // random load we can't handle.
1209   Value *LoadPtr = LI->getPointerOperand();
1210   const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1211   return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSize,
1212                                     SI->getAlign(), LI->getAlign(), SI, LI,
1213                                     StoreEv, LoadEv, BECount);
1214 }
1215 
1216 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1217     Value *DestPtr, Value *SourcePtr, unsigned StoreSize, MaybeAlign StoreAlign,
1218     MaybeAlign LoadAlign, Instruction *TheStore, Instruction *TheLoad,
1219     const SCEVAddRecExpr *StoreEv, const SCEVAddRecExpr *LoadEv,
1220     const SCEV *BECount) {
1221 
1222   // FIXME: until llvm.memcpy.inline supports dynamic sizes, we need to
1223   // conservatively bail here, since otherwise we may have to transform
1224   // llvm.memcpy.inline into llvm.memcpy which is illegal.
1225   if (isa<MemCpyInlineInst>(TheStore))
1226     return false;
1227 
1228   // The trip count of the loop and the base pointer of the addrec SCEV is
1229   // guaranteed to be loop invariant, which means that it should dominate the
1230   // header.  This allows us to insert code for it in the preheader.
1231   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1232   IRBuilder<> Builder(Preheader->getTerminator());
1233   SCEVExpander Expander(*SE, *DL, "loop-idiom");
1234 
1235   SCEVExpanderCleaner ExpCleaner(Expander, *DT);
1236 
1237   bool Changed = false;
1238   const SCEV *StrStart = StoreEv->getStart();
1239   unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();
1240   Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));
1241 
1242   APInt Stride = getStoreStride(StoreEv);
1243   bool IsNegStride = StoreSize == -Stride;
1244 
1245   const SCEV *StoreSizeSCEV = SE->getConstant(BECount->getType(), StoreSize);
1246   // Handle negative strided loops.
1247   if (IsNegStride)
1248     StrStart =
1249         getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1250 
1251   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
1252   // this into a memcpy in the loop preheader now if we want.  However, this
1253   // would be unsafe to do if there is anything else in the loop that may read
1254   // or write the memory region we're storing to.  This includes the load that
1255   // feeds the stores.  Check for an alias by generating the base address and
1256   // checking everything.
1257   Value *StoreBasePtr = Expander.expandCodeFor(
1258       StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
1259 
1260   // From here on out, conservatively report to the pass manager that we've
1261   // changed the IR, even if we later clean up these added instructions. There
1262   // may be structural differences e.g. in the order of use lists not accounted
1263   // for in just a textual dump of the IR. This is written as a variable, even
1264   // though statically all the places this dominates could be replaced with
1265   // 'true', with the hope that anyone trying to be clever / "more precise" with
1266   // the return value will read this comment, and leave them alone.
1267   Changed = true;
1268 
1269   SmallPtrSet<Instruction *, 2> Stores;
1270   Stores.insert(TheStore);
1271 
1272   bool IsMemCpy = isa<MemCpyInst>(TheStore);
1273   const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";
1274 
1275   bool UseMemMove =
1276       mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1277                             StoreSizeSCEV, *AA, Stores);
1278   if (UseMemMove) {
1279     Stores.insert(TheLoad);
1280     if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
1281                               BECount, StoreSizeSCEV, *AA, Stores)) {
1282       ORE.emit([&]() {
1283         return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore",
1284                                         TheStore)
1285                << ore::NV("Inst", InstRemark) << " in "
1286                << ore::NV("Function", TheStore->getFunction())
1287                << " function will not be hoisted: "
1288                << ore::NV("Reason", "The loop may access store location");
1289       });
1290       return Changed;
1291     }
1292     Stores.erase(TheLoad);
1293   }
1294 
1295   const SCEV *LdStart = LoadEv->getStart();
1296   unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();
1297 
1298   // Handle negative strided loops.
1299   if (IsNegStride)
1300     LdStart =
1301         getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1302 
1303   // For a memcpy, we have to make sure that the input array is not being
1304   // mutated by the loop.
1305   Value *LoadBasePtr = Expander.expandCodeFor(
1306       LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
1307 
1308   // If the store is a memcpy instruction, we must check if it will write to
1309   // the load memory locations. So remove it from the ignored stores.
1310   if (IsMemCpy)
1311     Stores.erase(TheStore);
1312   if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1313                             StoreSizeSCEV, *AA, Stores)) {
1314     ORE.emit([&]() {
1315       return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad)
1316              << ore::NV("Inst", InstRemark) << " in "
1317              << ore::NV("Function", TheStore->getFunction())
1318              << " function will not be hoisted: "
1319              << ore::NV("Reason", "The loop may access load location");
1320     });
1321     return Changed;
1322   }
1323   if (UseMemMove) {
1324     // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr for
1325     // negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr.
1326     int64_t LoadOff = 0, StoreOff = 0;
1327     const Value *BP1 = llvm::GetPointerBaseWithConstantOffset(
1328         LoadBasePtr->stripPointerCasts(), LoadOff, *DL);
1329     const Value *BP2 = llvm::GetPointerBaseWithConstantOffset(
1330         StoreBasePtr->stripPointerCasts(), StoreOff, *DL);
1331     int64_t LoadSize =
1332         DL->getTypeSizeInBits(TheLoad->getType()).getFixedSize() / 8;
1333     if (BP1 != BP2 || LoadSize != int64_t(StoreSize))
1334       return Changed;
1335     if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) ||
1336         (IsNegStride && LoadOff + LoadSize > StoreOff))
1337       return Changed;
1338   }
1339 
1340   if (avoidLIRForMultiBlockLoop())
1341     return Changed;
1342 
1343   // Okay, everything is safe, we can transform this!
1344 
1345   const SCEV *NumBytesS =
1346       getNumBytes(BECount, IntIdxTy, StoreSize, CurLoop, DL, SE);
1347 
1348   Value *NumBytes =
1349       Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1350 
1351   CallInst *NewCall = nullptr;
1352   // Check whether to generate an unordered atomic memcpy:
1353   //  If the load or store are atomic, then they must necessarily be unordered
1354   //  by previous checks.
1355   if (!TheStore->isAtomic() && !TheLoad->isAtomic()) {
1356     if (UseMemMove)
1357       NewCall = Builder.CreateMemMove(StoreBasePtr, StoreAlign, LoadBasePtr,
1358                                       LoadAlign, NumBytes);
1359     else
1360       NewCall = Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr,
1361                                      LoadAlign, NumBytes);
1362   } else {
1363     // For now don't support unordered atomic memmove.
1364     if (UseMemMove)
1365       return Changed;
1366     // We cannot allow unaligned ops for unordered load/store, so reject
1367     // anything where the alignment isn't at least the element size.
1368     assert((StoreAlign.hasValue() && LoadAlign.hasValue()) &&
1369            "Expect unordered load/store to have align.");
1370     if (StoreAlign.getValue() < StoreSize || LoadAlign.getValue() < StoreSize)
1371       return Changed;
1372 
1373     // If the element.atomic memcpy is not lowered into explicit
1374     // loads/stores later, then it will be lowered into an element-size
1375     // specific lib call. If the lib call doesn't exist for our store size, then
1376     // we shouldn't generate the memcpy.
1377     if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1378       return Changed;
1379 
1380     // Create the call.
1381     // Note that unordered atomic loads/stores are *required* by the spec to
1382     // have an alignment but non-atomic loads/stores may not.
1383     NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1384         StoreBasePtr, StoreAlign.getValue(), LoadBasePtr, LoadAlign.getValue(),
1385         NumBytes, StoreSize);
1386   }
1387   NewCall->setDebugLoc(TheStore->getDebugLoc());
1388 
1389   if (MSSAU) {
1390     MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1391         NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1392     MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1393   }
1394 
1395   LLVM_DEBUG(dbgs() << "  Formed new call: " << *NewCall << "\n"
1396                     << "    from load ptr=" << *LoadEv << " at: " << *TheLoad
1397                     << "\n"
1398                     << "    from store ptr=" << *StoreEv << " at: " << *TheStore
1399                     << "\n");
1400 
1401   ORE.emit([&]() {
1402     return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",
1403                               NewCall->getDebugLoc(), Preheader)
1404            << "Formed a call to "
1405            << ore::NV("NewFunction", NewCall->getCalledFunction())
1406            << "() intrinsic from " << ore::NV("Inst", InstRemark)
1407            << " instruction in " << ore::NV("Function", TheStore->getFunction())
1408            << " function";
1409   });
1410 
1411   // Okay, the memcpy has been formed.  Zap the original store and anything that
1412   // feeds into it.
1413   if (MSSAU)
1414     MSSAU->removeMemoryAccess(TheStore, true);
1415   deleteDeadInstruction(TheStore);
1416   if (MSSAU && VerifyMemorySSA)
1417     MSSAU->getMemorySSA()->verifyMemorySSA();
1418   if (UseMemMove)
1419     ++NumMemMove;
1420   else
1421     ++NumMemCpy;
1422   ExpCleaner.markResultUsed();
1423   return true;
1424 }
1425 
1426 // When compiling for codesize we avoid idiom recognition for a multi-block loop
1427 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1428 //
1429 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1430                                                    bool IsLoopMemset) {
1431   if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1432     if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {
1433       LLVM_DEBUG(dbgs() << "  " << CurLoop->getHeader()->getParent()->getName()
1434                         << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1435                         << " avoided: multi-block top-level loop\n");
1436       return true;
1437     }
1438   }
1439 
1440   return false;
1441 }
1442 
1443 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1444   LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
1445                     << CurLoop->getHeader()->getParent()->getName()
1446                     << "] Noncountable Loop %"
1447                     << CurLoop->getHeader()->getName() << "\n");
1448 
1449   return recognizePopcount() || recognizeAndInsertFFS() ||
1450          recognizeShiftUntilBitTest() || recognizeShiftUntilZero();
1451 }
1452 
1453 /// Check if the given conditional branch is based on the comparison between
1454 /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
1455 /// true), the control yields to the loop entry. If the branch matches the
1456 /// behavior, the variable involved in the comparison is returned. This function
1457 /// will be called to see if the precondition and postcondition of the loop are
1458 /// in desirable form.
1459 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,
1460                              bool JmpOnZero = false) {
1461   if (!BI || !BI->isConditional())
1462     return nullptr;
1463 
1464   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1465   if (!Cond)
1466     return nullptr;
1467 
1468   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1469   if (!CmpZero || !CmpZero->isZero())
1470     return nullptr;
1471 
1472   BasicBlock *TrueSucc = BI->getSuccessor(0);
1473   BasicBlock *FalseSucc = BI->getSuccessor(1);
1474   if (JmpOnZero)
1475     std::swap(TrueSucc, FalseSucc);
1476 
1477   ICmpInst::Predicate Pred = Cond->getPredicate();
1478   if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
1479       (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
1480     return Cond->getOperand(0);
1481 
1482   return nullptr;
1483 }
1484 
1485 // Check if the recurrence variable `VarX` is in the right form to create
1486 // the idiom. Returns the value coerced to a PHINode if so.
1487 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1488                                  BasicBlock *LoopEntry) {
1489   auto *PhiX = dyn_cast<PHINode>(VarX);
1490   if (PhiX && PhiX->getParent() == LoopEntry &&
1491       (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1492     return PhiX;
1493   return nullptr;
1494 }
1495 
1496 /// Return true iff the idiom is detected in the loop.
1497 ///
1498 /// Additionally:
1499 /// 1) \p CntInst is set to the instruction counting the population bit.
1500 /// 2) \p CntPhi is set to the corresponding phi node.
1501 /// 3) \p Var is set to the value whose population bits are being counted.
1502 ///
1503 /// The core idiom we are trying to detect is:
1504 /// \code
1505 ///    if (x0 != 0)
1506 ///      goto loop-exit // the precondition of the loop
1507 ///    cnt0 = init-val;
1508 ///    do {
1509 ///       x1 = phi (x0, x2);
1510 ///       cnt1 = phi(cnt0, cnt2);
1511 ///
1512 ///       cnt2 = cnt1 + 1;
1513 ///        ...
1514 ///       x2 = x1 & (x1 - 1);
1515 ///        ...
1516 ///    } while(x != 0);
1517 ///
1518 /// loop-exit:
1519 /// \endcode
1520 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1521                                 Instruction *&CntInst, PHINode *&CntPhi,
1522                                 Value *&Var) {
1523   // step 1: Check to see if the look-back branch match this pattern:
1524   //    "if (a!=0) goto loop-entry".
1525   BasicBlock *LoopEntry;
1526   Instruction *DefX2, *CountInst;
1527   Value *VarX1, *VarX0;
1528   PHINode *PhiX, *CountPhi;
1529 
1530   DefX2 = CountInst = nullptr;
1531   VarX1 = VarX0 = nullptr;
1532   PhiX = CountPhi = nullptr;
1533   LoopEntry = *(CurLoop->block_begin());
1534 
1535   // step 1: Check if the loop-back branch is in desirable form.
1536   {
1537     if (Value *T = matchCondition(
1538             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1539       DefX2 = dyn_cast<Instruction>(T);
1540     else
1541       return false;
1542   }
1543 
1544   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1545   {
1546     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1547       return false;
1548 
1549     BinaryOperator *SubOneOp;
1550 
1551     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1552       VarX1 = DefX2->getOperand(1);
1553     else {
1554       VarX1 = DefX2->getOperand(0);
1555       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1556     }
1557     if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
1558       return false;
1559 
1560     ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
1561     if (!Dec ||
1562         !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1563           (SubOneOp->getOpcode() == Instruction::Add &&
1564            Dec->isMinusOne()))) {
1565       return false;
1566     }
1567   }
1568 
1569   // step 3: Check the recurrence of variable X
1570   PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1571   if (!PhiX)
1572     return false;
1573 
1574   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1575   {
1576     CountInst = nullptr;
1577     for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1578                               IterE = LoopEntry->end();
1579          Iter != IterE; Iter++) {
1580       Instruction *Inst = &*Iter;
1581       if (Inst->getOpcode() != Instruction::Add)
1582         continue;
1583 
1584       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1585       if (!Inc || !Inc->isOne())
1586         continue;
1587 
1588       PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1589       if (!Phi)
1590         continue;
1591 
1592       // Check if the result of the instruction is live of the loop.
1593       bool LiveOutLoop = false;
1594       for (User *U : Inst->users()) {
1595         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1596           LiveOutLoop = true;
1597           break;
1598         }
1599       }
1600 
1601       if (LiveOutLoop) {
1602         CountInst = Inst;
1603         CountPhi = Phi;
1604         break;
1605       }
1606     }
1607 
1608     if (!CountInst)
1609       return false;
1610   }
1611 
1612   // step 5: check if the precondition is in this form:
1613   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1614   {
1615     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1616     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1617     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1618       return false;
1619 
1620     CntInst = CountInst;
1621     CntPhi = CountPhi;
1622     Var = T;
1623   }
1624 
1625   return true;
1626 }
1627 
1628 /// Return true if the idiom is detected in the loop.
1629 ///
1630 /// Additionally:
1631 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1632 ///       or nullptr if there is no such.
1633 /// 2) \p CntPhi is set to the corresponding phi node
1634 ///       or nullptr if there is no such.
1635 /// 3) \p Var is set to the value whose CTLZ could be used.
1636 /// 4) \p DefX is set to the instruction calculating Loop exit condition.
1637 ///
1638 /// The core idiom we are trying to detect is:
1639 /// \code
1640 ///    if (x0 == 0)
1641 ///      goto loop-exit // the precondition of the loop
1642 ///    cnt0 = init-val;
1643 ///    do {
1644 ///       x = phi (x0, x.next);   //PhiX
1645 ///       cnt = phi(cnt0, cnt.next);
1646 ///
1647 ///       cnt.next = cnt + 1;
1648 ///        ...
1649 ///       x.next = x >> 1;   // DefX
1650 ///        ...
1651 ///    } while(x.next != 0);
1652 ///
1653 /// loop-exit:
1654 /// \endcode
1655 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
1656                                       Intrinsic::ID &IntrinID, Value *&InitX,
1657                                       Instruction *&CntInst, PHINode *&CntPhi,
1658                                       Instruction *&DefX) {
1659   BasicBlock *LoopEntry;
1660   Value *VarX = nullptr;
1661 
1662   DefX = nullptr;
1663   CntInst = nullptr;
1664   CntPhi = nullptr;
1665   LoopEntry = *(CurLoop->block_begin());
1666 
1667   // step 1: Check if the loop-back branch is in desirable form.
1668   if (Value *T = matchCondition(
1669           dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1670     DefX = dyn_cast<Instruction>(T);
1671   else
1672     return false;
1673 
1674   // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
1675   if (!DefX || !DefX->isShift())
1676     return false;
1677   IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1678                                                      Intrinsic::ctlz;
1679   ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1680   if (!Shft || !Shft->isOne())
1681     return false;
1682   VarX = DefX->getOperand(0);
1683 
1684   // step 3: Check the recurrence of variable X
1685   PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1686   if (!PhiX)
1687     return false;
1688 
1689   InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1690 
1691   // Make sure the initial value can't be negative otherwise the ashr in the
1692   // loop might never reach zero which would make the loop infinite.
1693   if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
1694     return false;
1695 
1696   // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1697   //         or cnt.next = cnt + -1.
1698   // TODO: We can skip the step. If loop trip count is known (CTLZ),
1699   //       then all uses of "cnt.next" could be optimized to the trip count
1700   //       plus "cnt0". Currently it is not optimized.
1701   //       This step could be used to detect POPCNT instruction:
1702   //       cnt.next = cnt + (x.next & 1)
1703   for (BasicBlock::iterator Iter = LoopEntry->getFirstNonPHI()->getIterator(),
1704                             IterE = LoopEntry->end();
1705        Iter != IterE; Iter++) {
1706     Instruction *Inst = &*Iter;
1707     if (Inst->getOpcode() != Instruction::Add)
1708       continue;
1709 
1710     ConstantInt *Inc = dyn_cast<ConstantInt>(Inst->getOperand(1));
1711     if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
1712       continue;
1713 
1714     PHINode *Phi = getRecurrenceVar(Inst->getOperand(0), Inst, LoopEntry);
1715     if (!Phi)
1716       continue;
1717 
1718     CntInst = Inst;
1719     CntPhi = Phi;
1720     break;
1721   }
1722   if (!CntInst)
1723     return false;
1724 
1725   return true;
1726 }
1727 
1728 /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
1729 /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
1730 /// trip count returns true; otherwise, returns false.
1731 bool LoopIdiomRecognize::recognizeAndInsertFFS() {
1732   // Give up if the loop has multiple blocks or multiple backedges.
1733   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1734     return false;
1735 
1736   Intrinsic::ID IntrinID;
1737   Value *InitX;
1738   Instruction *DefX = nullptr;
1739   PHINode *CntPhi = nullptr;
1740   Instruction *CntInst = nullptr;
1741   // Help decide if transformation is profitable. For ShiftUntilZero idiom,
1742   // this is always 6.
1743   size_t IdiomCanonicalSize = 6;
1744 
1745   if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX,
1746                                  CntInst, CntPhi, DefX))
1747     return false;
1748 
1749   bool IsCntPhiUsedOutsideLoop = false;
1750   for (User *U : CntPhi->users())
1751     if (!CurLoop->contains(cast<Instruction>(U))) {
1752       IsCntPhiUsedOutsideLoop = true;
1753       break;
1754     }
1755   bool IsCntInstUsedOutsideLoop = false;
1756   for (User *U : CntInst->users())
1757     if (!CurLoop->contains(cast<Instruction>(U))) {
1758       IsCntInstUsedOutsideLoop = true;
1759       break;
1760     }
1761   // If both CntInst and CntPhi are used outside the loop the profitability
1762   // is questionable.
1763   if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1764     return false;
1765 
1766   // For some CPUs result of CTLZ(X) intrinsic is undefined
1767   // when X is 0. If we can not guarantee X != 0, we need to check this
1768   // when expand.
1769   bool ZeroCheck = false;
1770   // It is safe to assume Preheader exist as it was checked in
1771   // parent function RunOnLoop.
1772   BasicBlock *PH = CurLoop->getLoopPreheader();
1773 
1774   // If we are using the count instruction outside the loop, make sure we
1775   // have a zero check as a precondition. Without the check the loop would run
1776   // one iteration for before any check of the input value. This means 0 and 1
1777   // would have identical behavior in the original loop and thus
1778   if (!IsCntPhiUsedOutsideLoop) {
1779     auto *PreCondBB = PH->getSinglePredecessor();
1780     if (!PreCondBB)
1781       return false;
1782     auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1783     if (!PreCondBI)
1784       return false;
1785     if (matchCondition(PreCondBI, PH) != InitX)
1786       return false;
1787     ZeroCheck = true;
1788   }
1789 
1790   // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
1791   // profitable if we delete the loop.
1792 
1793   // the loop has only 6 instructions:
1794   //  %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1795   //  %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1796   //  %shr = ashr %n.addr.0, 1
1797   //  %tobool = icmp eq %shr, 0
1798   //  %inc = add nsw %i.0, 1
1799   //  br i1 %tobool
1800 
1801   const Value *Args[] = {InitX,
1802                          ConstantInt::getBool(InitX->getContext(), ZeroCheck)};
1803 
1804   // @llvm.dbg doesn't count as they have no semantic effect.
1805   auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
1806   uint32_t HeaderSize =
1807       std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
1808 
1809   IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);
1810   InstructionCost Cost =
1811     TTI->getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency);
1812   if (HeaderSize != IdiomCanonicalSize &&
1813       Cost > TargetTransformInfo::TCC_Basic)
1814     return false;
1815 
1816   transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
1817                            DefX->getDebugLoc(), ZeroCheck,
1818                            IsCntPhiUsedOutsideLoop);
1819   return true;
1820 }
1821 
1822 /// Recognizes a population count idiom in a non-countable loop.
1823 ///
1824 /// If detected, transforms the relevant code to issue the popcount intrinsic
1825 /// function call, and returns true; otherwise, returns false.
1826 bool LoopIdiomRecognize::recognizePopcount() {
1827   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1828     return false;
1829 
1830   // Counting population are usually conducted by few arithmetic instructions.
1831   // Such instructions can be easily "absorbed" by vacant slots in a
1832   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1833   // in a compact loop.
1834 
1835   // Give up if the loop has multiple blocks or multiple backedges.
1836   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1837     return false;
1838 
1839   BasicBlock *LoopBody = *(CurLoop->block_begin());
1840   if (LoopBody->size() >= 20) {
1841     // The loop is too big, bail out.
1842     return false;
1843   }
1844 
1845   // It should have a preheader containing nothing but an unconditional branch.
1846   BasicBlock *PH = CurLoop->getLoopPreheader();
1847   if (!PH || &PH->front() != PH->getTerminator())
1848     return false;
1849   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1850   if (!EntryBI || EntryBI->isConditional())
1851     return false;
1852 
1853   // It should have a precondition block where the generated popcount intrinsic
1854   // function can be inserted.
1855   auto *PreCondBB = PH->getSinglePredecessor();
1856   if (!PreCondBB)
1857     return false;
1858   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1859   if (!PreCondBI || PreCondBI->isUnconditional())
1860     return false;
1861 
1862   Instruction *CntInst;
1863   PHINode *CntPhi;
1864   Value *Val;
1865   if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1866     return false;
1867 
1868   transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1869   return true;
1870 }
1871 
1872 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1873                                        const DebugLoc &DL) {
1874   Value *Ops[] = {Val};
1875   Type *Tys[] = {Val->getType()};
1876 
1877   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1878   Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1879   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1880   CI->setDebugLoc(DL);
1881 
1882   return CI;
1883 }
1884 
1885 static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1886                                     const DebugLoc &DL, bool ZeroCheck,
1887                                     Intrinsic::ID IID) {
1888   Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};
1889   Type *Tys[] = {Val->getType()};
1890 
1891   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1892   Function *Func = Intrinsic::getDeclaration(M, IID, Tys);
1893   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1894   CI->setDebugLoc(DL);
1895 
1896   return CI;
1897 }
1898 
1899 /// Transform the following loop (Using CTLZ, CTTZ is similar):
1900 /// loop:
1901 ///   CntPhi = PHI [Cnt0, CntInst]
1902 ///   PhiX = PHI [InitX, DefX]
1903 ///   CntInst = CntPhi + 1
1904 ///   DefX = PhiX >> 1
1905 ///   LOOP_BODY
1906 ///   Br: loop if (DefX != 0)
1907 /// Use(CntPhi) or Use(CntInst)
1908 ///
1909 /// Into:
1910 /// If CntPhi used outside the loop:
1911 ///   CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
1912 ///   Count = CountPrev + 1
1913 /// else
1914 ///   Count = BitWidth(InitX) - CTLZ(InitX)
1915 /// loop:
1916 ///   CntPhi = PHI [Cnt0, CntInst]
1917 ///   PhiX = PHI [InitX, DefX]
1918 ///   PhiCount = PHI [Count, Dec]
1919 ///   CntInst = CntPhi + 1
1920 ///   DefX = PhiX >> 1
1921 ///   Dec = PhiCount - 1
1922 ///   LOOP_BODY
1923 ///   Br: loop if (Dec != 0)
1924 /// Use(CountPrev + Cnt0) // Use(CntPhi)
1925 /// or
1926 /// Use(Count + Cnt0) // Use(CntInst)
1927 ///
1928 /// If LOOP_BODY is empty the loop will be deleted.
1929 /// If CntInst and DefX are not used in LOOP_BODY they will be removed.
1930 void LoopIdiomRecognize::transformLoopToCountable(
1931     Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
1932     PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
1933     bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
1934   BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
1935 
1936   // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
1937   IRBuilder<> Builder(PreheaderBr);
1938   Builder.SetCurrentDebugLocation(DL);
1939 
1940   // If there are no uses of CntPhi crate:
1941   //   Count = BitWidth - CTLZ(InitX);
1942   //   NewCount = Count;
1943   // If there are uses of CntPhi create:
1944   //   NewCount = BitWidth - CTLZ(InitX >> 1);
1945   //   Count = NewCount + 1;
1946   Value *InitXNext;
1947   if (IsCntPhiUsedOutsideLoop) {
1948     if (DefX->getOpcode() == Instruction::AShr)
1949       InitXNext = Builder.CreateAShr(InitX, 1);
1950     else if (DefX->getOpcode() == Instruction::LShr)
1951       InitXNext = Builder.CreateLShr(InitX, 1);
1952     else if (DefX->getOpcode() == Instruction::Shl) // cttz
1953       InitXNext = Builder.CreateShl(InitX, 1);
1954     else
1955       llvm_unreachable("Unexpected opcode!");
1956   } else
1957     InitXNext = InitX;
1958   Value *Count =
1959       createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
1960   Type *CountTy = Count->getType();
1961   Count = Builder.CreateSub(
1962       ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);
1963   Value *NewCount = Count;
1964   if (IsCntPhiUsedOutsideLoop)
1965     Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
1966 
1967   NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());
1968 
1969   Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
1970   if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {
1971     // If the counter was being incremented in the loop, add NewCount to the
1972     // counter's initial value, but only if the initial value is not zero.
1973     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
1974     if (!InitConst || !InitConst->isZero())
1975       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1976   } else {
1977     // If the count was being decremented in the loop, subtract NewCount from
1978     // the counter's initial value.
1979     NewCount = Builder.CreateSub(CntInitVal, NewCount);
1980   }
1981 
1982   // Step 2: Insert new IV and loop condition:
1983   // loop:
1984   //   ...
1985   //   PhiCount = PHI [Count, Dec]
1986   //   ...
1987   //   Dec = PhiCount - 1
1988   //   ...
1989   //   Br: loop if (Dec != 0)
1990   BasicBlock *Body = *(CurLoop->block_begin());
1991   auto *LbBr = cast<BranchInst>(Body->getTerminator());
1992   ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1993 
1994   PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi", &Body->front());
1995 
1996   Builder.SetInsertPoint(LbCond);
1997   Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
1998       TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));
1999 
2000   TcPhi->addIncoming(Count, Preheader);
2001   TcPhi->addIncoming(TcDec, Body);
2002 
2003   CmpInst::Predicate Pred =
2004       (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
2005   LbCond->setPredicate(Pred);
2006   LbCond->setOperand(0, TcDec);
2007   LbCond->setOperand(1, ConstantInt::get(CountTy, 0));
2008 
2009   // Step 3: All the references to the original counter outside
2010   //  the loop are replaced with the NewCount
2011   if (IsCntPhiUsedOutsideLoop)
2012     CntPhi->replaceUsesOutsideBlock(NewCount, Body);
2013   else
2014     CntInst->replaceUsesOutsideBlock(NewCount, Body);
2015 
2016   // step 4: Forget the "non-computable" trip-count SCEV associated with the
2017   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2018   SE->forgetLoop(CurLoop);
2019 }
2020 
2021 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
2022                                                  Instruction *CntInst,
2023                                                  PHINode *CntPhi, Value *Var) {
2024   BasicBlock *PreHead = CurLoop->getLoopPreheader();
2025   auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
2026   const DebugLoc &DL = CntInst->getDebugLoc();
2027 
2028   // Assuming before transformation, the loop is following:
2029   //  if (x) // the precondition
2030   //     do { cnt++; x &= x - 1; } while(x);
2031 
2032   // Step 1: Insert the ctpop instruction at the end of the precondition block
2033   IRBuilder<> Builder(PreCondBr);
2034   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
2035   {
2036     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
2037     NewCount = PopCntZext =
2038         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
2039 
2040     if (NewCount != PopCnt)
2041       (cast<Instruction>(NewCount))->setDebugLoc(DL);
2042 
2043     // TripCnt is exactly the number of iterations the loop has
2044     TripCnt = NewCount;
2045 
2046     // If the population counter's initial value is not zero, insert Add Inst.
2047     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
2048     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2049     if (!InitConst || !InitConst->isZero()) {
2050       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2051       (cast<Instruction>(NewCount))->setDebugLoc(DL);
2052     }
2053   }
2054 
2055   // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
2056   //   "if (NewCount == 0) loop-exit". Without this change, the intrinsic
2057   //   function would be partial dead code, and downstream passes will drag
2058   //   it back from the precondition block to the preheader.
2059   {
2060     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
2061 
2062     Value *Opnd0 = PopCntZext;
2063     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
2064     if (PreCond->getOperand(0) != Var)
2065       std::swap(Opnd0, Opnd1);
2066 
2067     ICmpInst *NewPreCond = cast<ICmpInst>(
2068         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
2069     PreCondBr->setCondition(NewPreCond);
2070 
2071     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
2072   }
2073 
2074   // Step 3: Note that the population count is exactly the trip count of the
2075   // loop in question, which enable us to convert the loop from noncountable
2076   // loop into a countable one. The benefit is twofold:
2077   //
2078   //  - If the loop only counts population, the entire loop becomes dead after
2079   //    the transformation. It is a lot easier to prove a countable loop dead
2080   //    than to prove a noncountable one. (In some C dialects, an infinite loop
2081   //    isn't dead even if it computes nothing useful. In general, DCE needs
2082   //    to prove a noncountable loop finite before safely delete it.)
2083   //
2084   //  - If the loop also performs something else, it remains alive.
2085   //    Since it is transformed to countable form, it can be aggressively
2086   //    optimized by some optimizations which are in general not applicable
2087   //    to a noncountable loop.
2088   //
2089   // After this step, this loop (conceptually) would look like following:
2090   //   newcnt = __builtin_ctpop(x);
2091   //   t = newcnt;
2092   //   if (x)
2093   //     do { cnt++; x &= x-1; t--) } while (t > 0);
2094   BasicBlock *Body = *(CurLoop->block_begin());
2095   {
2096     auto *LbBr = cast<BranchInst>(Body->getTerminator());
2097     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2098     Type *Ty = TripCnt->getType();
2099 
2100     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
2101 
2102     Builder.SetInsertPoint(LbCond);
2103     Instruction *TcDec = cast<Instruction>(
2104         Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
2105                           "tcdec", false, true));
2106 
2107     TcPhi->addIncoming(TripCnt, PreHead);
2108     TcPhi->addIncoming(TcDec, Body);
2109 
2110     CmpInst::Predicate Pred =
2111         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
2112     LbCond->setPredicate(Pred);
2113     LbCond->setOperand(0, TcDec);
2114     LbCond->setOperand(1, ConstantInt::get(Ty, 0));
2115   }
2116 
2117   // Step 4: All the references to the original population counter outside
2118   //  the loop are replaced with the NewCount -- the value returned from
2119   //  __builtin_ctpop().
2120   CntInst->replaceUsesOutsideBlock(NewCount, Body);
2121 
2122   // step 5: Forget the "non-computable" trip-count SCEV associated with the
2123   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2124   SE->forgetLoop(CurLoop);
2125 }
2126 
2127 /// Match loop-invariant value.
2128 template <typename SubPattern_t> struct match_LoopInvariant {
2129   SubPattern_t SubPattern;
2130   const Loop *L;
2131 
2132   match_LoopInvariant(const SubPattern_t &SP, const Loop *L)
2133       : SubPattern(SP), L(L) {}
2134 
2135   template <typename ITy> bool match(ITy *V) {
2136     return L->isLoopInvariant(V) && SubPattern.match(V);
2137   }
2138 };
2139 
2140 /// Matches if the value is loop-invariant.
2141 template <typename Ty>
2142 inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {
2143   return match_LoopInvariant<Ty>(M, L);
2144 }
2145 
2146 /// Return true if the idiom is detected in the loop.
2147 ///
2148 /// The core idiom we are trying to detect is:
2149 /// \code
2150 ///   entry:
2151 ///     <...>
2152 ///     %bitmask = shl i32 1, %bitpos
2153 ///     br label %loop
2154 ///
2155 ///   loop:
2156 ///     %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2157 ///     %x.curr.bitmasked = and i32 %x.curr, %bitmask
2158 ///     %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2159 ///     %x.next = shl i32 %x.curr, 1
2160 ///     <...>
2161 ///     br i1 %x.curr.isbitunset, label %loop, label %end
2162 ///
2163 ///   end:
2164 ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2165 ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2166 ///     <...>
2167 /// \endcode
2168 static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,
2169                                          Value *&BitMask, Value *&BitPos,
2170                                          Value *&CurrX, Instruction *&NextX) {
2171   LLVM_DEBUG(dbgs() << DEBUG_TYPE
2172              " Performing shift-until-bittest idiom detection.\n");
2173 
2174   // Give up if the loop has multiple blocks or multiple backedges.
2175   if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2176     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
2177     return false;
2178   }
2179 
2180   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2181   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2182   assert(LoopPreheaderBB && "There is always a loop preheader.");
2183 
2184   using namespace PatternMatch;
2185 
2186   // Step 1: Check if the loop backedge is in desirable form.
2187 
2188   ICmpInst::Predicate Pred;
2189   Value *CmpLHS, *CmpRHS;
2190   BasicBlock *TrueBB, *FalseBB;
2191   if (!match(LoopHeaderBB->getTerminator(),
2192              m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
2193                   m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {
2194     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
2195     return false;
2196   }
2197 
2198   // Step 2: Check if the backedge's condition is in desirable form.
2199 
2200   auto MatchVariableBitMask = [&]() {
2201     return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2202            match(CmpLHS,
2203                  m_c_And(m_Value(CurrX),
2204                          m_CombineAnd(
2205                              m_Value(BitMask),
2206                              m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),
2207                                              CurLoop))));
2208   };
2209   auto MatchConstantBitMask = [&]() {
2210     return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2211            match(CmpLHS, m_And(m_Value(CurrX),
2212                                m_CombineAnd(m_Value(BitMask), m_Power2()))) &&
2213            (BitPos = ConstantExpr::getExactLogBase2(cast<Constant>(BitMask)));
2214   };
2215   auto MatchDecomposableConstantBitMask = [&]() {
2216     APInt Mask;
2217     return llvm::decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, CurrX, Mask) &&
2218            ICmpInst::isEquality(Pred) && Mask.isPowerOf2() &&
2219            (BitMask = ConstantInt::get(CurrX->getType(), Mask)) &&
2220            (BitPos = ConstantInt::get(CurrX->getType(), Mask.logBase2()));
2221   };
2222 
2223   if (!MatchVariableBitMask() && !MatchConstantBitMask() &&
2224       !MatchDecomposableConstantBitMask()) {
2225     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n");
2226     return false;
2227   }
2228 
2229   // Step 3: Check if the recurrence is in desirable form.
2230   auto *CurrXPN = dyn_cast<PHINode>(CurrX);
2231   if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
2232     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
2233     return false;
2234   }
2235 
2236   BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
2237   NextX =
2238       dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
2239 
2240   assert(CurLoop->isLoopInvariant(BaseX) &&
2241          "Expected BaseX to be avaliable in the preheader!");
2242 
2243   if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) {
2244     // FIXME: support right-shift?
2245     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
2246     return false;
2247   }
2248 
2249   // Step 4: Check if the backedge's destinations are in desirable form.
2250 
2251   assert(ICmpInst::isEquality(Pred) &&
2252          "Should only get equality predicates here.");
2253 
2254   // cmp-br is commutative, so canonicalize to a single variant.
2255   if (Pred != ICmpInst::Predicate::ICMP_EQ) {
2256     Pred = ICmpInst::getInversePredicate(Pred);
2257     std::swap(TrueBB, FalseBB);
2258   }
2259 
2260   // We expect to exit loop when comparison yields false,
2261   // so when it yields true we should branch back to loop header.
2262   if (TrueBB != LoopHeaderBB) {
2263     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
2264     return false;
2265   }
2266 
2267   // Okay, idiom checks out.
2268   return true;
2269 }
2270 
2271 /// Look for the following loop:
2272 /// \code
2273 ///   entry:
2274 ///     <...>
2275 ///     %bitmask = shl i32 1, %bitpos
2276 ///     br label %loop
2277 ///
2278 ///   loop:
2279 ///     %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2280 ///     %x.curr.bitmasked = and i32 %x.curr, %bitmask
2281 ///     %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2282 ///     %x.next = shl i32 %x.curr, 1
2283 ///     <...>
2284 ///     br i1 %x.curr.isbitunset, label %loop, label %end
2285 ///
2286 ///   end:
2287 ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2288 ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2289 ///     <...>
2290 /// \endcode
2291 ///
2292 /// And transform it into:
2293 /// \code
2294 ///   entry:
2295 ///     %bitmask = shl i32 1, %bitpos
2296 ///     %lowbitmask = add i32 %bitmask, -1
2297 ///     %mask = or i32 %lowbitmask, %bitmask
2298 ///     %x.masked = and i32 %x, %mask
2299 ///     %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,
2300 ///                                                         i1 true)
2301 ///     %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros
2302 ///     %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1
2303 ///     %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos
2304 ///     %tripcount = add i32 %backedgetakencount, 1
2305 ///     %x.curr = shl i32 %x, %backedgetakencount
2306 ///     %x.next = shl i32 %x, %tripcount
2307 ///     br label %loop
2308 ///
2309 ///   loop:
2310 ///     %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]
2311 ///     %loop.iv.next = add nuw i32 %loop.iv, 1
2312 ///     %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount
2313 ///     <...>
2314 ///     br i1 %loop.ivcheck, label %end, label %loop
2315 ///
2316 ///   end:
2317 ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2318 ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2319 ///     <...>
2320 /// \endcode
2321 bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
2322   bool MadeChange = false;
2323 
2324   Value *X, *BitMask, *BitPos, *XCurr;
2325   Instruction *XNext;
2326   if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,
2327                                     XNext)) {
2328     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2329                " shift-until-bittest idiom detection failed.\n");
2330     return MadeChange;
2331   }
2332   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n");
2333 
2334   // Ok, it is the idiom we were looking for, we *could* transform this loop,
2335   // but is it profitable to transform?
2336 
2337   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2338   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2339   assert(LoopPreheaderBB && "There is always a loop preheader.");
2340 
2341   BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2342   assert(SuccessorBB && "There is only a single successor.");
2343 
2344   IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2345   Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());
2346 
2347   Intrinsic::ID IntrID = Intrinsic::ctlz;
2348   Type *Ty = X->getType();
2349   unsigned Bitwidth = Ty->getScalarSizeInBits();
2350 
2351   TargetTransformInfo::TargetCostKind CostKind =
2352       TargetTransformInfo::TCK_SizeAndLatency;
2353 
2354   // The rewrite is considered to be unprofitable iff and only iff the
2355   // intrinsic/shift we'll use are not cheap. Note that we are okay with *just*
2356   // making the loop countable, even if nothing else changes.
2357   IntrinsicCostAttributes Attrs(
2358       IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getTrue()});
2359   InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2360   if (Cost > TargetTransformInfo::TCC_Basic) {
2361     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2362                " Intrinsic is too costly, not beneficial\n");
2363     return MadeChange;
2364   }
2365   if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) >
2366       TargetTransformInfo::TCC_Basic) {
2367     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n");
2368     return MadeChange;
2369   }
2370 
2371   // Ok, transform appears worthwhile.
2372   MadeChange = true;
2373 
2374   // Step 1: Compute the loop trip count.
2375 
2376   Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),
2377                                         BitPos->getName() + ".lowbitmask");
2378   Value *Mask =
2379       Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");
2380   Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");
2381   CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
2382       IntrID, Ty, {XMasked, /*is_zero_undef=*/Builder.getTrue()},
2383       /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");
2384   Value *XMaskedNumActiveBits = Builder.CreateSub(
2385       ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,
2386       XMasked->getName() + ".numactivebits", /*HasNUW=*/true,
2387       /*HasNSW=*/Bitwidth != 2);
2388   Value *XMaskedLeadingOnePos =
2389       Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),
2390                         XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,
2391                         /*HasNSW=*/Bitwidth > 2);
2392 
2393   Value *LoopBackedgeTakenCount = Builder.CreateSub(
2394       BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount",
2395       /*HasNUW=*/true, /*HasNSW=*/true);
2396   // We know loop's backedge-taken count, but what's loop's trip count?
2397   // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2398   Value *LoopTripCount =
2399       Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2400                         CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2401                         /*HasNSW=*/Bitwidth != 2);
2402 
2403   // Step 2: Compute the recurrence's final value without a loop.
2404 
2405   // NewX is always safe to compute, because `LoopBackedgeTakenCount`
2406   // will always be smaller than `bitwidth(X)`, i.e. we never get poison.
2407   Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount);
2408   NewX->takeName(XCurr);
2409   if (auto *I = dyn_cast<Instruction>(NewX))
2410     I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2411 
2412   Value *NewXNext;
2413   // Rewriting XNext is more complicated, however, because `X << LoopTripCount`
2414   // will be poison iff `LoopTripCount == bitwidth(X)` (which will happen
2415   // iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know
2416   // that isn't the case, we'll need to emit an alternative, safe IR.
2417   if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||
2418       PatternMatch::match(
2419           BitPos, PatternMatch::m_SpecificInt_ICMP(
2420                       ICmpInst::ICMP_NE, APInt(Ty->getScalarSizeInBits(),
2421                                                Ty->getScalarSizeInBits() - 1))))
2422     NewXNext = Builder.CreateShl(X, LoopTripCount);
2423   else {
2424     // Otherwise, just additionally shift by one. It's the smallest solution,
2425     // alternatively, we could check that NewX is INT_MIN (or BitPos is )
2426     // and select 0 instead.
2427     NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
2428   }
2429 
2430   NewXNext->takeName(XNext);
2431   if (auto *I = dyn_cast<Instruction>(NewXNext))
2432     I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2433 
2434   // Step 3: Adjust the successor basic block to recieve the computed
2435   //         recurrence's final value instead of the recurrence itself.
2436 
2437   XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);
2438   XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);
2439 
2440   // Step 4: Rewrite the loop into a countable form, with canonical IV.
2441 
2442   // The new canonical induction variable.
2443   Builder.SetInsertPoint(&LoopHeaderBB->front());
2444   auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2445 
2446   // The induction itself.
2447   // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2448   Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2449   auto *IVNext =
2450       Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
2451                         /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2452 
2453   // The loop trip count check.
2454   auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
2455                                        CurLoop->getName() + ".ivcheck");
2456   Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
2457   LoopHeaderBB->getTerminator()->eraseFromParent();
2458 
2459   // Populate the IV PHI.
2460   IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2461   IV->addIncoming(IVNext, LoopHeaderBB);
2462 
2463   // Step 5: Forget the "non-computable" trip-count SCEV associated with the
2464   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2465 
2466   SE->forgetLoop(CurLoop);
2467 
2468   // Other passes will take care of actually deleting the loop if possible.
2469 
2470   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n");
2471 
2472   ++NumShiftUntilBitTest;
2473   return MadeChange;
2474 }
2475 
2476 /// Return true if the idiom is detected in the loop.
2477 ///
2478 /// The core idiom we are trying to detect is:
2479 /// \code
2480 ///   entry:
2481 ///     <...>
2482 ///     %start = <...>
2483 ///     %extraoffset = <...>
2484 ///     <...>
2485 ///     br label %for.cond
2486 ///
2487 ///   loop:
2488 ///     %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2489 ///     %nbits = add nsw i8 %iv, %extraoffset
2490 ///     %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2491 ///     %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2492 ///     %iv.next = add i8 %iv, 1
2493 ///     <...>
2494 ///     br i1 %val.shifted.iszero, label %end, label %loop
2495 ///
2496 ///   end:
2497 ///     %iv.res = phi i8 [ %iv, %loop ] <...>
2498 ///     %nbits.res = phi i8 [ %nbits, %loop ] <...>
2499 ///     %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2500 ///     %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2501 ///     %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2502 ///     <...>
2503 /// \endcode
2504 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, ScalarEvolution *SE,
2505                                       Instruction *&ValShiftedIsZero,
2506                                       Intrinsic::ID &IntrinID, Instruction *&IV,
2507                                       Value *&Start, Value *&Val,
2508                                       const SCEV *&ExtraOffsetExpr,
2509                                       bool &InvertedCond) {
2510   LLVM_DEBUG(dbgs() << DEBUG_TYPE
2511              " Performing shift-until-zero idiom detection.\n");
2512 
2513   // Give up if the loop has multiple blocks or multiple backedges.
2514   if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2515     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
2516     return false;
2517   }
2518 
2519   Instruction *ValShifted, *NBits, *IVNext;
2520   Value *ExtraOffset;
2521 
2522   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2523   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2524   assert(LoopPreheaderBB && "There is always a loop preheader.");
2525 
2526   using namespace PatternMatch;
2527 
2528   // Step 1: Check if the loop backedge, condition is in desirable form.
2529 
2530   ICmpInst::Predicate Pred;
2531   BasicBlock *TrueBB, *FalseBB;
2532   if (!match(LoopHeaderBB->getTerminator(),
2533              m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),
2534                   m_BasicBlock(FalseBB))) ||
2535       !match(ValShiftedIsZero,
2536              m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||
2537       !ICmpInst::isEquality(Pred)) {
2538     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
2539     return false;
2540   }
2541 
2542   // Step 2: Check if the comparison's operand is in desirable form.
2543   // FIXME: Val could be a one-input PHI node, which we should look past.
2544   if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),
2545                                  m_Instruction(NBits)))) {
2546     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n");
2547     return false;
2548   }
2549   IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz
2550                                                          : Intrinsic::ctlz;
2551 
2552   // Step 3: Check if the shift amount is in desirable form.
2553 
2554   if (match(NBits, m_c_Add(m_Instruction(IV),
2555                            m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2556       (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))
2557     ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));
2558   else if (match(NBits,
2559                  m_Sub(m_Instruction(IV),
2560                        m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2561            NBits->hasNoSignedWrap())
2562     ExtraOffsetExpr = SE->getSCEV(ExtraOffset);
2563   else {
2564     IV = NBits;
2565     ExtraOffsetExpr = SE->getZero(NBits->getType());
2566   }
2567 
2568   // Step 4: Check if the recurrence is in desirable form.
2569   auto *IVPN = dyn_cast<PHINode>(IV);
2570   if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
2571     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
2572     return false;
2573   }
2574 
2575   Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
2576   IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
2577 
2578   if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {
2579     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
2580     return false;
2581   }
2582 
2583   // Step 4: Check if the backedge's destinations are in desirable form.
2584 
2585   assert(ICmpInst::isEquality(Pred) &&
2586          "Should only get equality predicates here.");
2587 
2588   // cmp-br is commutative, so canonicalize to a single variant.
2589   InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;
2590   if (InvertedCond) {
2591     Pred = ICmpInst::getInversePredicate(Pred);
2592     std::swap(TrueBB, FalseBB);
2593   }
2594 
2595   // We expect to exit loop when comparison yields true,
2596   // so when it yields false we should branch back to loop header.
2597   if (FalseBB != LoopHeaderBB) {
2598     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
2599     return false;
2600   }
2601 
2602   // The new, countable, loop will certainly only run a known number of
2603   // iterations, It won't be infinite. But the old loop might be infinite
2604   // under certain conditions. For logical shifts, the value will become zero
2605   // after at most bitwidth(%Val) loop iterations. However, for arithmetic
2606   // right-shift, iff the sign bit was set, the value will never become zero,
2607   // and the loop may never finish.
2608   if (ValShifted->getOpcode() == Instruction::AShr &&
2609       !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {
2610     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n");
2611     return false;
2612   }
2613 
2614   // Okay, idiom checks out.
2615   return true;
2616 }
2617 
2618 /// Look for the following loop:
2619 /// \code
2620 ///   entry:
2621 ///     <...>
2622 ///     %start = <...>
2623 ///     %extraoffset = <...>
2624 ///     <...>
2625 ///     br label %for.cond
2626 ///
2627 ///   loop:
2628 ///     %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2629 ///     %nbits = add nsw i8 %iv, %extraoffset
2630 ///     %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2631 ///     %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2632 ///     %iv.next = add i8 %iv, 1
2633 ///     <...>
2634 ///     br i1 %val.shifted.iszero, label %end, label %loop
2635 ///
2636 ///   end:
2637 ///     %iv.res = phi i8 [ %iv, %loop ] <...>
2638 ///     %nbits.res = phi i8 [ %nbits, %loop ] <...>
2639 ///     %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2640 ///     %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2641 ///     %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2642 ///     <...>
2643 /// \endcode
2644 ///
2645 /// And transform it into:
2646 /// \code
2647 ///   entry:
2648 ///     <...>
2649 ///     %start = <...>
2650 ///     %extraoffset = <...>
2651 ///     <...>
2652 ///     %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)
2653 ///     %val.numactivebits = sub i8 8, %val.numleadingzeros
2654 ///     %extraoffset.neg = sub i8 0, %extraoffset
2655 ///     %tmp = add i8 %val.numactivebits, %extraoffset.neg
2656 ///     %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)
2657 ///     %loop.tripcount = sub i8 %iv.final, %start
2658 ///     br label %loop
2659 ///
2660 ///   loop:
2661 ///     %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]
2662 ///     %loop.iv.next = add i8 %loop.iv, 1
2663 ///     %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount
2664 ///     %iv = add i8 %loop.iv, %start
2665 ///     <...>
2666 ///     br i1 %loop.ivcheck, label %end, label %loop
2667 ///
2668 ///   end:
2669 ///     %iv.res = phi i8 [ %iv.final, %loop ] <...>
2670 ///     <...>
2671 /// \endcode
2672 bool LoopIdiomRecognize::recognizeShiftUntilZero() {
2673   bool MadeChange = false;
2674 
2675   Instruction *ValShiftedIsZero;
2676   Intrinsic::ID IntrID;
2677   Instruction *IV;
2678   Value *Start, *Val;
2679   const SCEV *ExtraOffsetExpr;
2680   bool InvertedCond;
2681   if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,
2682                                  Start, Val, ExtraOffsetExpr, InvertedCond)) {
2683     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2684                " shift-until-zero idiom detection failed.\n");
2685     return MadeChange;
2686   }
2687   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n");
2688 
2689   // Ok, it is the idiom we were looking for, we *could* transform this loop,
2690   // but is it profitable to transform?
2691 
2692   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2693   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2694   assert(LoopPreheaderBB && "There is always a loop preheader.");
2695 
2696   BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2697   assert(SuccessorBB && "There is only a single successor.");
2698 
2699   IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2700   Builder.SetCurrentDebugLocation(IV->getDebugLoc());
2701 
2702   Type *Ty = Val->getType();
2703   unsigned Bitwidth = Ty->getScalarSizeInBits();
2704 
2705   TargetTransformInfo::TargetCostKind CostKind =
2706       TargetTransformInfo::TCK_SizeAndLatency;
2707 
2708   // The rewrite is considered to be unprofitable iff and only iff the
2709   // intrinsic we'll use are not cheap. Note that we are okay with *just*
2710   // making the loop countable, even if nothing else changes.
2711   IntrinsicCostAttributes Attrs(
2712       IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getFalse()});
2713   InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2714   if (Cost > TargetTransformInfo::TCC_Basic) {
2715     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2716                " Intrinsic is too costly, not beneficial\n");
2717     return MadeChange;
2718   }
2719 
2720   // Ok, transform appears worthwhile.
2721   MadeChange = true;
2722 
2723   bool OffsetIsZero = false;
2724   if (auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr))
2725     OffsetIsZero = ExtraOffsetExprC->isZero();
2726 
2727   // Step 1: Compute the loop's final IV value / trip count.
2728 
2729   CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic(
2730       IntrID, Ty, {Val, /*is_zero_undef=*/Builder.getFalse()},
2731       /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");
2732   Value *ValNumActiveBits = Builder.CreateSub(
2733       ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,
2734       Val->getName() + ".numactivebits", /*HasNUW=*/true,
2735       /*HasNSW=*/Bitwidth != 2);
2736 
2737   SCEVExpander Expander(*SE, *DL, "loop-idiom");
2738   Expander.setInsertPoint(&*Builder.GetInsertPoint());
2739   Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
2740 
2741   Value *ValNumActiveBitsOffset = Builder.CreateAdd(
2742       ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",
2743       /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);
2744   Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
2745                                            {ValNumActiveBitsOffset, Start},
2746                                            /*FMFSource=*/nullptr, "iv.final");
2747 
2748   auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
2749       IVFinal, Start, CurLoop->getName() + ".backedgetakencount",
2750       /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));
2751   // FIXME: or when the offset was `add nuw`
2752 
2753   // We know loop's backedge-taken count, but what's loop's trip count?
2754   Value *LoopTripCount =
2755       Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2756                         CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2757                         /*HasNSW=*/Bitwidth != 2);
2758 
2759   // Step 2: Adjust the successor basic block to recieve the original
2760   //         induction variable's final value instead of the orig. IV itself.
2761 
2762   IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
2763 
2764   // Step 3: Rewrite the loop into a countable form, with canonical IV.
2765 
2766   // The new canonical induction variable.
2767   Builder.SetInsertPoint(&LoopHeaderBB->front());
2768   auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2769 
2770   // The induction itself.
2771   Builder.SetInsertPoint(LoopHeaderBB->getFirstNonPHI());
2772   auto *CIVNext =
2773       Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",
2774                         /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2775 
2776   // The loop trip count check.
2777   auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
2778                                         CurLoop->getName() + ".ivcheck");
2779   auto *NewIVCheck = CIVCheck;
2780   if (InvertedCond) {
2781     NewIVCheck = Builder.CreateNot(CIVCheck);
2782     NewIVCheck->takeName(ValShiftedIsZero);
2783   }
2784 
2785   // The original IV, but rebased to be an offset to the CIV.
2786   auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,
2787                                      /*HasNSW=*/true); // FIXME: what about NUW?
2788   IVDePHId->takeName(IV);
2789 
2790   // The loop terminator.
2791   Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2792   Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
2793   LoopHeaderBB->getTerminator()->eraseFromParent();
2794 
2795   // Populate the IV PHI.
2796   CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2797   CIV->addIncoming(CIVNext, LoopHeaderBB);
2798 
2799   // Step 4: Forget the "non-computable" trip-count SCEV associated with the
2800   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2801 
2802   SE->forgetLoop(CurLoop);
2803 
2804   // Step 5: Try to cleanup the loop's body somewhat.
2805   IV->replaceAllUsesWith(IVDePHId);
2806   IV->eraseFromParent();
2807 
2808   ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);
2809   ValShiftedIsZero->eraseFromParent();
2810 
2811   // Other passes will take care of actually deleting the loop if possible.
2812 
2813   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n");
2814 
2815   ++NumShiftUntilZero;
2816   return MadeChange;
2817 }
2818