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