xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
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                                   const SCEV *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 (BasicBlock *ExitBlock : ExitBlocks)
629     if (!DT->dominates(BB, ExitBlock))
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 (StoreInst *I : Heads) {
754     if (Tails.count(I))
755       continue;
756 
757     // We found a store instr that starts a chain. Now follow the chain and try
758     // to transform it.
759     SmallPtrSet<Instruction *, 8> AdjacentStores;
760     StoreInst *HeadStore = I;
761     unsigned StoreSize = 0;
762 
763     // Collect the chain into a list.
764     while (Tails.count(I) || Heads.count(I)) {
765       if (TransformedStores.count(I))
766         break;
767       AdjacentStores.insert(I);
768 
769       StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());
770       // Move to the next value in the chain.
771       I = ConsecutiveChain[I];
772     }
773 
774     Value *StoredVal = HeadStore->getValueOperand();
775     Value *StorePtr = HeadStore->getPointerOperand();
776     const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
777     APInt Stride = getStoreStride(StoreEv);
778 
779     // Check to see if the stride matches the size of the stores.  If so, then
780     // we know that every byte is touched in the loop.
781     if (StoreSize != Stride && StoreSize != -Stride)
782       continue;
783 
784     bool IsNegStride = StoreSize == -Stride;
785 
786     Type *IntIdxTy = DL->getIndexType(StorePtr->getType());
787     const SCEV *StoreSizeSCEV = SE->getConstant(IntIdxTy, StoreSize);
788     if (processLoopStridedStore(StorePtr, StoreSizeSCEV,
789                                 MaybeAlign(HeadStore->getAlign()), StoredVal,
790                                 HeadStore, AdjacentStores, StoreEv, BECount,
791                                 IsNegStride)) {
792       TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());
793       Changed = true;
794     }
795   }
796 
797   return Changed;
798 }
799 
800 /// processLoopMemIntrinsic - Template function for calling different processor
801 /// functions based on mem instrinsic type.
802 template <typename MemInst>
803 bool LoopIdiomRecognize::processLoopMemIntrinsic(
804     BasicBlock *BB,
805     bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),
806     const SCEV *BECount) {
807   bool MadeChange = false;
808   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
809     Instruction *Inst = &*I++;
810     // Look for memory instructions, which may be optimized to a larger one.
811     if (MemInst *MI = dyn_cast<MemInst>(Inst)) {
812       WeakTrackingVH InstPtr(&*I);
813       if (!(this->*Processor)(MI, BECount))
814         continue;
815       MadeChange = true;
816 
817       // If processing the instruction invalidated our iterator, start over from
818       // the top of the block.
819       if (!InstPtr)
820         I = BB->begin();
821     }
822   }
823   return MadeChange;
824 }
825 
826 /// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy
827 bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,
828                                            const SCEV *BECount) {
829   // We can only handle non-volatile memcpys with a constant size.
830   if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))
831     return false;
832 
833   // If we're not allowed to hack on memcpy, we fail.
834   if ((!HasMemcpy && !isa<MemCpyInlineInst>(MCI)) || DisableLIRP::Memcpy)
835     return false;
836 
837   Value *Dest = MCI->getDest();
838   Value *Source = MCI->getSource();
839   if (!Dest || !Source)
840     return false;
841 
842   // See if the load and store pointer expressions are AddRec like {base,+,1} on
843   // the current loop, which indicates a strided load and store.  If we have
844   // something else, it's a random load or store we can't handle.
845   const SCEVAddRecExpr *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Dest));
846   if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
847     return false;
848   const SCEVAddRecExpr *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Source));
849   if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
850     return false;
851 
852   // Reject memcpys that are so large that they overflow an unsigned.
853   uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();
854   if ((SizeInBytes >> 32) != 0)
855     return false;
856 
857   // Check if the stride matches the size of the memcpy. If so, then we know
858   // that every byte is touched in the loop.
859   const SCEVConstant *ConstStoreStride =
860       dyn_cast<SCEVConstant>(StoreEv->getOperand(1));
861   const SCEVConstant *ConstLoadStride =
862       dyn_cast<SCEVConstant>(LoadEv->getOperand(1));
863   if (!ConstStoreStride || !ConstLoadStride)
864     return false;
865 
866   APInt StoreStrideValue = ConstStoreStride->getAPInt();
867   APInt LoadStrideValue = ConstLoadStride->getAPInt();
868   // Huge stride value - give up
869   if (StoreStrideValue.getBitWidth() > 64 || LoadStrideValue.getBitWidth() > 64)
870     return false;
871 
872   if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) {
873     ORE.emit([&]() {
874       return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI)
875              << ore::NV("Inst", "memcpy") << " in "
876              << ore::NV("Function", MCI->getFunction())
877              << " function will not be hoisted: "
878              << ore::NV("Reason", "memcpy size is not equal to stride");
879     });
880     return false;
881   }
882 
883   int64_t StoreStrideInt = StoreStrideValue.getSExtValue();
884   int64_t LoadStrideInt = LoadStrideValue.getSExtValue();
885   // Check if the load stride matches the store stride.
886   if (StoreStrideInt != LoadStrideInt)
887     return false;
888 
889   return processLoopStoreOfLoopLoad(
890       Dest, Source, SE->getConstant(Dest->getType(), SizeInBytes),
891       MCI->getDestAlign(), MCI->getSourceAlign(), MCI, MCI, StoreEv, LoadEv,
892       BECount);
893 }
894 
895 /// processLoopMemSet - See if this memset can be promoted to a large memset.
896 bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,
897                                            const SCEV *BECount) {
898   // We can only handle non-volatile memsets.
899   if (MSI->isVolatile())
900     return false;
901 
902   // If we're not allowed to hack on memset, we fail.
903   if (!HasMemset || DisableLIRP::Memset)
904     return false;
905 
906   Value *Pointer = MSI->getDest();
907 
908   // See if the pointer expression is an AddRec like {base,+,1} on the current
909   // loop, which indicates a strided store.  If we have something else, it's a
910   // random store we can't handle.
911   const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));
912   if (!Ev || Ev->getLoop() != CurLoop)
913     return false;
914   if (!Ev->isAffine()) {
915     LLVM_DEBUG(dbgs() << "  Pointer is not affine, abort\n");
916     return false;
917   }
918 
919   const SCEV *PointerStrideSCEV = Ev->getOperand(1);
920   const SCEV *MemsetSizeSCEV = SE->getSCEV(MSI->getLength());
921   if (!PointerStrideSCEV || !MemsetSizeSCEV)
922     return false;
923 
924   bool IsNegStride = false;
925   const bool IsConstantSize = isa<ConstantInt>(MSI->getLength());
926 
927   if (IsConstantSize) {
928     // Memset size is constant.
929     // Check if the pointer stride matches the memset size. If so, then
930     // we know that every byte is touched in the loop.
931     LLVM_DEBUG(dbgs() << "  memset size is constant\n");
932     uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
933     const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));
934     if (!ConstStride)
935       return false;
936 
937     APInt Stride = ConstStride->getAPInt();
938     if (SizeInBytes != Stride && SizeInBytes != -Stride)
939       return false;
940 
941     IsNegStride = SizeInBytes == -Stride;
942   } else {
943     // Memset size is non-constant.
944     // Check if the pointer stride matches the memset size.
945     // To be conservative, the pass would not promote pointers that aren't in
946     // address space zero. Also, the pass only handles memset length and stride
947     // that are invariant for the top level loop.
948     LLVM_DEBUG(dbgs() << "  memset size is non-constant\n");
949     if (Pointer->getType()->getPointerAddressSpace() != 0) {
950       LLVM_DEBUG(dbgs() << "  pointer is not in address space zero, "
951                         << "abort\n");
952       return false;
953     }
954     if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) {
955       LLVM_DEBUG(dbgs() << "  memset size is not a loop-invariant, "
956                         << "abort\n");
957       return false;
958     }
959 
960     // Compare positive direction PointerStrideSCEV with MemsetSizeSCEV
961     IsNegStride = PointerStrideSCEV->isNonConstantNegative();
962     const SCEV *PositiveStrideSCEV =
963         IsNegStride ? SE->getNegativeSCEV(PointerStrideSCEV)
964                     : PointerStrideSCEV;
965     LLVM_DEBUG(dbgs() << "  MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n"
966                       << "  PositiveStrideSCEV: " << *PositiveStrideSCEV
967                       << "\n");
968 
969     if (PositiveStrideSCEV != MemsetSizeSCEV) {
970       // If an expression is covered by the loop guard, compare again and
971       // proceed with optimization if equal.
972       const SCEV *FoldedPositiveStride =
973           SE->applyLoopGuards(PositiveStrideSCEV, CurLoop);
974       const SCEV *FoldedMemsetSize =
975           SE->applyLoopGuards(MemsetSizeSCEV, CurLoop);
976 
977       LLVM_DEBUG(dbgs() << "  Try to fold SCEV based on loop guard\n"
978                         << "    FoldedMemsetSize: " << *FoldedMemsetSize << "\n"
979                         << "    FoldedPositiveStride: " << *FoldedPositiveStride
980                         << "\n");
981 
982       if (FoldedPositiveStride != FoldedMemsetSize) {
983         LLVM_DEBUG(dbgs() << "  SCEV don't match, abort\n");
984         return false;
985       }
986     }
987   }
988 
989   // Verify that the memset value is loop invariant.  If not, we can't promote
990   // the memset.
991   Value *SplatValue = MSI->getValue();
992   if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
993     return false;
994 
995   SmallPtrSet<Instruction *, 1> MSIs;
996   MSIs.insert(MSI);
997   return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()),
998                                  MaybeAlign(MSI->getDestAlignment()),
999                                  SplatValue, MSI, MSIs, Ev, BECount,
1000                                  IsNegStride, /*IsLoopMemset=*/true);
1001 }
1002 
1003 /// mayLoopAccessLocation - Return true if the specified loop might access the
1004 /// specified pointer location, which is a loop-strided access.  The 'Access'
1005 /// argument specifies what the verboten forms of access are (read or write).
1006 static bool
1007 mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,
1008                       const SCEV *BECount, const SCEV *StoreSizeSCEV,
1009                       AliasAnalysis &AA,
1010                       SmallPtrSetImpl<Instruction *> &IgnoredInsts) {
1011   // Get the location that may be stored across the loop.  Since the access is
1012   // strided positively through memory, we say that the modified location starts
1013   // at the pointer and has infinite size.
1014   LocationSize AccessSize = LocationSize::afterPointer();
1015 
1016   // If the loop iterates a fixed number of times, we can refine the access size
1017   // to be exactly the size of the memset, which is (BECount+1)*StoreSize
1018   const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount);
1019   const SCEVConstant *ConstSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1020   if (BECst && ConstSize)
1021     AccessSize = LocationSize::precise((BECst->getValue()->getZExtValue() + 1) *
1022                                        ConstSize->getValue()->getZExtValue());
1023 
1024   // TODO: For this to be really effective, we have to dive into the pointer
1025   // operand in the store.  Store to &A[i] of 100 will always return may alias
1026   // with store of &A[100], we need to StoreLoc to be "A" with size of 100,
1027   // which will then no-alias a store to &A[100].
1028   MemoryLocation StoreLoc(Ptr, AccessSize);
1029 
1030   for (BasicBlock *B : L->blocks())
1031     for (Instruction &I : *B)
1032       if (!IgnoredInsts.contains(&I) &&
1033           isModOrRefSet(
1034               intersectModRef(AA.getModRefInfo(&I, StoreLoc), Access)))
1035         return true;
1036   return false;
1037 }
1038 
1039 // If we have a negative stride, Start refers to the end of the memory location
1040 // we're trying to memset.  Therefore, we need to recompute the base pointer,
1041 // which is just Start - BECount*Size.
1042 static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,
1043                                         Type *IntPtr, const SCEV *StoreSizeSCEV,
1044                                         ScalarEvolution *SE) {
1045   const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);
1046   if (!StoreSizeSCEV->isOne()) {
1047     // index = back edge count * store size
1048     Index = SE->getMulExpr(Index,
1049                            SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1050                            SCEV::FlagNUW);
1051   }
1052   // base pointer = start - index * store size
1053   return SE->getMinusSCEV(Start, Index);
1054 }
1055 
1056 /// Compute trip count from the backedge taken count.
1057 static const SCEV *getTripCount(const SCEV *BECount, Type *IntPtr,
1058                                 Loop *CurLoop, const DataLayout *DL,
1059                                 ScalarEvolution *SE) {
1060   const SCEV *TripCountS = nullptr;
1061   // The # stored bytes is (BECount+1).  Expand the trip count out to
1062   // pointer size if it isn't already.
1063   //
1064   // If we're going to need to zero extend the BE count, check if we can add
1065   // one to it prior to zero extending without overflow. Provided this is safe,
1066   // it allows better simplification of the +1.
1067   if (DL->getTypeSizeInBits(BECount->getType()) <
1068           DL->getTypeSizeInBits(IntPtr) &&
1069       SE->isLoopEntryGuardedByCond(
1070           CurLoop, ICmpInst::ICMP_NE, BECount,
1071           SE->getNegativeSCEV(SE->getOne(BECount->getType())))) {
1072     TripCountS = SE->getZeroExtendExpr(
1073         SE->getAddExpr(BECount, SE->getOne(BECount->getType()), SCEV::FlagNUW),
1074         IntPtr);
1075   } else {
1076     TripCountS = SE->getAddExpr(SE->getTruncateOrZeroExtend(BECount, IntPtr),
1077                                 SE->getOne(IntPtr), SCEV::FlagNUW);
1078   }
1079 
1080   return TripCountS;
1081 }
1082 
1083 /// Compute the number of bytes as a SCEV from the backedge taken count.
1084 ///
1085 /// This also maps the SCEV into the provided type and tries to handle the
1086 /// computation in a way that will fold cleanly.
1087 static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,
1088                                const SCEV *StoreSizeSCEV, Loop *CurLoop,
1089                                const DataLayout *DL, ScalarEvolution *SE) {
1090   const SCEV *TripCountSCEV = getTripCount(BECount, IntPtr, CurLoop, DL, SE);
1091 
1092   return SE->getMulExpr(TripCountSCEV,
1093                         SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),
1094                         SCEV::FlagNUW);
1095 }
1096 
1097 /// processLoopStridedStore - We see a strided store of some value.  If we can
1098 /// transform this into a memset or memset_pattern in the loop preheader, do so.
1099 bool LoopIdiomRecognize::processLoopStridedStore(
1100     Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment,
1101     Value *StoredVal, Instruction *TheStore,
1102     SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,
1103     const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) {
1104   Value *SplatValue = isBytewiseValue(StoredVal, *DL);
1105   Constant *PatternValue = nullptr;
1106 
1107   if (!SplatValue)
1108     PatternValue = getMemSetPatternValue(StoredVal, DL);
1109 
1110   assert((SplatValue || PatternValue) &&
1111          "Expected either splat value or pattern value.");
1112 
1113   // The trip count of the loop and the base pointer of the addrec SCEV is
1114   // guaranteed to be loop invariant, which means that it should dominate the
1115   // header.  This allows us to insert code for it in the preheader.
1116   unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
1117   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1118   IRBuilder<> Builder(Preheader->getTerminator());
1119   SCEVExpander Expander(*SE, *DL, "loop-idiom");
1120   SCEVExpanderCleaner ExpCleaner(Expander);
1121 
1122   Type *DestInt8PtrTy = Builder.getInt8PtrTy(DestAS);
1123   Type *IntIdxTy = DL->getIndexType(DestPtr->getType());
1124 
1125   bool Changed = false;
1126   const SCEV *Start = Ev->getStart();
1127   // Handle negative strided loops.
1128   if (IsNegStride)
1129     Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE);
1130 
1131   // TODO: ideally we should still be able to generate memset if SCEV expander
1132   // is taught to generate the dependencies at the latest point.
1133   if (!isSafeToExpand(Start, *SE))
1134     return Changed;
1135 
1136   // Okay, we have a strided store "p[i]" of a splattable value.  We can turn
1137   // this into a memset in the loop preheader now if we want.  However, this
1138   // would be unsafe to do if there is anything else in the loop that may read
1139   // or write to the aliased location.  Check for any overlap by generating the
1140   // base pointer and checking the region.
1141   Value *BasePtr =
1142       Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());
1143 
1144   // From here on out, conservatively report to the pass manager that we've
1145   // changed the IR, even if we later clean up these added instructions. There
1146   // may be structural differences e.g. in the order of use lists not accounted
1147   // for in just a textual dump of the IR. This is written as a variable, even
1148   // though statically all the places this dominates could be replaced with
1149   // 'true', with the hope that anyone trying to be clever / "more precise" with
1150   // the return value will read this comment, and leave them alone.
1151   Changed = true;
1152 
1153   if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1154                             StoreSizeSCEV, *AA, Stores))
1155     return Changed;
1156 
1157   if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))
1158     return Changed;
1159 
1160   // Okay, everything looks good, insert the memset.
1161 
1162   const SCEV *NumBytesS =
1163       getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1164 
1165   // TODO: ideally we should still be able to generate memset if SCEV expander
1166   // is taught to generate the dependencies at the latest point.
1167   if (!isSafeToExpand(NumBytesS, *SE))
1168     return Changed;
1169 
1170   Value *NumBytes =
1171       Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1172 
1173   CallInst *NewCall;
1174   if (SplatValue) {
1175     AAMDNodes AATags = TheStore->getAAMetadata();
1176     for (Instruction *Store : Stores)
1177       AATags = AATags.merge(Store->getAAMetadata());
1178     if (auto CI = dyn_cast<ConstantInt>(NumBytes))
1179       AATags = AATags.extendTo(CI->getZExtValue());
1180     else
1181       AATags = AATags.extendTo(-1);
1182 
1183     NewCall = Builder.CreateMemSet(
1184         BasePtr, SplatValue, NumBytes, MaybeAlign(StoreAlignment),
1185         /*isVolatile=*/false, AATags.TBAA, AATags.Scope, AATags.NoAlias);
1186   } else {
1187     // Everything is emitted in default address space
1188     Type *Int8PtrTy = DestInt8PtrTy;
1189 
1190     Module *M = TheStore->getModule();
1191     StringRef FuncName = "memset_pattern16";
1192     FunctionCallee MSP = M->getOrInsertFunction(FuncName, Builder.getVoidTy(),
1193                                                 Int8PtrTy, Int8PtrTy, IntIdxTy);
1194     inferLibFuncAttributes(M, FuncName, *TLI);
1195 
1196     // Otherwise we should form a memset_pattern16.  PatternValue is known to be
1197     // an constant array of 16-bytes.  Plop the value into a mergable global.
1198     GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,
1199                                             GlobalValue::PrivateLinkage,
1200                                             PatternValue, ".memset_pattern");
1201     GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.
1202     GV->setAlignment(Align(16));
1203     Value *PatternPtr = ConstantExpr::getBitCast(GV, Int8PtrTy);
1204     NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
1205   }
1206   NewCall->setDebugLoc(TheStore->getDebugLoc());
1207 
1208   if (MSSAU) {
1209     MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1210         NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1211     MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1212   }
1213 
1214   LLVM_DEBUG(dbgs() << "  Formed memset: " << *NewCall << "\n"
1215                     << "    from store to: " << *Ev << " at: " << *TheStore
1216                     << "\n");
1217 
1218   ORE.emit([&]() {
1219     OptimizationRemark R(DEBUG_TYPE, "ProcessLoopStridedStore",
1220                          NewCall->getDebugLoc(), Preheader);
1221     R << "Transformed loop-strided store in "
1222       << ore::NV("Function", TheStore->getFunction())
1223       << " function into a call to "
1224       << ore::NV("NewFunction", NewCall->getCalledFunction())
1225       << "() intrinsic";
1226     if (!Stores.empty())
1227       R << ore::setExtraArgs();
1228     for (auto *I : Stores) {
1229       R << ore::NV("FromBlock", I->getParent()->getName())
1230         << ore::NV("ToBlock", Preheader->getName());
1231     }
1232     return R;
1233   });
1234 
1235   // Okay, the memset has been formed.  Zap the original store and anything that
1236   // feeds into it.
1237   for (auto *I : Stores) {
1238     if (MSSAU)
1239       MSSAU->removeMemoryAccess(I, true);
1240     deleteDeadInstruction(I);
1241   }
1242   if (MSSAU && VerifyMemorySSA)
1243     MSSAU->getMemorySSA()->verifyMemorySSA();
1244   ++NumMemSet;
1245   ExpCleaner.markResultUsed();
1246   return true;
1247 }
1248 
1249 /// If the stored value is a strided load in the same loop with the same stride
1250 /// this may be transformable into a memcpy.  This kicks in for stuff like
1251 /// for (i) A[i] = B[i];
1252 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,
1253                                                     const SCEV *BECount) {
1254   assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");
1255 
1256   Value *StorePtr = SI->getPointerOperand();
1257   const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1258   unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());
1259 
1260   // The store must be feeding a non-volatile load.
1261   LoadInst *LI = cast<LoadInst>(SI->getValueOperand());
1262   assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");
1263 
1264   // See if the pointer expression is an AddRec like {base,+,1} on the current
1265   // loop, which indicates a strided load.  If we have something else, it's a
1266   // random load we can't handle.
1267   Value *LoadPtr = LI->getPointerOperand();
1268   const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));
1269 
1270   const SCEV *StoreSizeSCEV = SE->getConstant(StorePtr->getType(), StoreSize);
1271   return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,
1272                                     SI->getAlign(), LI->getAlign(), SI, LI,
1273                                     StoreEv, LoadEv, BECount);
1274 }
1275 
1276 class MemmoveVerifier {
1277 public:
1278   explicit MemmoveVerifier(const Value &LoadBasePtr, const Value &StoreBasePtr,
1279                            const DataLayout &DL)
1280       : DL(DL), LoadOff(0), StoreOff(0),
1281         BP1(llvm::GetPointerBaseWithConstantOffset(
1282             LoadBasePtr.stripPointerCasts(), LoadOff, DL)),
1283         BP2(llvm::GetPointerBaseWithConstantOffset(
1284             StoreBasePtr.stripPointerCasts(), StoreOff, DL)),
1285         IsSameObject(BP1 == BP2) {}
1286 
1287   bool loadAndStoreMayFormMemmove(unsigned StoreSize, bool IsNegStride,
1288                                   const Instruction &TheLoad,
1289                                   bool IsMemCpy) const {
1290     if (IsMemCpy) {
1291       // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1292       // for negative stride.
1293       if ((!IsNegStride && LoadOff <= StoreOff) ||
1294           (IsNegStride && LoadOff >= StoreOff))
1295         return false;
1296     } else {
1297       // Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr
1298       // for negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr.
1299       int64_t LoadSize =
1300           DL.getTypeSizeInBits(TheLoad.getType()).getFixedSize() / 8;
1301       if (BP1 != BP2 || LoadSize != int64_t(StoreSize))
1302         return false;
1303       if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) ||
1304           (IsNegStride && LoadOff + LoadSize > StoreOff))
1305         return false;
1306     }
1307     return true;
1308   }
1309 
1310 private:
1311   const DataLayout &DL;
1312   int64_t LoadOff;
1313   int64_t StoreOff;
1314   const Value *BP1;
1315   const Value *BP2;
1316 
1317 public:
1318   const bool IsSameObject;
1319 };
1320 
1321 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
1322     Value *DestPtr, Value *SourcePtr, const SCEV *StoreSizeSCEV,
1323     MaybeAlign StoreAlign, MaybeAlign LoadAlign, Instruction *TheStore,
1324     Instruction *TheLoad, const SCEVAddRecExpr *StoreEv,
1325     const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {
1326 
1327   // FIXME: until llvm.memcpy.inline supports dynamic sizes, we need to
1328   // conservatively bail here, since otherwise we may have to transform
1329   // llvm.memcpy.inline into llvm.memcpy which is illegal.
1330   if (isa<MemCpyInlineInst>(TheStore))
1331     return false;
1332 
1333   // The trip count of the loop and the base pointer of the addrec SCEV is
1334   // guaranteed to be loop invariant, which means that it should dominate the
1335   // header.  This allows us to insert code for it in the preheader.
1336   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1337   IRBuilder<> Builder(Preheader->getTerminator());
1338   SCEVExpander Expander(*SE, *DL, "loop-idiom");
1339 
1340   SCEVExpanderCleaner ExpCleaner(Expander);
1341 
1342   bool Changed = false;
1343   const SCEV *StrStart = StoreEv->getStart();
1344   unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();
1345   Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));
1346 
1347   APInt Stride = getStoreStride(StoreEv);
1348   const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);
1349 
1350   // TODO: Deal with non-constant size; Currently expect constant store size
1351   assert(ConstStoreSize && "store size is expected to be a constant");
1352 
1353   int64_t StoreSize = ConstStoreSize->getValue()->getZExtValue();
1354   bool IsNegStride = StoreSize == -Stride;
1355 
1356   // Handle negative strided loops.
1357   if (IsNegStride)
1358     StrStart =
1359         getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1360 
1361   // Okay, we have a strided store "p[i]" of a loaded value.  We can turn
1362   // this into a memcpy in the loop preheader now if we want.  However, this
1363   // would be unsafe to do if there is anything else in the loop that may read
1364   // or write the memory region we're storing to.  This includes the load that
1365   // feeds the stores.  Check for an alias by generating the base address and
1366   // checking everything.
1367   Value *StoreBasePtr = Expander.expandCodeFor(
1368       StrStart, Builder.getInt8PtrTy(StrAS), Preheader->getTerminator());
1369 
1370   // From here on out, conservatively report to the pass manager that we've
1371   // changed the IR, even if we later clean up these added instructions. There
1372   // may be structural differences e.g. in the order of use lists not accounted
1373   // for in just a textual dump of the IR. This is written as a variable, even
1374   // though statically all the places this dominates could be replaced with
1375   // 'true', with the hope that anyone trying to be clever / "more precise" with
1376   // the return value will read this comment, and leave them alone.
1377   Changed = true;
1378 
1379   SmallPtrSet<Instruction *, 2> IgnoredInsts;
1380   IgnoredInsts.insert(TheStore);
1381 
1382   bool IsMemCpy = isa<MemCpyInst>(TheStore);
1383   const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";
1384 
1385   bool LoopAccessStore =
1386       mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,
1387                             StoreSizeSCEV, *AA, IgnoredInsts);
1388   if (LoopAccessStore) {
1389     // For memmove case it's not enough to guarantee that loop doesn't access
1390     // TheStore and TheLoad. Additionally we need to make sure that TheStore is
1391     // the only user of TheLoad.
1392     if (!TheLoad->hasOneUse())
1393       return Changed;
1394     IgnoredInsts.insert(TheLoad);
1395     if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,
1396                               BECount, StoreSizeSCEV, *AA, IgnoredInsts)) {
1397       ORE.emit([&]() {
1398         return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore",
1399                                         TheStore)
1400                << ore::NV("Inst", InstRemark) << " in "
1401                << ore::NV("Function", TheStore->getFunction())
1402                << " function will not be hoisted: "
1403                << ore::NV("Reason", "The loop may access store location");
1404       });
1405       return Changed;
1406     }
1407     IgnoredInsts.erase(TheLoad);
1408   }
1409 
1410   const SCEV *LdStart = LoadEv->getStart();
1411   unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();
1412 
1413   // Handle negative strided loops.
1414   if (IsNegStride)
1415     LdStart =
1416         getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE);
1417 
1418   // For a memcpy, we have to make sure that the input array is not being
1419   // mutated by the loop.
1420   Value *LoadBasePtr = Expander.expandCodeFor(
1421       LdStart, Builder.getInt8PtrTy(LdAS), Preheader->getTerminator());
1422 
1423   // If the store is a memcpy instruction, we must check if it will write to
1424   // the load memory locations. So remove it from the ignored stores.
1425   MemmoveVerifier Verifier(*LoadBasePtr, *StoreBasePtr, *DL);
1426   if (IsMemCpy && !Verifier.IsSameObject)
1427     IgnoredInsts.erase(TheStore);
1428   if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,
1429                             StoreSizeSCEV, *AA, IgnoredInsts)) {
1430     ORE.emit([&]() {
1431       return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad)
1432              << ore::NV("Inst", InstRemark) << " in "
1433              << ore::NV("Function", TheStore->getFunction())
1434              << " function will not be hoisted: "
1435              << ore::NV("Reason", "The loop may access load location");
1436     });
1437     return Changed;
1438   }
1439 
1440   bool UseMemMove = IsMemCpy ? Verifier.IsSameObject : LoopAccessStore;
1441   if (UseMemMove)
1442     if (!Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,
1443                                              IsMemCpy))
1444       return Changed;
1445 
1446   if (avoidLIRForMultiBlockLoop())
1447     return Changed;
1448 
1449   // Okay, everything is safe, we can transform this!
1450 
1451   const SCEV *NumBytesS =
1452       getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);
1453 
1454   Value *NumBytes =
1455       Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());
1456 
1457   AAMDNodes AATags = TheLoad->getAAMetadata();
1458   AAMDNodes StoreAATags = TheStore->getAAMetadata();
1459   AATags = AATags.merge(StoreAATags);
1460   if (auto CI = dyn_cast<ConstantInt>(NumBytes))
1461     AATags = AATags.extendTo(CI->getZExtValue());
1462   else
1463     AATags = AATags.extendTo(-1);
1464 
1465   CallInst *NewCall = nullptr;
1466   // Check whether to generate an unordered atomic memcpy:
1467   //  If the load or store are atomic, then they must necessarily be unordered
1468   //  by previous checks.
1469   if (!TheStore->isAtomic() && !TheLoad->isAtomic()) {
1470     if (UseMemMove)
1471       NewCall = Builder.CreateMemMove(
1472           StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign, NumBytes,
1473           /*isVolatile=*/false, AATags.TBAA, AATags.Scope, AATags.NoAlias);
1474     else
1475       NewCall =
1476           Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,
1477                                NumBytes, /*isVolatile=*/false, AATags.TBAA,
1478                                AATags.TBAAStruct, AATags.Scope, AATags.NoAlias);
1479   } else {
1480     // For now don't support unordered atomic memmove.
1481     if (UseMemMove)
1482       return Changed;
1483     // We cannot allow unaligned ops for unordered load/store, so reject
1484     // anything where the alignment isn't at least the element size.
1485     assert((StoreAlign.hasValue() && LoadAlign.hasValue()) &&
1486            "Expect unordered load/store to have align.");
1487     if (StoreAlign.getValue() < StoreSize || LoadAlign.getValue() < StoreSize)
1488       return Changed;
1489 
1490     // If the element.atomic memcpy is not lowered into explicit
1491     // loads/stores later, then it will be lowered into an element-size
1492     // specific lib call. If the lib call doesn't exist for our store size, then
1493     // we shouldn't generate the memcpy.
1494     if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())
1495       return Changed;
1496 
1497     // Create the call.
1498     // Note that unordered atomic loads/stores are *required* by the spec to
1499     // have an alignment but non-atomic loads/stores may not.
1500     NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1501         StoreBasePtr, StoreAlign.getValue(), LoadBasePtr, LoadAlign.getValue(),
1502         NumBytes, StoreSize, AATags.TBAA, AATags.TBAAStruct, AATags.Scope,
1503         AATags.NoAlias);
1504   }
1505   NewCall->setDebugLoc(TheStore->getDebugLoc());
1506 
1507   if (MSSAU) {
1508     MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1509         NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);
1510     MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1511   }
1512 
1513   LLVM_DEBUG(dbgs() << "  Formed new call: " << *NewCall << "\n"
1514                     << "    from load ptr=" << *LoadEv << " at: " << *TheLoad
1515                     << "\n"
1516                     << "    from store ptr=" << *StoreEv << " at: " << *TheStore
1517                     << "\n");
1518 
1519   ORE.emit([&]() {
1520     return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",
1521                               NewCall->getDebugLoc(), Preheader)
1522            << "Formed a call to "
1523            << ore::NV("NewFunction", NewCall->getCalledFunction())
1524            << "() intrinsic from " << ore::NV("Inst", InstRemark)
1525            << " instruction in " << ore::NV("Function", TheStore->getFunction())
1526            << " function"
1527            << ore::setExtraArgs()
1528            << ore::NV("FromBlock", TheStore->getParent()->getName())
1529            << ore::NV("ToBlock", Preheader->getName());
1530   });
1531 
1532   // Okay, a new call to memcpy/memmove has been formed.  Zap the original store
1533   // and anything that feeds into it.
1534   if (MSSAU)
1535     MSSAU->removeMemoryAccess(TheStore, true);
1536   deleteDeadInstruction(TheStore);
1537   if (MSSAU && VerifyMemorySSA)
1538     MSSAU->getMemorySSA()->verifyMemorySSA();
1539   if (UseMemMove)
1540     ++NumMemMove;
1541   else
1542     ++NumMemCpy;
1543   ExpCleaner.markResultUsed();
1544   return true;
1545 }
1546 
1547 // When compiling for codesize we avoid idiom recognition for a multi-block loop
1548 // unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.
1549 //
1550 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,
1551                                                    bool IsLoopMemset) {
1552   if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1553     if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {
1554       LLVM_DEBUG(dbgs() << "  " << CurLoop->getHeader()->getParent()->getName()
1555                         << " : LIR " << (IsMemset ? "Memset" : "Memcpy")
1556                         << " avoided: multi-block top-level loop\n");
1557       return true;
1558     }
1559   }
1560 
1561   return false;
1562 }
1563 
1564 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1565   LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["
1566                     << CurLoop->getHeader()->getParent()->getName()
1567                     << "] Noncountable Loop %"
1568                     << CurLoop->getHeader()->getName() << "\n");
1569 
1570   return recognizePopcount() || recognizeAndInsertFFS() ||
1571          recognizeShiftUntilBitTest() || recognizeShiftUntilZero();
1572 }
1573 
1574 /// Check if the given conditional branch is based on the comparison between
1575 /// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is
1576 /// true), the control yields to the loop entry. If the branch matches the
1577 /// behavior, the variable involved in the comparison is returned. This function
1578 /// will be called to see if the precondition and postcondition of the loop are
1579 /// in desirable form.
1580 static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,
1581                              bool JmpOnZero = false) {
1582   if (!BI || !BI->isConditional())
1583     return nullptr;
1584 
1585   ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());
1586   if (!Cond)
1587     return nullptr;
1588 
1589   ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));
1590   if (!CmpZero || !CmpZero->isZero())
1591     return nullptr;
1592 
1593   BasicBlock *TrueSucc = BI->getSuccessor(0);
1594   BasicBlock *FalseSucc = BI->getSuccessor(1);
1595   if (JmpOnZero)
1596     std::swap(TrueSucc, FalseSucc);
1597 
1598   ICmpInst::Predicate Pred = Cond->getPredicate();
1599   if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||
1600       (Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))
1601     return Cond->getOperand(0);
1602 
1603   return nullptr;
1604 }
1605 
1606 // Check if the recurrence variable `VarX` is in the right form to create
1607 // the idiom. Returns the value coerced to a PHINode if so.
1608 static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,
1609                                  BasicBlock *LoopEntry) {
1610   auto *PhiX = dyn_cast<PHINode>(VarX);
1611   if (PhiX && PhiX->getParent() == LoopEntry &&
1612       (PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))
1613     return PhiX;
1614   return nullptr;
1615 }
1616 
1617 /// Return true iff the idiom is detected in the loop.
1618 ///
1619 /// Additionally:
1620 /// 1) \p CntInst is set to the instruction counting the population bit.
1621 /// 2) \p CntPhi is set to the corresponding phi node.
1622 /// 3) \p Var is set to the value whose population bits are being counted.
1623 ///
1624 /// The core idiom we are trying to detect is:
1625 /// \code
1626 ///    if (x0 != 0)
1627 ///      goto loop-exit // the precondition of the loop
1628 ///    cnt0 = init-val;
1629 ///    do {
1630 ///       x1 = phi (x0, x2);
1631 ///       cnt1 = phi(cnt0, cnt2);
1632 ///
1633 ///       cnt2 = cnt1 + 1;
1634 ///        ...
1635 ///       x2 = x1 & (x1 - 1);
1636 ///        ...
1637 ///    } while(x != 0);
1638 ///
1639 /// loop-exit:
1640 /// \endcode
1641 static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,
1642                                 Instruction *&CntInst, PHINode *&CntPhi,
1643                                 Value *&Var) {
1644   // step 1: Check to see if the look-back branch match this pattern:
1645   //    "if (a!=0) goto loop-entry".
1646   BasicBlock *LoopEntry;
1647   Instruction *DefX2, *CountInst;
1648   Value *VarX1, *VarX0;
1649   PHINode *PhiX, *CountPhi;
1650 
1651   DefX2 = CountInst = nullptr;
1652   VarX1 = VarX0 = nullptr;
1653   PhiX = CountPhi = nullptr;
1654   LoopEntry = *(CurLoop->block_begin());
1655 
1656   // step 1: Check if the loop-back branch is in desirable form.
1657   {
1658     if (Value *T = matchCondition(
1659             dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1660       DefX2 = dyn_cast<Instruction>(T);
1661     else
1662       return false;
1663   }
1664 
1665   // step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"
1666   {
1667     if (!DefX2 || DefX2->getOpcode() != Instruction::And)
1668       return false;
1669 
1670     BinaryOperator *SubOneOp;
1671 
1672     if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))
1673       VarX1 = DefX2->getOperand(1);
1674     else {
1675       VarX1 = DefX2->getOperand(0);
1676       SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));
1677     }
1678     if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)
1679       return false;
1680 
1681     ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));
1682     if (!Dec ||
1683         !((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||
1684           (SubOneOp->getOpcode() == Instruction::Add &&
1685            Dec->isMinusOne()))) {
1686       return false;
1687     }
1688   }
1689 
1690   // step 3: Check the recurrence of variable X
1691   PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);
1692   if (!PhiX)
1693     return false;
1694 
1695   // step 4: Find the instruction which count the population: cnt2 = cnt1 + 1
1696   {
1697     CountInst = nullptr;
1698     for (Instruction &Inst : llvm::make_range(
1699              LoopEntry->getFirstNonPHI()->getIterator(), LoopEntry->end())) {
1700       if (Inst.getOpcode() != Instruction::Add)
1701         continue;
1702 
1703       ConstantInt *Inc = dyn_cast<ConstantInt>(Inst.getOperand(1));
1704       if (!Inc || !Inc->isOne())
1705         continue;
1706 
1707       PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
1708       if (!Phi)
1709         continue;
1710 
1711       // Check if the result of the instruction is live of the loop.
1712       bool LiveOutLoop = false;
1713       for (User *U : Inst.users()) {
1714         if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1715           LiveOutLoop = true;
1716           break;
1717         }
1718       }
1719 
1720       if (LiveOutLoop) {
1721         CountInst = &Inst;
1722         CountPhi = Phi;
1723         break;
1724       }
1725     }
1726 
1727     if (!CountInst)
1728       return false;
1729   }
1730 
1731   // step 5: check if the precondition is in this form:
1732   //   "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"
1733   {
1734     auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1735     Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());
1736     if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))
1737       return false;
1738 
1739     CntInst = CountInst;
1740     CntPhi = CountPhi;
1741     Var = T;
1742   }
1743 
1744   return true;
1745 }
1746 
1747 /// Return true if the idiom is detected in the loop.
1748 ///
1749 /// Additionally:
1750 /// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)
1751 ///       or nullptr if there is no such.
1752 /// 2) \p CntPhi is set to the corresponding phi node
1753 ///       or nullptr if there is no such.
1754 /// 3) \p Var is set to the value whose CTLZ could be used.
1755 /// 4) \p DefX is set to the instruction calculating Loop exit condition.
1756 ///
1757 /// The core idiom we are trying to detect is:
1758 /// \code
1759 ///    if (x0 == 0)
1760 ///      goto loop-exit // the precondition of the loop
1761 ///    cnt0 = init-val;
1762 ///    do {
1763 ///       x = phi (x0, x.next);   //PhiX
1764 ///       cnt = phi(cnt0, cnt.next);
1765 ///
1766 ///       cnt.next = cnt + 1;
1767 ///        ...
1768 ///       x.next = x >> 1;   // DefX
1769 ///        ...
1770 ///    } while(x.next != 0);
1771 ///
1772 /// loop-exit:
1773 /// \endcode
1774 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,
1775                                       Intrinsic::ID &IntrinID, Value *&InitX,
1776                                       Instruction *&CntInst, PHINode *&CntPhi,
1777                                       Instruction *&DefX) {
1778   BasicBlock *LoopEntry;
1779   Value *VarX = nullptr;
1780 
1781   DefX = nullptr;
1782   CntInst = nullptr;
1783   CntPhi = nullptr;
1784   LoopEntry = *(CurLoop->block_begin());
1785 
1786   // step 1: Check if the loop-back branch is in desirable form.
1787   if (Value *T = matchCondition(
1788           dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))
1789     DefX = dyn_cast<Instruction>(T);
1790   else
1791     return false;
1792 
1793   // step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"
1794   if (!DefX || !DefX->isShift())
1795     return false;
1796   IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :
1797                                                      Intrinsic::ctlz;
1798   ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));
1799   if (!Shft || !Shft->isOne())
1800     return false;
1801   VarX = DefX->getOperand(0);
1802 
1803   // step 3: Check the recurrence of variable X
1804   PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);
1805   if (!PhiX)
1806     return false;
1807 
1808   InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1809 
1810   // Make sure the initial value can't be negative otherwise the ashr in the
1811   // loop might never reach zero which would make the loop infinite.
1812   if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))
1813     return false;
1814 
1815   // step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 1
1816   //         or cnt.next = cnt + -1.
1817   // TODO: We can skip the step. If loop trip count is known (CTLZ),
1818   //       then all uses of "cnt.next" could be optimized to the trip count
1819   //       plus "cnt0". Currently it is not optimized.
1820   //       This step could be used to detect POPCNT instruction:
1821   //       cnt.next = cnt + (x.next & 1)
1822   for (Instruction &Inst : llvm::make_range(
1823            LoopEntry->getFirstNonPHI()->getIterator(), LoopEntry->end())) {
1824     if (Inst.getOpcode() != Instruction::Add)
1825       continue;
1826 
1827     ConstantInt *Inc = dyn_cast<ConstantInt>(Inst.getOperand(1));
1828     if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))
1829       continue;
1830 
1831     PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);
1832     if (!Phi)
1833       continue;
1834 
1835     CntInst = &Inst;
1836     CntPhi = Phi;
1837     break;
1838   }
1839   if (!CntInst)
1840     return false;
1841 
1842   return true;
1843 }
1844 
1845 /// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop
1846 /// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new
1847 /// trip count returns true; otherwise, returns false.
1848 bool LoopIdiomRecognize::recognizeAndInsertFFS() {
1849   // Give up if the loop has multiple blocks or multiple backedges.
1850   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1851     return false;
1852 
1853   Intrinsic::ID IntrinID;
1854   Value *InitX;
1855   Instruction *DefX = nullptr;
1856   PHINode *CntPhi = nullptr;
1857   Instruction *CntInst = nullptr;
1858   // Help decide if transformation is profitable. For ShiftUntilZero idiom,
1859   // this is always 6.
1860   size_t IdiomCanonicalSize = 6;
1861 
1862   if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX,
1863                                  CntInst, CntPhi, DefX))
1864     return false;
1865 
1866   bool IsCntPhiUsedOutsideLoop = false;
1867   for (User *U : CntPhi->users())
1868     if (!CurLoop->contains(cast<Instruction>(U))) {
1869       IsCntPhiUsedOutsideLoop = true;
1870       break;
1871     }
1872   bool IsCntInstUsedOutsideLoop = false;
1873   for (User *U : CntInst->users())
1874     if (!CurLoop->contains(cast<Instruction>(U))) {
1875       IsCntInstUsedOutsideLoop = true;
1876       break;
1877     }
1878   // If both CntInst and CntPhi are used outside the loop the profitability
1879   // is questionable.
1880   if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1881     return false;
1882 
1883   // For some CPUs result of CTLZ(X) intrinsic is undefined
1884   // when X is 0. If we can not guarantee X != 0, we need to check this
1885   // when expand.
1886   bool ZeroCheck = false;
1887   // It is safe to assume Preheader exist as it was checked in
1888   // parent function RunOnLoop.
1889   BasicBlock *PH = CurLoop->getLoopPreheader();
1890 
1891   // If we are using the count instruction outside the loop, make sure we
1892   // have a zero check as a precondition. Without the check the loop would run
1893   // one iteration for before any check of the input value. This means 0 and 1
1894   // would have identical behavior in the original loop and thus
1895   if (!IsCntPhiUsedOutsideLoop) {
1896     auto *PreCondBB = PH->getSinglePredecessor();
1897     if (!PreCondBB)
1898       return false;
1899     auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1900     if (!PreCondBI)
1901       return false;
1902     if (matchCondition(PreCondBI, PH) != InitX)
1903       return false;
1904     ZeroCheck = true;
1905   }
1906 
1907   // Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always
1908   // profitable if we delete the loop.
1909 
1910   // the loop has only 6 instructions:
1911   //  %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]
1912   //  %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]
1913   //  %shr = ashr %n.addr.0, 1
1914   //  %tobool = icmp eq %shr, 0
1915   //  %inc = add nsw %i.0, 1
1916   //  br i1 %tobool
1917 
1918   const Value *Args[] = {InitX,
1919                          ConstantInt::getBool(InitX->getContext(), ZeroCheck)};
1920 
1921   // @llvm.dbg doesn't count as they have no semantic effect.
1922   auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();
1923   uint32_t HeaderSize =
1924       std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());
1925 
1926   IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);
1927   InstructionCost Cost =
1928     TTI->getIntrinsicInstrCost(Attrs, TargetTransformInfo::TCK_SizeAndLatency);
1929   if (HeaderSize != IdiomCanonicalSize &&
1930       Cost > TargetTransformInfo::TCC_Basic)
1931     return false;
1932 
1933   transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,
1934                            DefX->getDebugLoc(), ZeroCheck,
1935                            IsCntPhiUsedOutsideLoop);
1936   return true;
1937 }
1938 
1939 /// Recognizes a population count idiom in a non-countable loop.
1940 ///
1941 /// If detected, transforms the relevant code to issue the popcount intrinsic
1942 /// function call, and returns true; otherwise, returns false.
1943 bool LoopIdiomRecognize::recognizePopcount() {
1944   if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)
1945     return false;
1946 
1947   // Counting population are usually conducted by few arithmetic instructions.
1948   // Such instructions can be easily "absorbed" by vacant slots in a
1949   // non-compact loop. Therefore, recognizing popcount idiom only makes sense
1950   // in a compact loop.
1951 
1952   // Give up if the loop has multiple blocks or multiple backedges.
1953   if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1954     return false;
1955 
1956   BasicBlock *LoopBody = *(CurLoop->block_begin());
1957   if (LoopBody->size() >= 20) {
1958     // The loop is too big, bail out.
1959     return false;
1960   }
1961 
1962   // It should have a preheader containing nothing but an unconditional branch.
1963   BasicBlock *PH = CurLoop->getLoopPreheader();
1964   if (!PH || &PH->front() != PH->getTerminator())
1965     return false;
1966   auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());
1967   if (!EntryBI || EntryBI->isConditional())
1968     return false;
1969 
1970   // It should have a precondition block where the generated popcount intrinsic
1971   // function can be inserted.
1972   auto *PreCondBB = PH->getSinglePredecessor();
1973   if (!PreCondBB)
1974     return false;
1975   auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());
1976   if (!PreCondBI || PreCondBI->isUnconditional())
1977     return false;
1978 
1979   Instruction *CntInst;
1980   PHINode *CntPhi;
1981   Value *Val;
1982   if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))
1983     return false;
1984 
1985   transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1986   return true;
1987 }
1988 
1989 static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
1990                                        const DebugLoc &DL) {
1991   Value *Ops[] = {Val};
1992   Type *Tys[] = {Val->getType()};
1993 
1994   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
1995   Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);
1996   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
1997   CI->setDebugLoc(DL);
1998 
1999   return CI;
2000 }
2001 
2002 static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,
2003                                     const DebugLoc &DL, bool ZeroCheck,
2004                                     Intrinsic::ID IID) {
2005   Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};
2006   Type *Tys[] = {Val->getType()};
2007 
2008   Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();
2009   Function *Func = Intrinsic::getDeclaration(M, IID, Tys);
2010   CallInst *CI = IRBuilder.CreateCall(Func, Ops);
2011   CI->setDebugLoc(DL);
2012 
2013   return CI;
2014 }
2015 
2016 /// Transform the following loop (Using CTLZ, CTTZ is similar):
2017 /// loop:
2018 ///   CntPhi = PHI [Cnt0, CntInst]
2019 ///   PhiX = PHI [InitX, DefX]
2020 ///   CntInst = CntPhi + 1
2021 ///   DefX = PhiX >> 1
2022 ///   LOOP_BODY
2023 ///   Br: loop if (DefX != 0)
2024 /// Use(CntPhi) or Use(CntInst)
2025 ///
2026 /// Into:
2027 /// If CntPhi used outside the loop:
2028 ///   CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)
2029 ///   Count = CountPrev + 1
2030 /// else
2031 ///   Count = BitWidth(InitX) - CTLZ(InitX)
2032 /// loop:
2033 ///   CntPhi = PHI [Cnt0, CntInst]
2034 ///   PhiX = PHI [InitX, DefX]
2035 ///   PhiCount = PHI [Count, Dec]
2036 ///   CntInst = CntPhi + 1
2037 ///   DefX = PhiX >> 1
2038 ///   Dec = PhiCount - 1
2039 ///   LOOP_BODY
2040 ///   Br: loop if (Dec != 0)
2041 /// Use(CountPrev + Cnt0) // Use(CntPhi)
2042 /// or
2043 /// Use(Count + Cnt0) // Use(CntInst)
2044 ///
2045 /// If LOOP_BODY is empty the loop will be deleted.
2046 /// If CntInst and DefX are not used in LOOP_BODY they will be removed.
2047 void LoopIdiomRecognize::transformLoopToCountable(
2048     Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,
2049     PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,
2050     bool ZeroCheck, bool IsCntPhiUsedOutsideLoop) {
2051   BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());
2052 
2053   // Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block
2054   IRBuilder<> Builder(PreheaderBr);
2055   Builder.SetCurrentDebugLocation(DL);
2056 
2057   // If there are no uses of CntPhi crate:
2058   //   Count = BitWidth - CTLZ(InitX);
2059   //   NewCount = Count;
2060   // If there are uses of CntPhi create:
2061   //   NewCount = BitWidth - CTLZ(InitX >> 1);
2062   //   Count = NewCount + 1;
2063   Value *InitXNext;
2064   if (IsCntPhiUsedOutsideLoop) {
2065     if (DefX->getOpcode() == Instruction::AShr)
2066       InitXNext = Builder.CreateAShr(InitX, 1);
2067     else if (DefX->getOpcode() == Instruction::LShr)
2068       InitXNext = Builder.CreateLShr(InitX, 1);
2069     else if (DefX->getOpcode() == Instruction::Shl) // cttz
2070       InitXNext = Builder.CreateShl(InitX, 1);
2071     else
2072       llvm_unreachable("Unexpected opcode!");
2073   } else
2074     InitXNext = InitX;
2075   Value *Count =
2076       createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);
2077   Type *CountTy = Count->getType();
2078   Count = Builder.CreateSub(
2079       ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);
2080   Value *NewCount = Count;
2081   if (IsCntPhiUsedOutsideLoop)
2082     Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));
2083 
2084   NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());
2085 
2086   Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);
2087   if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {
2088     // If the counter was being incremented in the loop, add NewCount to the
2089     // counter's initial value, but only if the initial value is not zero.
2090     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2091     if (!InitConst || !InitConst->isZero())
2092       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2093   } else {
2094     // If the count was being decremented in the loop, subtract NewCount from
2095     // the counter's initial value.
2096     NewCount = Builder.CreateSub(CntInitVal, NewCount);
2097   }
2098 
2099   // Step 2: Insert new IV and loop condition:
2100   // loop:
2101   //   ...
2102   //   PhiCount = PHI [Count, Dec]
2103   //   ...
2104   //   Dec = PhiCount - 1
2105   //   ...
2106   //   Br: loop if (Dec != 0)
2107   BasicBlock *Body = *(CurLoop->block_begin());
2108   auto *LbBr = cast<BranchInst>(Body->getTerminator());
2109   ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2110 
2111   PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi", &Body->front());
2112 
2113   Builder.SetInsertPoint(LbCond);
2114   Instruction *TcDec = cast<Instruction>(Builder.CreateSub(
2115       TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));
2116 
2117   TcPhi->addIncoming(Count, Preheader);
2118   TcPhi->addIncoming(TcDec, Body);
2119 
2120   CmpInst::Predicate Pred =
2121       (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
2122   LbCond->setPredicate(Pred);
2123   LbCond->setOperand(0, TcDec);
2124   LbCond->setOperand(1, ConstantInt::get(CountTy, 0));
2125 
2126   // Step 3: All the references to the original counter outside
2127   //  the loop are replaced with the NewCount
2128   if (IsCntPhiUsedOutsideLoop)
2129     CntPhi->replaceUsesOutsideBlock(NewCount, Body);
2130   else
2131     CntInst->replaceUsesOutsideBlock(NewCount, Body);
2132 
2133   // step 4: Forget the "non-computable" trip-count SCEV associated with the
2134   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2135   SE->forgetLoop(CurLoop);
2136 }
2137 
2138 void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,
2139                                                  Instruction *CntInst,
2140                                                  PHINode *CntPhi, Value *Var) {
2141   BasicBlock *PreHead = CurLoop->getLoopPreheader();
2142   auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());
2143   const DebugLoc &DL = CntInst->getDebugLoc();
2144 
2145   // Assuming before transformation, the loop is following:
2146   //  if (x) // the precondition
2147   //     do { cnt++; x &= x - 1; } while(x);
2148 
2149   // Step 1: Insert the ctpop instruction at the end of the precondition block
2150   IRBuilder<> Builder(PreCondBr);
2151   Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
2152   {
2153     PopCnt = createPopcntIntrinsic(Builder, Var, DL);
2154     NewCount = PopCntZext =
2155         Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));
2156 
2157     if (NewCount != PopCnt)
2158       (cast<Instruction>(NewCount))->setDebugLoc(DL);
2159 
2160     // TripCnt is exactly the number of iterations the loop has
2161     TripCnt = NewCount;
2162 
2163     // If the population counter's initial value is not zero, insert Add Inst.
2164     Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);
2165     ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);
2166     if (!InitConst || !InitConst->isZero()) {
2167       NewCount = Builder.CreateAdd(NewCount, CntInitVal);
2168       (cast<Instruction>(NewCount))->setDebugLoc(DL);
2169     }
2170   }
2171 
2172   // Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to
2173   //   "if (NewCount == 0) loop-exit". Without this change, the intrinsic
2174   //   function would be partial dead code, and downstream passes will drag
2175   //   it back from the precondition block to the preheader.
2176   {
2177     ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
2178 
2179     Value *Opnd0 = PopCntZext;
2180     Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);
2181     if (PreCond->getOperand(0) != Var)
2182       std::swap(Opnd0, Opnd1);
2183 
2184     ICmpInst *NewPreCond = cast<ICmpInst>(
2185         Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));
2186     PreCondBr->setCondition(NewPreCond);
2187 
2188     RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);
2189   }
2190 
2191   // Step 3: Note that the population count is exactly the trip count of the
2192   // loop in question, which enable us to convert the loop from noncountable
2193   // loop into a countable one. The benefit is twofold:
2194   //
2195   //  - If the loop only counts population, the entire loop becomes dead after
2196   //    the transformation. It is a lot easier to prove a countable loop dead
2197   //    than to prove a noncountable one. (In some C dialects, an infinite loop
2198   //    isn't dead even if it computes nothing useful. In general, DCE needs
2199   //    to prove a noncountable loop finite before safely delete it.)
2200   //
2201   //  - If the loop also performs something else, it remains alive.
2202   //    Since it is transformed to countable form, it can be aggressively
2203   //    optimized by some optimizations which are in general not applicable
2204   //    to a noncountable loop.
2205   //
2206   // After this step, this loop (conceptually) would look like following:
2207   //   newcnt = __builtin_ctpop(x);
2208   //   t = newcnt;
2209   //   if (x)
2210   //     do { cnt++; x &= x-1; t--) } while (t > 0);
2211   BasicBlock *Body = *(CurLoop->block_begin());
2212   {
2213     auto *LbBr = cast<BranchInst>(Body->getTerminator());
2214     ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
2215     Type *Ty = TripCnt->getType();
2216 
2217     PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi", &Body->front());
2218 
2219     Builder.SetInsertPoint(LbCond);
2220     Instruction *TcDec = cast<Instruction>(
2221         Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),
2222                           "tcdec", false, true));
2223 
2224     TcPhi->addIncoming(TripCnt, PreHead);
2225     TcPhi->addIncoming(TcDec, Body);
2226 
2227     CmpInst::Predicate Pred =
2228         (LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;
2229     LbCond->setPredicate(Pred);
2230     LbCond->setOperand(0, TcDec);
2231     LbCond->setOperand(1, ConstantInt::get(Ty, 0));
2232   }
2233 
2234   // Step 4: All the references to the original population counter outside
2235   //  the loop are replaced with the NewCount -- the value returned from
2236   //  __builtin_ctpop().
2237   CntInst->replaceUsesOutsideBlock(NewCount, Body);
2238 
2239   // step 5: Forget the "non-computable" trip-count SCEV associated with the
2240   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2241   SE->forgetLoop(CurLoop);
2242 }
2243 
2244 /// Match loop-invariant value.
2245 template <typename SubPattern_t> struct match_LoopInvariant {
2246   SubPattern_t SubPattern;
2247   const Loop *L;
2248 
2249   match_LoopInvariant(const SubPattern_t &SP, const Loop *L)
2250       : SubPattern(SP), L(L) {}
2251 
2252   template <typename ITy> bool match(ITy *V) {
2253     return L->isLoopInvariant(V) && SubPattern.match(V);
2254   }
2255 };
2256 
2257 /// Matches if the value is loop-invariant.
2258 template <typename Ty>
2259 inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {
2260   return match_LoopInvariant<Ty>(M, L);
2261 }
2262 
2263 /// Return true if the idiom is detected in the loop.
2264 ///
2265 /// The core idiom we are trying to detect is:
2266 /// \code
2267 ///   entry:
2268 ///     <...>
2269 ///     %bitmask = shl i32 1, %bitpos
2270 ///     br label %loop
2271 ///
2272 ///   loop:
2273 ///     %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2274 ///     %x.curr.bitmasked = and i32 %x.curr, %bitmask
2275 ///     %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2276 ///     %x.next = shl i32 %x.curr, 1
2277 ///     <...>
2278 ///     br i1 %x.curr.isbitunset, label %loop, label %end
2279 ///
2280 ///   end:
2281 ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2282 ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2283 ///     <...>
2284 /// \endcode
2285 static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,
2286                                          Value *&BitMask, Value *&BitPos,
2287                                          Value *&CurrX, Instruction *&NextX) {
2288   LLVM_DEBUG(dbgs() << DEBUG_TYPE
2289              " Performing shift-until-bittest idiom detection.\n");
2290 
2291   // Give up if the loop has multiple blocks or multiple backedges.
2292   if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2293     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
2294     return false;
2295   }
2296 
2297   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2298   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2299   assert(LoopPreheaderBB && "There is always a loop preheader.");
2300 
2301   using namespace PatternMatch;
2302 
2303   // Step 1: Check if the loop backedge is in desirable form.
2304 
2305   ICmpInst::Predicate Pred;
2306   Value *CmpLHS, *CmpRHS;
2307   BasicBlock *TrueBB, *FalseBB;
2308   if (!match(LoopHeaderBB->getTerminator(),
2309              m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
2310                   m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {
2311     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
2312     return false;
2313   }
2314 
2315   // Step 2: Check if the backedge's condition is in desirable form.
2316 
2317   auto MatchVariableBitMask = [&]() {
2318     return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2319            match(CmpLHS,
2320                  m_c_And(m_Value(CurrX),
2321                          m_CombineAnd(
2322                              m_Value(BitMask),
2323                              m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),
2324                                              CurLoop))));
2325   };
2326   auto MatchConstantBitMask = [&]() {
2327     return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&
2328            match(CmpLHS, m_And(m_Value(CurrX),
2329                                m_CombineAnd(m_Value(BitMask), m_Power2()))) &&
2330            (BitPos = ConstantExpr::getExactLogBase2(cast<Constant>(BitMask)));
2331   };
2332   auto MatchDecomposableConstantBitMask = [&]() {
2333     APInt Mask;
2334     return llvm::decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, CurrX, Mask) &&
2335            ICmpInst::isEquality(Pred) && Mask.isPowerOf2() &&
2336            (BitMask = ConstantInt::get(CurrX->getType(), Mask)) &&
2337            (BitPos = ConstantInt::get(CurrX->getType(), Mask.logBase2()));
2338   };
2339 
2340   if (!MatchVariableBitMask() && !MatchConstantBitMask() &&
2341       !MatchDecomposableConstantBitMask()) {
2342     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n");
2343     return false;
2344   }
2345 
2346   // Step 3: Check if the recurrence is in desirable form.
2347   auto *CurrXPN = dyn_cast<PHINode>(CurrX);
2348   if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {
2349     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
2350     return false;
2351   }
2352 
2353   BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);
2354   NextX =
2355       dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));
2356 
2357   assert(CurLoop->isLoopInvariant(BaseX) &&
2358          "Expected BaseX to be avaliable in the preheader!");
2359 
2360   if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) {
2361     // FIXME: support right-shift?
2362     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
2363     return false;
2364   }
2365 
2366   // Step 4: Check if the backedge's destinations are in desirable form.
2367 
2368   assert(ICmpInst::isEquality(Pred) &&
2369          "Should only get equality predicates here.");
2370 
2371   // cmp-br is commutative, so canonicalize to a single variant.
2372   if (Pred != ICmpInst::Predicate::ICMP_EQ) {
2373     Pred = ICmpInst::getInversePredicate(Pred);
2374     std::swap(TrueBB, FalseBB);
2375   }
2376 
2377   // We expect to exit loop when comparison yields false,
2378   // so when it yields true we should branch back to loop header.
2379   if (TrueBB != LoopHeaderBB) {
2380     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
2381     return false;
2382   }
2383 
2384   // Okay, idiom checks out.
2385   return true;
2386 }
2387 
2388 /// Look for the following loop:
2389 /// \code
2390 ///   entry:
2391 ///     <...>
2392 ///     %bitmask = shl i32 1, %bitpos
2393 ///     br label %loop
2394 ///
2395 ///   loop:
2396 ///     %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]
2397 ///     %x.curr.bitmasked = and i32 %x.curr, %bitmask
2398 ///     %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 0
2399 ///     %x.next = shl i32 %x.curr, 1
2400 ///     <...>
2401 ///     br i1 %x.curr.isbitunset, label %loop, label %end
2402 ///
2403 ///   end:
2404 ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2405 ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2406 ///     <...>
2407 /// \endcode
2408 ///
2409 /// And transform it into:
2410 /// \code
2411 ///   entry:
2412 ///     %bitmask = shl i32 1, %bitpos
2413 ///     %lowbitmask = add i32 %bitmask, -1
2414 ///     %mask = or i32 %lowbitmask, %bitmask
2415 ///     %x.masked = and i32 %x, %mask
2416 ///     %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,
2417 ///                                                         i1 true)
2418 ///     %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros
2419 ///     %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -1
2420 ///     %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos
2421 ///     %tripcount = add i32 %backedgetakencount, 1
2422 ///     %x.curr = shl i32 %x, %backedgetakencount
2423 ///     %x.next = shl i32 %x, %tripcount
2424 ///     br label %loop
2425 ///
2426 ///   loop:
2427 ///     %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]
2428 ///     %loop.iv.next = add nuw i32 %loop.iv, 1
2429 ///     %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount
2430 ///     <...>
2431 ///     br i1 %loop.ivcheck, label %end, label %loop
2432 ///
2433 ///   end:
2434 ///     %x.curr.res = phi i32 [ %x.curr, %loop ] <...>
2435 ///     %x.next.res = phi i32 [ %x.next, %loop ] <...>
2436 ///     <...>
2437 /// \endcode
2438 bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {
2439   bool MadeChange = false;
2440 
2441   Value *X, *BitMask, *BitPos, *XCurr;
2442   Instruction *XNext;
2443   if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,
2444                                     XNext)) {
2445     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2446                " shift-until-bittest idiom detection failed.\n");
2447     return MadeChange;
2448   }
2449   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n");
2450 
2451   // Ok, it is the idiom we were looking for, we *could* transform this loop,
2452   // but is it profitable to transform?
2453 
2454   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2455   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2456   assert(LoopPreheaderBB && "There is always a loop preheader.");
2457 
2458   BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2459   assert(SuccessorBB && "There is only a single successor.");
2460 
2461   IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2462   Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());
2463 
2464   Intrinsic::ID IntrID = Intrinsic::ctlz;
2465   Type *Ty = X->getType();
2466   unsigned Bitwidth = Ty->getScalarSizeInBits();
2467 
2468   TargetTransformInfo::TargetCostKind CostKind =
2469       TargetTransformInfo::TCK_SizeAndLatency;
2470 
2471   // The rewrite is considered to be unprofitable iff and only iff the
2472   // intrinsic/shift we'll use are not cheap. Note that we are okay with *just*
2473   // making the loop countable, even if nothing else changes.
2474   IntrinsicCostAttributes Attrs(
2475       IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getTrue()});
2476   InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2477   if (Cost > TargetTransformInfo::TCC_Basic) {
2478     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2479                " Intrinsic is too costly, not beneficial\n");
2480     return MadeChange;
2481   }
2482   if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) >
2483       TargetTransformInfo::TCC_Basic) {
2484     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n");
2485     return MadeChange;
2486   }
2487 
2488   // Ok, transform appears worthwhile.
2489   MadeChange = true;
2490 
2491   // Step 1: Compute the loop trip count.
2492 
2493   Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),
2494                                         BitPos->getName() + ".lowbitmask");
2495   Value *Mask =
2496       Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");
2497   Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");
2498   CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(
2499       IntrID, Ty, {XMasked, /*is_zero_undef=*/Builder.getTrue()},
2500       /*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");
2501   Value *XMaskedNumActiveBits = Builder.CreateSub(
2502       ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,
2503       XMasked->getName() + ".numactivebits", /*HasNUW=*/true,
2504       /*HasNSW=*/Bitwidth != 2);
2505   Value *XMaskedLeadingOnePos =
2506       Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),
2507                         XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,
2508                         /*HasNSW=*/Bitwidth > 2);
2509 
2510   Value *LoopBackedgeTakenCount = Builder.CreateSub(
2511       BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount",
2512       /*HasNUW=*/true, /*HasNSW=*/true);
2513   // We know loop's backedge-taken count, but what's loop's trip count?
2514   // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2515   Value *LoopTripCount =
2516       Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2517                         CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2518                         /*HasNSW=*/Bitwidth != 2);
2519 
2520   // Step 2: Compute the recurrence's final value without a loop.
2521 
2522   // NewX is always safe to compute, because `LoopBackedgeTakenCount`
2523   // will always be smaller than `bitwidth(X)`, i.e. we never get poison.
2524   Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount);
2525   NewX->takeName(XCurr);
2526   if (auto *I = dyn_cast<Instruction>(NewX))
2527     I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2528 
2529   Value *NewXNext;
2530   // Rewriting XNext is more complicated, however, because `X << LoopTripCount`
2531   // will be poison iff `LoopTripCount == bitwidth(X)` (which will happen
2532   // iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know
2533   // that isn't the case, we'll need to emit an alternative, safe IR.
2534   if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||
2535       PatternMatch::match(
2536           BitPos, PatternMatch::m_SpecificInt_ICMP(
2537                       ICmpInst::ICMP_NE, APInt(Ty->getScalarSizeInBits(),
2538                                                Ty->getScalarSizeInBits() - 1))))
2539     NewXNext = Builder.CreateShl(X, LoopTripCount);
2540   else {
2541     // Otherwise, just additionally shift by one. It's the smallest solution,
2542     // alternatively, we could check that NewX is INT_MIN (or BitPos is )
2543     // and select 0 instead.
2544     NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));
2545   }
2546 
2547   NewXNext->takeName(XNext);
2548   if (auto *I = dyn_cast<Instruction>(NewXNext))
2549     I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);
2550 
2551   // Step 3: Adjust the successor basic block to recieve the computed
2552   //         recurrence's final value instead of the recurrence itself.
2553 
2554   XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);
2555   XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);
2556 
2557   // Step 4: Rewrite the loop into a countable form, with canonical IV.
2558 
2559   // The new canonical induction variable.
2560   Builder.SetInsertPoint(&LoopHeaderBB->front());
2561   auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2562 
2563   // The induction itself.
2564   // Note that while NUW is always safe, while NSW is only for bitwidths != 2.
2565   Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2566   auto *IVNext =
2567       Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",
2568                         /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2569 
2570   // The loop trip count check.
2571   auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,
2572                                        CurLoop->getName() + ".ivcheck");
2573   Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);
2574   LoopHeaderBB->getTerminator()->eraseFromParent();
2575 
2576   // Populate the IV PHI.
2577   IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2578   IV->addIncoming(IVNext, LoopHeaderBB);
2579 
2580   // Step 5: Forget the "non-computable" trip-count SCEV associated with the
2581   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2582 
2583   SE->forgetLoop(CurLoop);
2584 
2585   // Other passes will take care of actually deleting the loop if possible.
2586 
2587   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n");
2588 
2589   ++NumShiftUntilBitTest;
2590   return MadeChange;
2591 }
2592 
2593 /// Return true if the idiom is detected in the loop.
2594 ///
2595 /// The core idiom we are trying to detect is:
2596 /// \code
2597 ///   entry:
2598 ///     <...>
2599 ///     %start = <...>
2600 ///     %extraoffset = <...>
2601 ///     <...>
2602 ///     br label %for.cond
2603 ///
2604 ///   loop:
2605 ///     %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2606 ///     %nbits = add nsw i8 %iv, %extraoffset
2607 ///     %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2608 ///     %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2609 ///     %iv.next = add i8 %iv, 1
2610 ///     <...>
2611 ///     br i1 %val.shifted.iszero, label %end, label %loop
2612 ///
2613 ///   end:
2614 ///     %iv.res = phi i8 [ %iv, %loop ] <...>
2615 ///     %nbits.res = phi i8 [ %nbits, %loop ] <...>
2616 ///     %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2617 ///     %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2618 ///     %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2619 ///     <...>
2620 /// \endcode
2621 static bool detectShiftUntilZeroIdiom(Loop *CurLoop, ScalarEvolution *SE,
2622                                       Instruction *&ValShiftedIsZero,
2623                                       Intrinsic::ID &IntrinID, Instruction *&IV,
2624                                       Value *&Start, Value *&Val,
2625                                       const SCEV *&ExtraOffsetExpr,
2626                                       bool &InvertedCond) {
2627   LLVM_DEBUG(dbgs() << DEBUG_TYPE
2628              " Performing shift-until-zero idiom detection.\n");
2629 
2630   // Give up if the loop has multiple blocks or multiple backedges.
2631   if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {
2632     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");
2633     return false;
2634   }
2635 
2636   Instruction *ValShifted, *NBits, *IVNext;
2637   Value *ExtraOffset;
2638 
2639   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2640   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2641   assert(LoopPreheaderBB && "There is always a loop preheader.");
2642 
2643   using namespace PatternMatch;
2644 
2645   // Step 1: Check if the loop backedge, condition is in desirable form.
2646 
2647   ICmpInst::Predicate Pred;
2648   BasicBlock *TrueBB, *FalseBB;
2649   if (!match(LoopHeaderBB->getTerminator(),
2650              m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),
2651                   m_BasicBlock(FalseBB))) ||
2652       !match(ValShiftedIsZero,
2653              m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||
2654       !ICmpInst::isEquality(Pred)) {
2655     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");
2656     return false;
2657   }
2658 
2659   // Step 2: Check if the comparison's operand is in desirable form.
2660   // FIXME: Val could be a one-input PHI node, which we should look past.
2661   if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),
2662                                  m_Instruction(NBits)))) {
2663     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n");
2664     return false;
2665   }
2666   IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz
2667                                                          : Intrinsic::ctlz;
2668 
2669   // Step 3: Check if the shift amount is in desirable form.
2670 
2671   if (match(NBits, m_c_Add(m_Instruction(IV),
2672                            m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2673       (NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))
2674     ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));
2675   else if (match(NBits,
2676                  m_Sub(m_Instruction(IV),
2677                        m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&
2678            NBits->hasNoSignedWrap())
2679     ExtraOffsetExpr = SE->getSCEV(ExtraOffset);
2680   else {
2681     IV = NBits;
2682     ExtraOffsetExpr = SE->getZero(NBits->getType());
2683   }
2684 
2685   // Step 4: Check if the recurrence is in desirable form.
2686   auto *IVPN = dyn_cast<PHINode>(IV);
2687   if (!IVPN || IVPN->getParent() != LoopHeaderBB) {
2688     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");
2689     return false;
2690   }
2691 
2692   Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);
2693   IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));
2694 
2695   if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {
2696     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");
2697     return false;
2698   }
2699 
2700   // Step 4: Check if the backedge's destinations are in desirable form.
2701 
2702   assert(ICmpInst::isEquality(Pred) &&
2703          "Should only get equality predicates here.");
2704 
2705   // cmp-br is commutative, so canonicalize to a single variant.
2706   InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;
2707   if (InvertedCond) {
2708     Pred = ICmpInst::getInversePredicate(Pred);
2709     std::swap(TrueBB, FalseBB);
2710   }
2711 
2712   // We expect to exit loop when comparison yields true,
2713   // so when it yields false we should branch back to loop header.
2714   if (FalseBB != LoopHeaderBB) {
2715     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");
2716     return false;
2717   }
2718 
2719   // The new, countable, loop will certainly only run a known number of
2720   // iterations, It won't be infinite. But the old loop might be infinite
2721   // under certain conditions. For logical shifts, the value will become zero
2722   // after at most bitwidth(%Val) loop iterations. However, for arithmetic
2723   // right-shift, iff the sign bit was set, the value will never become zero,
2724   // and the loop may never finish.
2725   if (ValShifted->getOpcode() == Instruction::AShr &&
2726       !isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {
2727     LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n");
2728     return false;
2729   }
2730 
2731   // Okay, idiom checks out.
2732   return true;
2733 }
2734 
2735 /// Look for the following loop:
2736 /// \code
2737 ///   entry:
2738 ///     <...>
2739 ///     %start = <...>
2740 ///     %extraoffset = <...>
2741 ///     <...>
2742 ///     br label %for.cond
2743 ///
2744 ///   loop:
2745 ///     %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]
2746 ///     %nbits = add nsw i8 %iv, %extraoffset
2747 ///     %val.shifted = {{l,a}shr,shl} i8 %val, %nbits
2748 ///     %val.shifted.iszero = icmp eq i8 %val.shifted, 0
2749 ///     %iv.next = add i8 %iv, 1
2750 ///     <...>
2751 ///     br i1 %val.shifted.iszero, label %end, label %loop
2752 ///
2753 ///   end:
2754 ///     %iv.res = phi i8 [ %iv, %loop ] <...>
2755 ///     %nbits.res = phi i8 [ %nbits, %loop ] <...>
2756 ///     %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>
2757 ///     %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>
2758 ///     %iv.next.res = phi i8 [ %iv.next, %loop ] <...>
2759 ///     <...>
2760 /// \endcode
2761 ///
2762 /// And transform it into:
2763 /// \code
2764 ///   entry:
2765 ///     <...>
2766 ///     %start = <...>
2767 ///     %extraoffset = <...>
2768 ///     <...>
2769 ///     %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)
2770 ///     %val.numactivebits = sub i8 8, %val.numleadingzeros
2771 ///     %extraoffset.neg = sub i8 0, %extraoffset
2772 ///     %tmp = add i8 %val.numactivebits, %extraoffset.neg
2773 ///     %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)
2774 ///     %loop.tripcount = sub i8 %iv.final, %start
2775 ///     br label %loop
2776 ///
2777 ///   loop:
2778 ///     %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]
2779 ///     %loop.iv.next = add i8 %loop.iv, 1
2780 ///     %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount
2781 ///     %iv = add i8 %loop.iv, %start
2782 ///     <...>
2783 ///     br i1 %loop.ivcheck, label %end, label %loop
2784 ///
2785 ///   end:
2786 ///     %iv.res = phi i8 [ %iv.final, %loop ] <...>
2787 ///     <...>
2788 /// \endcode
2789 bool LoopIdiomRecognize::recognizeShiftUntilZero() {
2790   bool MadeChange = false;
2791 
2792   Instruction *ValShiftedIsZero;
2793   Intrinsic::ID IntrID;
2794   Instruction *IV;
2795   Value *Start, *Val;
2796   const SCEV *ExtraOffsetExpr;
2797   bool InvertedCond;
2798   if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,
2799                                  Start, Val, ExtraOffsetExpr, InvertedCond)) {
2800     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2801                " shift-until-zero idiom detection failed.\n");
2802     return MadeChange;
2803   }
2804   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n");
2805 
2806   // Ok, it is the idiom we were looking for, we *could* transform this loop,
2807   // but is it profitable to transform?
2808 
2809   BasicBlock *LoopHeaderBB = CurLoop->getHeader();
2810   BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();
2811   assert(LoopPreheaderBB && "There is always a loop preheader.");
2812 
2813   BasicBlock *SuccessorBB = CurLoop->getExitBlock();
2814   assert(SuccessorBB && "There is only a single successor.");
2815 
2816   IRBuilder<> Builder(LoopPreheaderBB->getTerminator());
2817   Builder.SetCurrentDebugLocation(IV->getDebugLoc());
2818 
2819   Type *Ty = Val->getType();
2820   unsigned Bitwidth = Ty->getScalarSizeInBits();
2821 
2822   TargetTransformInfo::TargetCostKind CostKind =
2823       TargetTransformInfo::TCK_SizeAndLatency;
2824 
2825   // The rewrite is considered to be unprofitable iff and only iff the
2826   // intrinsic we'll use are not cheap. Note that we are okay with *just*
2827   // making the loop countable, even if nothing else changes.
2828   IntrinsicCostAttributes Attrs(
2829       IntrID, Ty, {UndefValue::get(Ty), /*is_zero_undef=*/Builder.getFalse()});
2830   InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);
2831   if (Cost > TargetTransformInfo::TCC_Basic) {
2832     LLVM_DEBUG(dbgs() << DEBUG_TYPE
2833                " Intrinsic is too costly, not beneficial\n");
2834     return MadeChange;
2835   }
2836 
2837   // Ok, transform appears worthwhile.
2838   MadeChange = true;
2839 
2840   bool OffsetIsZero = false;
2841   if (auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr))
2842     OffsetIsZero = ExtraOffsetExprC->isZero();
2843 
2844   // Step 1: Compute the loop's final IV value / trip count.
2845 
2846   CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic(
2847       IntrID, Ty, {Val, /*is_zero_undef=*/Builder.getFalse()},
2848       /*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");
2849   Value *ValNumActiveBits = Builder.CreateSub(
2850       ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,
2851       Val->getName() + ".numactivebits", /*HasNUW=*/true,
2852       /*HasNSW=*/Bitwidth != 2);
2853 
2854   SCEVExpander Expander(*SE, *DL, "loop-idiom");
2855   Expander.setInsertPoint(&*Builder.GetInsertPoint());
2856   Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);
2857 
2858   Value *ValNumActiveBitsOffset = Builder.CreateAdd(
2859       ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",
2860       /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);
2861   Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},
2862                                            {ValNumActiveBitsOffset, Start},
2863                                            /*FMFSource=*/nullptr, "iv.final");
2864 
2865   auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(
2866       IVFinal, Start, CurLoop->getName() + ".backedgetakencount",
2867       /*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));
2868   // FIXME: or when the offset was `add nuw`
2869 
2870   // We know loop's backedge-taken count, but what's loop's trip count?
2871   Value *LoopTripCount =
2872       Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),
2873                         CurLoop->getName() + ".tripcount", /*HasNUW=*/true,
2874                         /*HasNSW=*/Bitwidth != 2);
2875 
2876   // Step 2: Adjust the successor basic block to recieve the original
2877   //         induction variable's final value instead of the orig. IV itself.
2878 
2879   IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);
2880 
2881   // Step 3: Rewrite the loop into a countable form, with canonical IV.
2882 
2883   // The new canonical induction variable.
2884   Builder.SetInsertPoint(&LoopHeaderBB->front());
2885   auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");
2886 
2887   // The induction itself.
2888   Builder.SetInsertPoint(LoopHeaderBB->getFirstNonPHI());
2889   auto *CIVNext =
2890       Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",
2891                         /*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);
2892 
2893   // The loop trip count check.
2894   auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,
2895                                         CurLoop->getName() + ".ivcheck");
2896   auto *NewIVCheck = CIVCheck;
2897   if (InvertedCond) {
2898     NewIVCheck = Builder.CreateNot(CIVCheck);
2899     NewIVCheck->takeName(ValShiftedIsZero);
2900   }
2901 
2902   // The original IV, but rebased to be an offset to the CIV.
2903   auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,
2904                                      /*HasNSW=*/true); // FIXME: what about NUW?
2905   IVDePHId->takeName(IV);
2906 
2907   // The loop terminator.
2908   Builder.SetInsertPoint(LoopHeaderBB->getTerminator());
2909   Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);
2910   LoopHeaderBB->getTerminator()->eraseFromParent();
2911 
2912   // Populate the IV PHI.
2913   CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);
2914   CIV->addIncoming(CIVNext, LoopHeaderBB);
2915 
2916   // Step 4: Forget the "non-computable" trip-count SCEV associated with the
2917   //   loop. The loop would otherwise not be deleted even if it becomes empty.
2918 
2919   SE->forgetLoop(CurLoop);
2920 
2921   // Step 5: Try to cleanup the loop's body somewhat.
2922   IV->replaceAllUsesWith(IVDePHId);
2923   IV->eraseFromParent();
2924 
2925   ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);
2926   ValShiftedIsZero->eraseFromParent();
2927 
2928   // Other passes will take care of actually deleting the loop if possible.
2929 
2930   LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n");
2931 
2932   ++NumShiftUntilZero;
2933   return MadeChange;
2934 }
2935