Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopIdiomRecognize.cpp
35269 views
//===- LoopIdiomRecognize.cpp - Loop idiom recognition --------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This pass implements an idiom recognizer that transforms simple loops into a9// non-loop form. In cases that this kicks in, it can be a significant10// performance win.11//12// If compiling for code size we avoid idiom recognition if the resulting13// code could be larger than the code for the original loop. One way this could14// happen is if the loop is not removable after idiom recognition due to the15// presence of non-idiom instructions. The initial implementation of the16// heuristics applies to idioms in multi-block loops.17//18//===----------------------------------------------------------------------===//19//20// TODO List:21//22// Future loop memory idioms to recognize:23// memcmp, strlen, etc.24//25// This could recognize common matrix multiplies and dot product idioms and26// replace them with calls to BLAS (if linked in??).27//28//===----------------------------------------------------------------------===//2930#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"31#include "llvm/ADT/APInt.h"32#include "llvm/ADT/ArrayRef.h"33#include "llvm/ADT/DenseMap.h"34#include "llvm/ADT/MapVector.h"35#include "llvm/ADT/SetVector.h"36#include "llvm/ADT/SmallPtrSet.h"37#include "llvm/ADT/SmallVector.h"38#include "llvm/ADT/Statistic.h"39#include "llvm/ADT/StringRef.h"40#include "llvm/Analysis/AliasAnalysis.h"41#include "llvm/Analysis/CmpInstAnalysis.h"42#include "llvm/Analysis/LoopAccessAnalysis.h"43#include "llvm/Analysis/LoopInfo.h"44#include "llvm/Analysis/LoopPass.h"45#include "llvm/Analysis/MemoryLocation.h"46#include "llvm/Analysis/MemorySSA.h"47#include "llvm/Analysis/MemorySSAUpdater.h"48#include "llvm/Analysis/MustExecute.h"49#include "llvm/Analysis/OptimizationRemarkEmitter.h"50#include "llvm/Analysis/ScalarEvolution.h"51#include "llvm/Analysis/ScalarEvolutionExpressions.h"52#include "llvm/Analysis/TargetLibraryInfo.h"53#include "llvm/Analysis/TargetTransformInfo.h"54#include "llvm/Analysis/ValueTracking.h"55#include "llvm/IR/BasicBlock.h"56#include "llvm/IR/Constant.h"57#include "llvm/IR/Constants.h"58#include "llvm/IR/DataLayout.h"59#include "llvm/IR/DebugLoc.h"60#include "llvm/IR/DerivedTypes.h"61#include "llvm/IR/Dominators.h"62#include "llvm/IR/GlobalValue.h"63#include "llvm/IR/GlobalVariable.h"64#include "llvm/IR/IRBuilder.h"65#include "llvm/IR/InstrTypes.h"66#include "llvm/IR/Instruction.h"67#include "llvm/IR/Instructions.h"68#include "llvm/IR/IntrinsicInst.h"69#include "llvm/IR/Intrinsics.h"70#include "llvm/IR/LLVMContext.h"71#include "llvm/IR/Module.h"72#include "llvm/IR/PassManager.h"73#include "llvm/IR/PatternMatch.h"74#include "llvm/IR/Type.h"75#include "llvm/IR/User.h"76#include "llvm/IR/Value.h"77#include "llvm/IR/ValueHandle.h"78#include "llvm/Support/Casting.h"79#include "llvm/Support/CommandLine.h"80#include "llvm/Support/Debug.h"81#include "llvm/Support/InstructionCost.h"82#include "llvm/Support/raw_ostream.h"83#include "llvm/Transforms/Utils/BuildLibCalls.h"84#include "llvm/Transforms/Utils/Local.h"85#include "llvm/Transforms/Utils/LoopUtils.h"86#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"87#include <algorithm>88#include <cassert>89#include <cstdint>90#include <utility>91#include <vector>9293using namespace llvm;9495#define DEBUG_TYPE "loop-idiom"9697STATISTIC(NumMemSet, "Number of memset's formed from loop stores");98STATISTIC(NumMemCpy, "Number of memcpy's formed from loop load+stores");99STATISTIC(NumMemMove, "Number of memmove's formed from loop load+stores");100STATISTIC(101NumShiftUntilBitTest,102"Number of uncountable loops recognized as 'shift until bitttest' idiom");103STATISTIC(NumShiftUntilZero,104"Number of uncountable loops recognized as 'shift until zero' idiom");105106bool DisableLIRP::All;107static cl::opt<bool, true>108DisableLIRPAll("disable-" DEBUG_TYPE "-all",109cl::desc("Options to disable Loop Idiom Recognize Pass."),110cl::location(DisableLIRP::All), cl::init(false),111cl::ReallyHidden);112113bool DisableLIRP::Memset;114static cl::opt<bool, true>115DisableLIRPMemset("disable-" DEBUG_TYPE "-memset",116cl::desc("Proceed with loop idiom recognize pass, but do "117"not convert loop(s) to memset."),118cl::location(DisableLIRP::Memset), cl::init(false),119cl::ReallyHidden);120121bool DisableLIRP::Memcpy;122static cl::opt<bool, true>123DisableLIRPMemcpy("disable-" DEBUG_TYPE "-memcpy",124cl::desc("Proceed with loop idiom recognize pass, but do "125"not convert loop(s) to memcpy."),126cl::location(DisableLIRP::Memcpy), cl::init(false),127cl::ReallyHidden);128129static cl::opt<bool> UseLIRCodeSizeHeurs(130"use-lir-code-size-heurs",131cl::desc("Use loop idiom recognition code size heuristics when compiling"132"with -Os/-Oz"),133cl::init(true), cl::Hidden);134135namespace {136137class LoopIdiomRecognize {138Loop *CurLoop = nullptr;139AliasAnalysis *AA;140DominatorTree *DT;141LoopInfo *LI;142ScalarEvolution *SE;143TargetLibraryInfo *TLI;144const TargetTransformInfo *TTI;145const DataLayout *DL;146OptimizationRemarkEmitter &ORE;147bool ApplyCodeSizeHeuristics;148std::unique_ptr<MemorySSAUpdater> MSSAU;149150public:151explicit LoopIdiomRecognize(AliasAnalysis *AA, DominatorTree *DT,152LoopInfo *LI, ScalarEvolution *SE,153TargetLibraryInfo *TLI,154const TargetTransformInfo *TTI, MemorySSA *MSSA,155const DataLayout *DL,156OptimizationRemarkEmitter &ORE)157: AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL), ORE(ORE) {158if (MSSA)159MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);160}161162bool runOnLoop(Loop *L);163164private:165using StoreList = SmallVector<StoreInst *, 8>;166using StoreListMap = MapVector<Value *, StoreList>;167168StoreListMap StoreRefsForMemset;169StoreListMap StoreRefsForMemsetPattern;170StoreList StoreRefsForMemcpy;171bool HasMemset;172bool HasMemsetPattern;173bool HasMemcpy;174175/// Return code for isLegalStore()176enum LegalStoreKind {177None = 0,178Memset,179MemsetPattern,180Memcpy,181UnorderedAtomicMemcpy,182DontUse // Dummy retval never to be used. Allows catching errors in retval183// handling.184};185186/// \name Countable Loop Idiom Handling187/// @{188189bool runOnCountableLoop();190bool runOnLoopBlock(BasicBlock *BB, const SCEV *BECount,191SmallVectorImpl<BasicBlock *> &ExitBlocks);192193void collectStores(BasicBlock *BB);194LegalStoreKind isLegalStore(StoreInst *SI);195enum class ForMemset { No, Yes };196bool processLoopStores(SmallVectorImpl<StoreInst *> &SL, const SCEV *BECount,197ForMemset For);198199template <typename MemInst>200bool processLoopMemIntrinsic(201BasicBlock *BB,202bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),203const SCEV *BECount);204bool processLoopMemCpy(MemCpyInst *MCI, const SCEV *BECount);205bool processLoopMemSet(MemSetInst *MSI, const SCEV *BECount);206207bool processLoopStridedStore(Value *DestPtr, const SCEV *StoreSizeSCEV,208MaybeAlign StoreAlignment, Value *StoredVal,209Instruction *TheStore,210SmallPtrSetImpl<Instruction *> &Stores,211const SCEVAddRecExpr *Ev, const SCEV *BECount,212bool IsNegStride, bool IsLoopMemset = false);213bool processLoopStoreOfLoopLoad(StoreInst *SI, const SCEV *BECount);214bool processLoopStoreOfLoopLoad(Value *DestPtr, Value *SourcePtr,215const SCEV *StoreSize, MaybeAlign StoreAlign,216MaybeAlign LoadAlign, Instruction *TheStore,217Instruction *TheLoad,218const SCEVAddRecExpr *StoreEv,219const SCEVAddRecExpr *LoadEv,220const SCEV *BECount);221bool avoidLIRForMultiBlockLoop(bool IsMemset = false,222bool IsLoopMemset = false);223224/// @}225/// \name Noncountable Loop Idiom Handling226/// @{227228bool runOnNoncountableLoop();229230bool recognizePopcount();231void transformLoopToPopcount(BasicBlock *PreCondBB, Instruction *CntInst,232PHINode *CntPhi, Value *Var);233bool isProfitableToInsertFFS(Intrinsic::ID IntrinID, Value *InitX,234bool ZeroCheck, size_t CanonicalSize);235bool insertFFSIfProfitable(Intrinsic::ID IntrinID, Value *InitX,236Instruction *DefX, PHINode *CntPhi,237Instruction *CntInst);238bool recognizeAndInsertFFS(); /// Find First Set: ctlz or cttz239bool recognizeShiftUntilLessThan();240void transformLoopToCountable(Intrinsic::ID IntrinID, BasicBlock *PreCondBB,241Instruction *CntInst, PHINode *CntPhi,242Value *Var, Instruction *DefX,243const DebugLoc &DL, bool ZeroCheck,244bool IsCntPhiUsedOutsideLoop,245bool InsertSub = false);246247bool recognizeShiftUntilBitTest();248bool recognizeShiftUntilZero();249250/// @}251};252} // end anonymous namespace253254PreservedAnalyses LoopIdiomRecognizePass::run(Loop &L, LoopAnalysisManager &AM,255LoopStandardAnalysisResults &AR,256LPMUpdater &) {257if (DisableLIRP::All)258return PreservedAnalyses::all();259260const auto *DL = &L.getHeader()->getDataLayout();261262// For the new PM, we also can't use OptimizationRemarkEmitter as an analysis263// pass. Function analyses need to be preserved across loop transformations264// but ORE cannot be preserved (see comment before the pass definition).265OptimizationRemarkEmitter ORE(L.getHeader()->getParent());266267LoopIdiomRecognize LIR(&AR.AA, &AR.DT, &AR.LI, &AR.SE, &AR.TLI, &AR.TTI,268AR.MSSA, DL, ORE);269if (!LIR.runOnLoop(&L))270return PreservedAnalyses::all();271272auto PA = getLoopPassPreservedAnalyses();273if (AR.MSSA)274PA.preserve<MemorySSAAnalysis>();275return PA;276}277278static void deleteDeadInstruction(Instruction *I) {279I->replaceAllUsesWith(PoisonValue::get(I->getType()));280I->eraseFromParent();281}282283//===----------------------------------------------------------------------===//284//285// Implementation of LoopIdiomRecognize286//287//===----------------------------------------------------------------------===//288289bool LoopIdiomRecognize::runOnLoop(Loop *L) {290CurLoop = L;291// If the loop could not be converted to canonical form, it must have an292// indirectbr in it, just give up.293if (!L->getLoopPreheader())294return false;295296// Disable loop idiom recognition if the function's name is a common idiom.297StringRef Name = L->getHeader()->getParent()->getName();298if (Name == "memset" || Name == "memcpy")299return false;300301// Determine if code size heuristics need to be applied.302ApplyCodeSizeHeuristics =303L->getHeader()->getParent()->hasOptSize() && UseLIRCodeSizeHeurs;304305HasMemset = TLI->has(LibFunc_memset);306HasMemsetPattern = TLI->has(LibFunc_memset_pattern16);307HasMemcpy = TLI->has(LibFunc_memcpy);308309if (HasMemset || HasMemsetPattern || HasMemcpy)310if (SE->hasLoopInvariantBackedgeTakenCount(L))311return runOnCountableLoop();312313return runOnNoncountableLoop();314}315316bool LoopIdiomRecognize::runOnCountableLoop() {317const SCEV *BECount = SE->getBackedgeTakenCount(CurLoop);318assert(!isa<SCEVCouldNotCompute>(BECount) &&319"runOnCountableLoop() called on a loop without a predictable"320"backedge-taken count");321322// If this loop executes exactly one time, then it should be peeled, not323// optimized by this pass.324if (const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))325if (BECst->getAPInt() == 0)326return false;327328SmallVector<BasicBlock *, 8> ExitBlocks;329CurLoop->getUniqueExitBlocks(ExitBlocks);330331LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["332<< CurLoop->getHeader()->getParent()->getName()333<< "] Countable Loop %" << CurLoop->getHeader()->getName()334<< "\n");335336// The following transforms hoist stores/memsets into the loop pre-header.337// Give up if the loop has instructions that may throw.338SimpleLoopSafetyInfo SafetyInfo;339SafetyInfo.computeLoopSafetyInfo(CurLoop);340if (SafetyInfo.anyBlockMayThrow())341return false;342343bool MadeChange = false;344345// Scan all the blocks in the loop that are not in subloops.346for (auto *BB : CurLoop->getBlocks()) {347// Ignore blocks in subloops.348if (LI->getLoopFor(BB) != CurLoop)349continue;350351MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);352}353return MadeChange;354}355356static APInt getStoreStride(const SCEVAddRecExpr *StoreEv) {357const SCEVConstant *ConstStride = cast<SCEVConstant>(StoreEv->getOperand(1));358return ConstStride->getAPInt();359}360361/// getMemSetPatternValue - If a strided store of the specified value is safe to362/// turn into a memset_pattern16, return a ConstantArray of 16 bytes that should363/// be passed in. Otherwise, return null.364///365/// Note that we don't ever attempt to use memset_pattern8 or 4, because these366/// just replicate their input array and then pass on to memset_pattern16.367static Constant *getMemSetPatternValue(Value *V, const DataLayout *DL) {368// FIXME: This could check for UndefValue because it can be merged into any369// other valid pattern.370371// If the value isn't a constant, we can't promote it to being in a constant372// array. We could theoretically do a store to an alloca or something, but373// that doesn't seem worthwhile.374Constant *C = dyn_cast<Constant>(V);375if (!C || isa<ConstantExpr>(C))376return nullptr;377378// Only handle simple values that are a power of two bytes in size.379uint64_t Size = DL->getTypeSizeInBits(V->getType());380if (Size == 0 || (Size & 7) || (Size & (Size - 1)))381return nullptr;382383// Don't care enough about darwin/ppc to implement this.384if (DL->isBigEndian())385return nullptr;386387// Convert to size in bytes.388Size /= 8;389390// TODO: If CI is larger than 16-bytes, we can try slicing it in half to see391// if the top and bottom are the same (e.g. for vectors and large integers).392if (Size > 16)393return nullptr;394395// If the constant is exactly 16 bytes, just use it.396if (Size == 16)397return C;398399// Otherwise, we'll use an array of the constants.400unsigned ArraySize = 16 / Size;401ArrayType *AT = ArrayType::get(V->getType(), ArraySize);402return ConstantArray::get(AT, std::vector<Constant *>(ArraySize, C));403}404405LoopIdiomRecognize::LegalStoreKind406LoopIdiomRecognize::isLegalStore(StoreInst *SI) {407// Don't touch volatile stores.408if (SI->isVolatile())409return LegalStoreKind::None;410// We only want simple or unordered-atomic stores.411if (!SI->isUnordered())412return LegalStoreKind::None;413414// Avoid merging nontemporal stores.415if (SI->getMetadata(LLVMContext::MD_nontemporal))416return LegalStoreKind::None;417418Value *StoredVal = SI->getValueOperand();419Value *StorePtr = SI->getPointerOperand();420421// Don't convert stores of non-integral pointer types to memsets (which stores422// integers).423if (DL->isNonIntegralPointerType(StoredVal->getType()->getScalarType()))424return LegalStoreKind::None;425426// Reject stores that are so large that they overflow an unsigned.427// When storing out scalable vectors we bail out for now, since the code428// below currently only works for constant strides.429TypeSize SizeInBits = DL->getTypeSizeInBits(StoredVal->getType());430if (SizeInBits.isScalable() || (SizeInBits.getFixedValue() & 7) ||431(SizeInBits.getFixedValue() >> 32) != 0)432return LegalStoreKind::None;433434// See if the pointer expression is an AddRec like {base,+,1} on the current435// loop, which indicates a strided store. If we have something else, it's a436// random store we can't handle.437const SCEVAddRecExpr *StoreEv =438dyn_cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));439if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())440return LegalStoreKind::None;441442// Check to see if we have a constant stride.443if (!isa<SCEVConstant>(StoreEv->getOperand(1)))444return LegalStoreKind::None;445446// See if the store can be turned into a memset.447448// If the stored value is a byte-wise value (like i32 -1), then it may be449// turned into a memset of i8 -1, assuming that all the consecutive bytes450// are stored. A store of i32 0x01020304 can never be turned into a memset,451// but it can be turned into memset_pattern if the target supports it.452Value *SplatValue = isBytewiseValue(StoredVal, *DL);453454// Note: memset and memset_pattern on unordered-atomic is yet not supported455bool UnorderedAtomic = SI->isUnordered() && !SI->isSimple();456457// If we're allowed to form a memset, and the stored value would be458// acceptable for memset, use it.459if (!UnorderedAtomic && HasMemset && SplatValue && !DisableLIRP::Memset &&460// Verify that the stored value is loop invariant. If not, we can't461// promote the memset.462CurLoop->isLoopInvariant(SplatValue)) {463// It looks like we can use SplatValue.464return LegalStoreKind::Memset;465}466if (!UnorderedAtomic && HasMemsetPattern && !DisableLIRP::Memset &&467// Don't create memset_pattern16s with address spaces.468StorePtr->getType()->getPointerAddressSpace() == 0 &&469getMemSetPatternValue(StoredVal, DL)) {470// It looks like we can use PatternValue!471return LegalStoreKind::MemsetPattern;472}473474// Otherwise, see if the store can be turned into a memcpy.475if (HasMemcpy && !DisableLIRP::Memcpy) {476// Check to see if the stride matches the size of the store. If so, then we477// know that every byte is touched in the loop.478APInt Stride = getStoreStride(StoreEv);479unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());480if (StoreSize != Stride && StoreSize != -Stride)481return LegalStoreKind::None;482483// The store must be feeding a non-volatile load.484LoadInst *LI = dyn_cast<LoadInst>(SI->getValueOperand());485486// Only allow non-volatile loads487if (!LI || LI->isVolatile())488return LegalStoreKind::None;489// Only allow simple or unordered-atomic loads490if (!LI->isUnordered())491return LegalStoreKind::None;492493// See if the pointer expression is an AddRec like {base,+,1} on the current494// loop, which indicates a strided load. If we have something else, it's a495// random load we can't handle.496const SCEVAddRecExpr *LoadEv =497dyn_cast<SCEVAddRecExpr>(SE->getSCEV(LI->getPointerOperand()));498if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())499return LegalStoreKind::None;500501// The store and load must share the same stride.502if (StoreEv->getOperand(1) != LoadEv->getOperand(1))503return LegalStoreKind::None;504505// Success. This store can be converted into a memcpy.506UnorderedAtomic = UnorderedAtomic || LI->isAtomic();507return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy508: LegalStoreKind::Memcpy;509}510// This store can't be transformed into a memset/memcpy.511return LegalStoreKind::None;512}513514void LoopIdiomRecognize::collectStores(BasicBlock *BB) {515StoreRefsForMemset.clear();516StoreRefsForMemsetPattern.clear();517StoreRefsForMemcpy.clear();518for (Instruction &I : *BB) {519StoreInst *SI = dyn_cast<StoreInst>(&I);520if (!SI)521continue;522523// Make sure this is a strided store with a constant stride.524switch (isLegalStore(SI)) {525case LegalStoreKind::None:526// Nothing to do527break;528case LegalStoreKind::Memset: {529// Find the base pointer.530Value *Ptr = getUnderlyingObject(SI->getPointerOperand());531StoreRefsForMemset[Ptr].push_back(SI);532} break;533case LegalStoreKind::MemsetPattern: {534// Find the base pointer.535Value *Ptr = getUnderlyingObject(SI->getPointerOperand());536StoreRefsForMemsetPattern[Ptr].push_back(SI);537} break;538case LegalStoreKind::Memcpy:539case LegalStoreKind::UnorderedAtomicMemcpy:540StoreRefsForMemcpy.push_back(SI);541break;542default:543assert(false && "unhandled return value");544break;545}546}547}548549/// runOnLoopBlock - Process the specified block, which lives in a counted loop550/// with the specified backedge count. This block is known to be in the current551/// loop and not in any subloops.552bool LoopIdiomRecognize::runOnLoopBlock(553BasicBlock *BB, const SCEV *BECount,554SmallVectorImpl<BasicBlock *> &ExitBlocks) {555// We can only promote stores in this block if they are unconditionally556// executed in the loop. For a block to be unconditionally executed, it has557// to dominate all the exit blocks of the loop. Verify this now.558for (BasicBlock *ExitBlock : ExitBlocks)559if (!DT->dominates(BB, ExitBlock))560return false;561562bool MadeChange = false;563// Look for store instructions, which may be optimized to memset/memcpy.564collectStores(BB);565566// Look for a single store or sets of stores with a common base, which can be567// optimized into a memset (memset_pattern). The latter most commonly happens568// with structs and handunrolled loops.569for (auto &SL : StoreRefsForMemset)570MadeChange |= processLoopStores(SL.second, BECount, ForMemset::Yes);571572for (auto &SL : StoreRefsForMemsetPattern)573MadeChange |= processLoopStores(SL.second, BECount, ForMemset::No);574575// Optimize the store into a memcpy, if it feeds an similarly strided load.576for (auto &SI : StoreRefsForMemcpy)577MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);578579MadeChange |= processLoopMemIntrinsic<MemCpyInst>(580BB, &LoopIdiomRecognize::processLoopMemCpy, BECount);581MadeChange |= processLoopMemIntrinsic<MemSetInst>(582BB, &LoopIdiomRecognize::processLoopMemSet, BECount);583584return MadeChange;585}586587/// See if this store(s) can be promoted to a memset.588bool LoopIdiomRecognize::processLoopStores(SmallVectorImpl<StoreInst *> &SL,589const SCEV *BECount, ForMemset For) {590// Try to find consecutive stores that can be transformed into memsets.591SetVector<StoreInst *> Heads, Tails;592SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;593594// Do a quadratic search on all of the given stores and find595// all of the pairs of stores that follow each other.596SmallVector<unsigned, 16> IndexQueue;597for (unsigned i = 0, e = SL.size(); i < e; ++i) {598assert(SL[i]->isSimple() && "Expected only non-volatile stores.");599600Value *FirstStoredVal = SL[i]->getValueOperand();601Value *FirstStorePtr = SL[i]->getPointerOperand();602const SCEVAddRecExpr *FirstStoreEv =603cast<SCEVAddRecExpr>(SE->getSCEV(FirstStorePtr));604APInt FirstStride = getStoreStride(FirstStoreEv);605unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->getType());606607// See if we can optimize just this store in isolation.608if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {609Heads.insert(SL[i]);610continue;611}612613Value *FirstSplatValue = nullptr;614Constant *FirstPatternValue = nullptr;615616if (For == ForMemset::Yes)617FirstSplatValue = isBytewiseValue(FirstStoredVal, *DL);618else619FirstPatternValue = getMemSetPatternValue(FirstStoredVal, DL);620621assert((FirstSplatValue || FirstPatternValue) &&622"Expected either splat value or pattern value.");623624IndexQueue.clear();625// If a store has multiple consecutive store candidates, search Stores626// array according to the sequence: from i+1 to e, then from i-1 to 0.627// This is because usually pairing with immediate succeeding or preceding628// candidate create the best chance to find memset opportunity.629unsigned j = 0;630for (j = i + 1; j < e; ++j)631IndexQueue.push_back(j);632for (j = i; j > 0; --j)633IndexQueue.push_back(j - 1);634635for (auto &k : IndexQueue) {636assert(SL[k]->isSimple() && "Expected only non-volatile stores.");637Value *SecondStorePtr = SL[k]->getPointerOperand();638const SCEVAddRecExpr *SecondStoreEv =639cast<SCEVAddRecExpr>(SE->getSCEV(SecondStorePtr));640APInt SecondStride = getStoreStride(SecondStoreEv);641642if (FirstStride != SecondStride)643continue;644645Value *SecondStoredVal = SL[k]->getValueOperand();646Value *SecondSplatValue = nullptr;647Constant *SecondPatternValue = nullptr;648649if (For == ForMemset::Yes)650SecondSplatValue = isBytewiseValue(SecondStoredVal, *DL);651else652SecondPatternValue = getMemSetPatternValue(SecondStoredVal, DL);653654assert((SecondSplatValue || SecondPatternValue) &&655"Expected either splat value or pattern value.");656657if (isConsecutiveAccess(SL[i], SL[k], *DL, *SE, false)) {658if (For == ForMemset::Yes) {659if (isa<UndefValue>(FirstSplatValue))660FirstSplatValue = SecondSplatValue;661if (FirstSplatValue != SecondSplatValue)662continue;663} else {664if (isa<UndefValue>(FirstPatternValue))665FirstPatternValue = SecondPatternValue;666if (FirstPatternValue != SecondPatternValue)667continue;668}669Tails.insert(SL[k]);670Heads.insert(SL[i]);671ConsecutiveChain[SL[i]] = SL[k];672break;673}674}675}676677// We may run into multiple chains that merge into a single chain. We mark the678// stores that we transformed so that we don't visit the same store twice.679SmallPtrSet<Value *, 16> TransformedStores;680bool Changed = false;681682// For stores that start but don't end a link in the chain:683for (StoreInst *I : Heads) {684if (Tails.count(I))685continue;686687// We found a store instr that starts a chain. Now follow the chain and try688// to transform it.689SmallPtrSet<Instruction *, 8> AdjacentStores;690StoreInst *HeadStore = I;691unsigned StoreSize = 0;692693// Collect the chain into a list.694while (Tails.count(I) || Heads.count(I)) {695if (TransformedStores.count(I))696break;697AdjacentStores.insert(I);698699StoreSize += DL->getTypeStoreSize(I->getValueOperand()->getType());700// Move to the next value in the chain.701I = ConsecutiveChain[I];702}703704Value *StoredVal = HeadStore->getValueOperand();705Value *StorePtr = HeadStore->getPointerOperand();706const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));707APInt Stride = getStoreStride(StoreEv);708709// Check to see if the stride matches the size of the stores. If so, then710// we know that every byte is touched in the loop.711if (StoreSize != Stride && StoreSize != -Stride)712continue;713714bool IsNegStride = StoreSize == -Stride;715716Type *IntIdxTy = DL->getIndexType(StorePtr->getType());717const SCEV *StoreSizeSCEV = SE->getConstant(IntIdxTy, StoreSize);718if (processLoopStridedStore(StorePtr, StoreSizeSCEV,719MaybeAlign(HeadStore->getAlign()), StoredVal,720HeadStore, AdjacentStores, StoreEv, BECount,721IsNegStride)) {722TransformedStores.insert(AdjacentStores.begin(), AdjacentStores.end());723Changed = true;724}725}726727return Changed;728}729730/// processLoopMemIntrinsic - Template function for calling different processor731/// functions based on mem intrinsic type.732template <typename MemInst>733bool LoopIdiomRecognize::processLoopMemIntrinsic(734BasicBlock *BB,735bool (LoopIdiomRecognize::*Processor)(MemInst *, const SCEV *),736const SCEV *BECount) {737bool MadeChange = false;738for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {739Instruction *Inst = &*I++;740// Look for memory instructions, which may be optimized to a larger one.741if (MemInst *MI = dyn_cast<MemInst>(Inst)) {742WeakTrackingVH InstPtr(&*I);743if (!(this->*Processor)(MI, BECount))744continue;745MadeChange = true;746747// If processing the instruction invalidated our iterator, start over from748// the top of the block.749if (!InstPtr)750I = BB->begin();751}752}753return MadeChange;754}755756/// processLoopMemCpy - See if this memcpy can be promoted to a large memcpy757bool LoopIdiomRecognize::processLoopMemCpy(MemCpyInst *MCI,758const SCEV *BECount) {759// We can only handle non-volatile memcpys with a constant size.760if (MCI->isVolatile() || !isa<ConstantInt>(MCI->getLength()))761return false;762763// If we're not allowed to hack on memcpy, we fail.764if ((!HasMemcpy && !isa<MemCpyInlineInst>(MCI)) || DisableLIRP::Memcpy)765return false;766767Value *Dest = MCI->getDest();768Value *Source = MCI->getSource();769if (!Dest || !Source)770return false;771772// See if the load and store pointer expressions are AddRec like {base,+,1} on773// the current loop, which indicates a strided load and store. If we have774// something else, it's a random load or store we can't handle.775const SCEVAddRecExpr *StoreEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Dest));776if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())777return false;778const SCEVAddRecExpr *LoadEv = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Source));779if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())780return false;781782// Reject memcpys that are so large that they overflow an unsigned.783uint64_t SizeInBytes = cast<ConstantInt>(MCI->getLength())->getZExtValue();784if ((SizeInBytes >> 32) != 0)785return false;786787// Check if the stride matches the size of the memcpy. If so, then we know788// that every byte is touched in the loop.789const SCEVConstant *ConstStoreStride =790dyn_cast<SCEVConstant>(StoreEv->getOperand(1));791const SCEVConstant *ConstLoadStride =792dyn_cast<SCEVConstant>(LoadEv->getOperand(1));793if (!ConstStoreStride || !ConstLoadStride)794return false;795796APInt StoreStrideValue = ConstStoreStride->getAPInt();797APInt LoadStrideValue = ConstLoadStride->getAPInt();798// Huge stride value - give up799if (StoreStrideValue.getBitWidth() > 64 || LoadStrideValue.getBitWidth() > 64)800return false;801802if (SizeInBytes != StoreStrideValue && SizeInBytes != -StoreStrideValue) {803ORE.emit([&]() {804return OptimizationRemarkMissed(DEBUG_TYPE, "SizeStrideUnequal", MCI)805<< ore::NV("Inst", "memcpy") << " in "806<< ore::NV("Function", MCI->getFunction())807<< " function will not be hoisted: "808<< ore::NV("Reason", "memcpy size is not equal to stride");809});810return false;811}812813int64_t StoreStrideInt = StoreStrideValue.getSExtValue();814int64_t LoadStrideInt = LoadStrideValue.getSExtValue();815// Check if the load stride matches the store stride.816if (StoreStrideInt != LoadStrideInt)817return false;818819return processLoopStoreOfLoopLoad(820Dest, Source, SE->getConstant(Dest->getType(), SizeInBytes),821MCI->getDestAlign(), MCI->getSourceAlign(), MCI, MCI, StoreEv, LoadEv,822BECount);823}824825/// processLoopMemSet - See if this memset can be promoted to a large memset.826bool LoopIdiomRecognize::processLoopMemSet(MemSetInst *MSI,827const SCEV *BECount) {828// We can only handle non-volatile memsets.829if (MSI->isVolatile())830return false;831832// If we're not allowed to hack on memset, we fail.833if (!HasMemset || DisableLIRP::Memset)834return false;835836Value *Pointer = MSI->getDest();837838// See if the pointer expression is an AddRec like {base,+,1} on the current839// loop, which indicates a strided store. If we have something else, it's a840// random store we can't handle.841const SCEVAddRecExpr *Ev = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Pointer));842if (!Ev || Ev->getLoop() != CurLoop)843return false;844if (!Ev->isAffine()) {845LLVM_DEBUG(dbgs() << " Pointer is not affine, abort\n");846return false;847}848849const SCEV *PointerStrideSCEV = Ev->getOperand(1);850const SCEV *MemsetSizeSCEV = SE->getSCEV(MSI->getLength());851if (!PointerStrideSCEV || !MemsetSizeSCEV)852return false;853854bool IsNegStride = false;855const bool IsConstantSize = isa<ConstantInt>(MSI->getLength());856857if (IsConstantSize) {858// Memset size is constant.859// Check if the pointer stride matches the memset size. If so, then860// we know that every byte is touched in the loop.861LLVM_DEBUG(dbgs() << " memset size is constant\n");862uint64_t SizeInBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();863const SCEVConstant *ConstStride = dyn_cast<SCEVConstant>(Ev->getOperand(1));864if (!ConstStride)865return false;866867APInt Stride = ConstStride->getAPInt();868if (SizeInBytes != Stride && SizeInBytes != -Stride)869return false;870871IsNegStride = SizeInBytes == -Stride;872} else {873// Memset size is non-constant.874// Check if the pointer stride matches the memset size.875// To be conservative, the pass would not promote pointers that aren't in876// address space zero. Also, the pass only handles memset length and stride877// that are invariant for the top level loop.878LLVM_DEBUG(dbgs() << " memset size is non-constant\n");879if (Pointer->getType()->getPointerAddressSpace() != 0) {880LLVM_DEBUG(dbgs() << " pointer is not in address space zero, "881<< "abort\n");882return false;883}884if (!SE->isLoopInvariant(MemsetSizeSCEV, CurLoop)) {885LLVM_DEBUG(dbgs() << " memset size is not a loop-invariant, "886<< "abort\n");887return false;888}889890// Compare positive direction PointerStrideSCEV with MemsetSizeSCEV891IsNegStride = PointerStrideSCEV->isNonConstantNegative();892const SCEV *PositiveStrideSCEV =893IsNegStride ? SE->getNegativeSCEV(PointerStrideSCEV)894: PointerStrideSCEV;895LLVM_DEBUG(dbgs() << " MemsetSizeSCEV: " << *MemsetSizeSCEV << "\n"896<< " PositiveStrideSCEV: " << *PositiveStrideSCEV897<< "\n");898899if (PositiveStrideSCEV != MemsetSizeSCEV) {900// If an expression is covered by the loop guard, compare again and901// proceed with optimization if equal.902const SCEV *FoldedPositiveStride =903SE->applyLoopGuards(PositiveStrideSCEV, CurLoop);904const SCEV *FoldedMemsetSize =905SE->applyLoopGuards(MemsetSizeSCEV, CurLoop);906907LLVM_DEBUG(dbgs() << " Try to fold SCEV based on loop guard\n"908<< " FoldedMemsetSize: " << *FoldedMemsetSize << "\n"909<< " FoldedPositiveStride: " << *FoldedPositiveStride910<< "\n");911912if (FoldedPositiveStride != FoldedMemsetSize) {913LLVM_DEBUG(dbgs() << " SCEV don't match, abort\n");914return false;915}916}917}918919// Verify that the memset value is loop invariant. If not, we can't promote920// the memset.921Value *SplatValue = MSI->getValue();922if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))923return false;924925SmallPtrSet<Instruction *, 1> MSIs;926MSIs.insert(MSI);927return processLoopStridedStore(Pointer, SE->getSCEV(MSI->getLength()),928MSI->getDestAlign(), SplatValue, MSI, MSIs, Ev,929BECount, IsNegStride, /*IsLoopMemset=*/true);930}931932/// mayLoopAccessLocation - Return true if the specified loop might access the933/// specified pointer location, which is a loop-strided access. The 'Access'934/// argument specifies what the verboten forms of access are (read or write).935static bool936mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L,937const SCEV *BECount, const SCEV *StoreSizeSCEV,938AliasAnalysis &AA,939SmallPtrSetImpl<Instruction *> &IgnoredInsts) {940// Get the location that may be stored across the loop. Since the access is941// strided positively through memory, we say that the modified location starts942// at the pointer and has infinite size.943LocationSize AccessSize = LocationSize::afterPointer();944945// If the loop iterates a fixed number of times, we can refine the access size946// to be exactly the size of the memset, which is (BECount+1)*StoreSize947const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount);948const SCEVConstant *ConstSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);949if (BECst && ConstSize) {950std::optional<uint64_t> BEInt = BECst->getAPInt().tryZExtValue();951std::optional<uint64_t> SizeInt = ConstSize->getAPInt().tryZExtValue();952// FIXME: Should this check for overflow?953if (BEInt && SizeInt)954AccessSize = LocationSize::precise((*BEInt + 1) * *SizeInt);955}956957// TODO: For this to be really effective, we have to dive into the pointer958// operand in the store. Store to &A[i] of 100 will always return may alias959// with store of &A[100], we need to StoreLoc to be "A" with size of 100,960// which will then no-alias a store to &A[100].961MemoryLocation StoreLoc(Ptr, AccessSize);962963for (BasicBlock *B : L->blocks())964for (Instruction &I : *B)965if (!IgnoredInsts.contains(&I) &&966isModOrRefSet(AA.getModRefInfo(&I, StoreLoc) & Access))967return true;968return false;969}970971// If we have a negative stride, Start refers to the end of the memory location972// we're trying to memset. Therefore, we need to recompute the base pointer,973// which is just Start - BECount*Size.974static const SCEV *getStartForNegStride(const SCEV *Start, const SCEV *BECount,975Type *IntPtr, const SCEV *StoreSizeSCEV,976ScalarEvolution *SE) {977const SCEV *Index = SE->getTruncateOrZeroExtend(BECount, IntPtr);978if (!StoreSizeSCEV->isOne()) {979// index = back edge count * store size980Index = SE->getMulExpr(Index,981SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),982SCEV::FlagNUW);983}984// base pointer = start - index * store size985return SE->getMinusSCEV(Start, Index);986}987988/// Compute the number of bytes as a SCEV from the backedge taken count.989///990/// This also maps the SCEV into the provided type and tries to handle the991/// computation in a way that will fold cleanly.992static const SCEV *getNumBytes(const SCEV *BECount, Type *IntPtr,993const SCEV *StoreSizeSCEV, Loop *CurLoop,994const DataLayout *DL, ScalarEvolution *SE) {995const SCEV *TripCountSCEV =996SE->getTripCountFromExitCount(BECount, IntPtr, CurLoop);997return SE->getMulExpr(TripCountSCEV,998SE->getTruncateOrZeroExtend(StoreSizeSCEV, IntPtr),999SCEV::FlagNUW);1000}10011002/// processLoopStridedStore - We see a strided store of some value. If we can1003/// transform this into a memset or memset_pattern in the loop preheader, do so.1004bool LoopIdiomRecognize::processLoopStridedStore(1005Value *DestPtr, const SCEV *StoreSizeSCEV, MaybeAlign StoreAlignment,1006Value *StoredVal, Instruction *TheStore,1007SmallPtrSetImpl<Instruction *> &Stores, const SCEVAddRecExpr *Ev,1008const SCEV *BECount, bool IsNegStride, bool IsLoopMemset) {1009Module *M = TheStore->getModule();1010Value *SplatValue = isBytewiseValue(StoredVal, *DL);1011Constant *PatternValue = nullptr;10121013if (!SplatValue)1014PatternValue = getMemSetPatternValue(StoredVal, DL);10151016assert((SplatValue || PatternValue) &&1017"Expected either splat value or pattern value.");10181019// The trip count of the loop and the base pointer of the addrec SCEV is1020// guaranteed to be loop invariant, which means that it should dominate the1021// header. This allows us to insert code for it in the preheader.1022unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();1023BasicBlock *Preheader = CurLoop->getLoopPreheader();1024IRBuilder<> Builder(Preheader->getTerminator());1025SCEVExpander Expander(*SE, *DL, "loop-idiom");1026SCEVExpanderCleaner ExpCleaner(Expander);10271028Type *DestInt8PtrTy = Builder.getPtrTy(DestAS);1029Type *IntIdxTy = DL->getIndexType(DestPtr->getType());10301031bool Changed = false;1032const SCEV *Start = Ev->getStart();1033// Handle negative strided loops.1034if (IsNegStride)1035Start = getStartForNegStride(Start, BECount, IntIdxTy, StoreSizeSCEV, SE);10361037// TODO: ideally we should still be able to generate memset if SCEV expander1038// is taught to generate the dependencies at the latest point.1039if (!Expander.isSafeToExpand(Start))1040return Changed;10411042// Okay, we have a strided store "p[i]" of a splattable value. We can turn1043// this into a memset in the loop preheader now if we want. However, this1044// would be unsafe to do if there is anything else in the loop that may read1045// or write to the aliased location. Check for any overlap by generating the1046// base pointer and checking the region.1047Value *BasePtr =1048Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->getTerminator());10491050// From here on out, conservatively report to the pass manager that we've1051// changed the IR, even if we later clean up these added instructions. There1052// may be structural differences e.g. in the order of use lists not accounted1053// for in just a textual dump of the IR. This is written as a variable, even1054// though statically all the places this dominates could be replaced with1055// 'true', with the hope that anyone trying to be clever / "more precise" with1056// the return value will read this comment, and leave them alone.1057Changed = true;10581059if (mayLoopAccessLocation(BasePtr, ModRefInfo::ModRef, CurLoop, BECount,1060StoreSizeSCEV, *AA, Stores))1061return Changed;10621063if (avoidLIRForMultiBlockLoop(/*IsMemset=*/true, IsLoopMemset))1064return Changed;10651066// Okay, everything looks good, insert the memset.10671068const SCEV *NumBytesS =1069getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);10701071// TODO: ideally we should still be able to generate memset if SCEV expander1072// is taught to generate the dependencies at the latest point.1073if (!Expander.isSafeToExpand(NumBytesS))1074return Changed;10751076Value *NumBytes =1077Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());10781079if (!SplatValue && !isLibFuncEmittable(M, TLI, LibFunc_memset_pattern16))1080return Changed;10811082AAMDNodes AATags = TheStore->getAAMetadata();1083for (Instruction *Store : Stores)1084AATags = AATags.merge(Store->getAAMetadata());1085if (auto CI = dyn_cast<ConstantInt>(NumBytes))1086AATags = AATags.extendTo(CI->getZExtValue());1087else1088AATags = AATags.extendTo(-1);10891090CallInst *NewCall;1091if (SplatValue) {1092NewCall = Builder.CreateMemSet(1093BasePtr, SplatValue, NumBytes, MaybeAlign(StoreAlignment),1094/*isVolatile=*/false, AATags.TBAA, AATags.Scope, AATags.NoAlias);1095} else {1096assert (isLibFuncEmittable(M, TLI, LibFunc_memset_pattern16));1097// Everything is emitted in default address space1098Type *Int8PtrTy = DestInt8PtrTy;10991100StringRef FuncName = "memset_pattern16";1101FunctionCallee MSP = getOrInsertLibFunc(M, *TLI, LibFunc_memset_pattern16,1102Builder.getVoidTy(), Int8PtrTy, Int8PtrTy, IntIdxTy);1103inferNonMandatoryLibFuncAttrs(M, FuncName, *TLI);11041105// Otherwise we should form a memset_pattern16. PatternValue is known to be1106// an constant array of 16-bytes. Plop the value into a mergable global.1107GlobalVariable *GV = new GlobalVariable(*M, PatternValue->getType(), true,1108GlobalValue::PrivateLinkage,1109PatternValue, ".memset_pattern");1110GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); // Ok to merge these.1111GV->setAlignment(Align(16));1112Value *PatternPtr = GV;1113NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});11141115// Set the TBAA info if present.1116if (AATags.TBAA)1117NewCall->setMetadata(LLVMContext::MD_tbaa, AATags.TBAA);11181119if (AATags.Scope)1120NewCall->setMetadata(LLVMContext::MD_alias_scope, AATags.Scope);11211122if (AATags.NoAlias)1123NewCall->setMetadata(LLVMContext::MD_noalias, AATags.NoAlias);1124}11251126NewCall->setDebugLoc(TheStore->getDebugLoc());11271128if (MSSAU) {1129MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(1130NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);1131MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);1132}11331134LLVM_DEBUG(dbgs() << " Formed memset: " << *NewCall << "\n"1135<< " from store to: " << *Ev << " at: " << *TheStore1136<< "\n");11371138ORE.emit([&]() {1139OptimizationRemark R(DEBUG_TYPE, "ProcessLoopStridedStore",1140NewCall->getDebugLoc(), Preheader);1141R << "Transformed loop-strided store in "1142<< ore::NV("Function", TheStore->getFunction())1143<< " function into a call to "1144<< ore::NV("NewFunction", NewCall->getCalledFunction())1145<< "() intrinsic";1146if (!Stores.empty())1147R << ore::setExtraArgs();1148for (auto *I : Stores) {1149R << ore::NV("FromBlock", I->getParent()->getName())1150<< ore::NV("ToBlock", Preheader->getName());1151}1152return R;1153});11541155// Okay, the memset has been formed. Zap the original store and anything that1156// feeds into it.1157for (auto *I : Stores) {1158if (MSSAU)1159MSSAU->removeMemoryAccess(I, true);1160deleteDeadInstruction(I);1161}1162if (MSSAU && VerifyMemorySSA)1163MSSAU->getMemorySSA()->verifyMemorySSA();1164++NumMemSet;1165ExpCleaner.markResultUsed();1166return true;1167}11681169/// If the stored value is a strided load in the same loop with the same stride1170/// this may be transformable into a memcpy. This kicks in for stuff like1171/// for (i) A[i] = B[i];1172bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(StoreInst *SI,1173const SCEV *BECount) {1174assert(SI->isUnordered() && "Expected only non-volatile non-ordered stores.");11751176Value *StorePtr = SI->getPointerOperand();1177const SCEVAddRecExpr *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));1178unsigned StoreSize = DL->getTypeStoreSize(SI->getValueOperand()->getType());11791180// The store must be feeding a non-volatile load.1181LoadInst *LI = cast<LoadInst>(SI->getValueOperand());1182assert(LI->isUnordered() && "Expected only non-volatile non-ordered loads.");11831184// See if the pointer expression is an AddRec like {base,+,1} on the current1185// loop, which indicates a strided load. If we have something else, it's a1186// random load we can't handle.1187Value *LoadPtr = LI->getPointerOperand();1188const SCEVAddRecExpr *LoadEv = cast<SCEVAddRecExpr>(SE->getSCEV(LoadPtr));11891190const SCEV *StoreSizeSCEV = SE->getConstant(StorePtr->getType(), StoreSize);1191return processLoopStoreOfLoopLoad(StorePtr, LoadPtr, StoreSizeSCEV,1192SI->getAlign(), LI->getAlign(), SI, LI,1193StoreEv, LoadEv, BECount);1194}11951196namespace {1197class MemmoveVerifier {1198public:1199explicit MemmoveVerifier(const Value &LoadBasePtr, const Value &StoreBasePtr,1200const DataLayout &DL)1201: DL(DL), BP1(llvm::GetPointerBaseWithConstantOffset(1202LoadBasePtr.stripPointerCasts(), LoadOff, DL)),1203BP2(llvm::GetPointerBaseWithConstantOffset(1204StoreBasePtr.stripPointerCasts(), StoreOff, DL)),1205IsSameObject(BP1 == BP2) {}12061207bool loadAndStoreMayFormMemmove(unsigned StoreSize, bool IsNegStride,1208const Instruction &TheLoad,1209bool IsMemCpy) const {1210if (IsMemCpy) {1211// Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr1212// for negative stride.1213if ((!IsNegStride && LoadOff <= StoreOff) ||1214(IsNegStride && LoadOff >= StoreOff))1215return false;1216} else {1217// Ensure that LoadBasePtr is after StoreBasePtr or before StoreBasePtr1218// for negative stride. LoadBasePtr shouldn't overlap with StoreBasePtr.1219int64_t LoadSize =1220DL.getTypeSizeInBits(TheLoad.getType()).getFixedValue() / 8;1221if (BP1 != BP2 || LoadSize != int64_t(StoreSize))1222return false;1223if ((!IsNegStride && LoadOff < StoreOff + int64_t(StoreSize)) ||1224(IsNegStride && LoadOff + LoadSize > StoreOff))1225return false;1226}1227return true;1228}12291230private:1231const DataLayout &DL;1232int64_t LoadOff = 0;1233int64_t StoreOff = 0;1234const Value *BP1;1235const Value *BP2;12361237public:1238const bool IsSameObject;1239};1240} // namespace12411242bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(1243Value *DestPtr, Value *SourcePtr, const SCEV *StoreSizeSCEV,1244MaybeAlign StoreAlign, MaybeAlign LoadAlign, Instruction *TheStore,1245Instruction *TheLoad, const SCEVAddRecExpr *StoreEv,1246const SCEVAddRecExpr *LoadEv, const SCEV *BECount) {12471248// FIXME: until llvm.memcpy.inline supports dynamic sizes, we need to1249// conservatively bail here, since otherwise we may have to transform1250// llvm.memcpy.inline into llvm.memcpy which is illegal.1251if (isa<MemCpyInlineInst>(TheStore))1252return false;12531254// The trip count of the loop and the base pointer of the addrec SCEV is1255// guaranteed to be loop invariant, which means that it should dominate the1256// header. This allows us to insert code for it in the preheader.1257BasicBlock *Preheader = CurLoop->getLoopPreheader();1258IRBuilder<> Builder(Preheader->getTerminator());1259SCEVExpander Expander(*SE, *DL, "loop-idiom");12601261SCEVExpanderCleaner ExpCleaner(Expander);12621263bool Changed = false;1264const SCEV *StrStart = StoreEv->getStart();1265unsigned StrAS = DestPtr->getType()->getPointerAddressSpace();1266Type *IntIdxTy = Builder.getIntNTy(DL->getIndexSizeInBits(StrAS));12671268APInt Stride = getStoreStride(StoreEv);1269const SCEVConstant *ConstStoreSize = dyn_cast<SCEVConstant>(StoreSizeSCEV);12701271// TODO: Deal with non-constant size; Currently expect constant store size1272assert(ConstStoreSize && "store size is expected to be a constant");12731274int64_t StoreSize = ConstStoreSize->getValue()->getZExtValue();1275bool IsNegStride = StoreSize == -Stride;12761277// Handle negative strided loops.1278if (IsNegStride)1279StrStart =1280getStartForNegStride(StrStart, BECount, IntIdxTy, StoreSizeSCEV, SE);12811282// Okay, we have a strided store "p[i]" of a loaded value. We can turn1283// this into a memcpy in the loop preheader now if we want. However, this1284// would be unsafe to do if there is anything else in the loop that may read1285// or write the memory region we're storing to. This includes the load that1286// feeds the stores. Check for an alias by generating the base address and1287// checking everything.1288Value *StoreBasePtr = Expander.expandCodeFor(1289StrStart, Builder.getPtrTy(StrAS), Preheader->getTerminator());12901291// From here on out, conservatively report to the pass manager that we've1292// changed the IR, even if we later clean up these added instructions. There1293// may be structural differences e.g. in the order of use lists not accounted1294// for in just a textual dump of the IR. This is written as a variable, even1295// though statically all the places this dominates could be replaced with1296// 'true', with the hope that anyone trying to be clever / "more precise" with1297// the return value will read this comment, and leave them alone.1298Changed = true;12991300SmallPtrSet<Instruction *, 2> IgnoredInsts;1301IgnoredInsts.insert(TheStore);13021303bool IsMemCpy = isa<MemCpyInst>(TheStore);1304const StringRef InstRemark = IsMemCpy ? "memcpy" : "load and store";13051306bool LoopAccessStore =1307mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop, BECount,1308StoreSizeSCEV, *AA, IgnoredInsts);1309if (LoopAccessStore) {1310// For memmove case it's not enough to guarantee that loop doesn't access1311// TheStore and TheLoad. Additionally we need to make sure that TheStore is1312// the only user of TheLoad.1313if (!TheLoad->hasOneUse())1314return Changed;1315IgnoredInsts.insert(TheLoad);1316if (mayLoopAccessLocation(StoreBasePtr, ModRefInfo::ModRef, CurLoop,1317BECount, StoreSizeSCEV, *AA, IgnoredInsts)) {1318ORE.emit([&]() {1319return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessStore",1320TheStore)1321<< ore::NV("Inst", InstRemark) << " in "1322<< ore::NV("Function", TheStore->getFunction())1323<< " function will not be hoisted: "1324<< ore::NV("Reason", "The loop may access store location");1325});1326return Changed;1327}1328IgnoredInsts.erase(TheLoad);1329}13301331const SCEV *LdStart = LoadEv->getStart();1332unsigned LdAS = SourcePtr->getType()->getPointerAddressSpace();13331334// Handle negative strided loops.1335if (IsNegStride)1336LdStart =1337getStartForNegStride(LdStart, BECount, IntIdxTy, StoreSizeSCEV, SE);13381339// For a memcpy, we have to make sure that the input array is not being1340// mutated by the loop.1341Value *LoadBasePtr = Expander.expandCodeFor(LdStart, Builder.getPtrTy(LdAS),1342Preheader->getTerminator());13431344// If the store is a memcpy instruction, we must check if it will write to1345// the load memory locations. So remove it from the ignored stores.1346MemmoveVerifier Verifier(*LoadBasePtr, *StoreBasePtr, *DL);1347if (IsMemCpy && !Verifier.IsSameObject)1348IgnoredInsts.erase(TheStore);1349if (mayLoopAccessLocation(LoadBasePtr, ModRefInfo::Mod, CurLoop, BECount,1350StoreSizeSCEV, *AA, IgnoredInsts)) {1351ORE.emit([&]() {1352return OptimizationRemarkMissed(DEBUG_TYPE, "LoopMayAccessLoad", TheLoad)1353<< ore::NV("Inst", InstRemark) << " in "1354<< ore::NV("Function", TheStore->getFunction())1355<< " function will not be hoisted: "1356<< ore::NV("Reason", "The loop may access load location");1357});1358return Changed;1359}13601361bool UseMemMove = IsMemCpy ? Verifier.IsSameObject : LoopAccessStore;1362if (UseMemMove)1363if (!Verifier.loadAndStoreMayFormMemmove(StoreSize, IsNegStride, *TheLoad,1364IsMemCpy))1365return Changed;13661367if (avoidLIRForMultiBlockLoop())1368return Changed;13691370// Okay, everything is safe, we can transform this!13711372const SCEV *NumBytesS =1373getNumBytes(BECount, IntIdxTy, StoreSizeSCEV, CurLoop, DL, SE);13741375Value *NumBytes =1376Expander.expandCodeFor(NumBytesS, IntIdxTy, Preheader->getTerminator());13771378AAMDNodes AATags = TheLoad->getAAMetadata();1379AAMDNodes StoreAATags = TheStore->getAAMetadata();1380AATags = AATags.merge(StoreAATags);1381if (auto CI = dyn_cast<ConstantInt>(NumBytes))1382AATags = AATags.extendTo(CI->getZExtValue());1383else1384AATags = AATags.extendTo(-1);13851386CallInst *NewCall = nullptr;1387// Check whether to generate an unordered atomic memcpy:1388// If the load or store are atomic, then they must necessarily be unordered1389// by previous checks.1390if (!TheStore->isAtomic() && !TheLoad->isAtomic()) {1391if (UseMemMove)1392NewCall = Builder.CreateMemMove(1393StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign, NumBytes,1394/*isVolatile=*/false, AATags.TBAA, AATags.Scope, AATags.NoAlias);1395else1396NewCall =1397Builder.CreateMemCpy(StoreBasePtr, StoreAlign, LoadBasePtr, LoadAlign,1398NumBytes, /*isVolatile=*/false, AATags.TBAA,1399AATags.TBAAStruct, AATags.Scope, AATags.NoAlias);1400} else {1401// For now don't support unordered atomic memmove.1402if (UseMemMove)1403return Changed;1404// We cannot allow unaligned ops for unordered load/store, so reject1405// anything where the alignment isn't at least the element size.1406assert((StoreAlign && LoadAlign) &&1407"Expect unordered load/store to have align.");1408if (*StoreAlign < StoreSize || *LoadAlign < StoreSize)1409return Changed;14101411// If the element.atomic memcpy is not lowered into explicit1412// loads/stores later, then it will be lowered into an element-size1413// specific lib call. If the lib call doesn't exist for our store size, then1414// we shouldn't generate the memcpy.1415if (StoreSize > TTI->getAtomicMemIntrinsicMaxElementSize())1416return Changed;14171418// Create the call.1419// Note that unordered atomic loads/stores are *required* by the spec to1420// have an alignment but non-atomic loads/stores may not.1421NewCall = Builder.CreateElementUnorderedAtomicMemCpy(1422StoreBasePtr, *StoreAlign, LoadBasePtr, *LoadAlign, NumBytes, StoreSize,1423AATags.TBAA, AATags.TBAAStruct, AATags.Scope, AATags.NoAlias);1424}1425NewCall->setDebugLoc(TheStore->getDebugLoc());14261427if (MSSAU) {1428MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(1429NewCall, nullptr, NewCall->getParent(), MemorySSA::BeforeTerminator);1430MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);1431}14321433LLVM_DEBUG(dbgs() << " Formed new call: " << *NewCall << "\n"1434<< " from load ptr=" << *LoadEv << " at: " << *TheLoad1435<< "\n"1436<< " from store ptr=" << *StoreEv << " at: " << *TheStore1437<< "\n");14381439ORE.emit([&]() {1440return OptimizationRemark(DEBUG_TYPE, "ProcessLoopStoreOfLoopLoad",1441NewCall->getDebugLoc(), Preheader)1442<< "Formed a call to "1443<< ore::NV("NewFunction", NewCall->getCalledFunction())1444<< "() intrinsic from " << ore::NV("Inst", InstRemark)1445<< " instruction in " << ore::NV("Function", TheStore->getFunction())1446<< " function"1447<< ore::setExtraArgs()1448<< ore::NV("FromBlock", TheStore->getParent()->getName())1449<< ore::NV("ToBlock", Preheader->getName());1450});14511452// Okay, a new call to memcpy/memmove has been formed. Zap the original store1453// and anything that feeds into it.1454if (MSSAU)1455MSSAU->removeMemoryAccess(TheStore, true);1456deleteDeadInstruction(TheStore);1457if (MSSAU && VerifyMemorySSA)1458MSSAU->getMemorySSA()->verifyMemorySSA();1459if (UseMemMove)1460++NumMemMove;1461else1462++NumMemCpy;1463ExpCleaner.markResultUsed();1464return true;1465}14661467// When compiling for codesize we avoid idiom recognition for a multi-block loop1468// unless it is a loop_memset idiom or a memset/memcpy idiom in a nested loop.1469//1470bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(bool IsMemset,1471bool IsLoopMemset) {1472if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {1473if (CurLoop->isOutermost() && (!IsMemset || !IsLoopMemset)) {1474LLVM_DEBUG(dbgs() << " " << CurLoop->getHeader()->getParent()->getName()1475<< " : LIR " << (IsMemset ? "Memset" : "Memcpy")1476<< " avoided: multi-block top-level loop\n");1477return true;1478}1479}14801481return false;1482}14831484bool LoopIdiomRecognize::runOnNoncountableLoop() {1485LLVM_DEBUG(dbgs() << DEBUG_TYPE " Scanning: F["1486<< CurLoop->getHeader()->getParent()->getName()1487<< "] Noncountable Loop %"1488<< CurLoop->getHeader()->getName() << "\n");14891490return recognizePopcount() || recognizeAndInsertFFS() ||1491recognizeShiftUntilBitTest() || recognizeShiftUntilZero() ||1492recognizeShiftUntilLessThan();1493}14941495/// Check if the given conditional branch is based on the comparison between1496/// a variable and zero, and if the variable is non-zero or zero (JmpOnZero is1497/// true), the control yields to the loop entry. If the branch matches the1498/// behavior, the variable involved in the comparison is returned. This function1499/// will be called to see if the precondition and postcondition of the loop are1500/// in desirable form.1501static Value *matchCondition(BranchInst *BI, BasicBlock *LoopEntry,1502bool JmpOnZero = false) {1503if (!BI || !BI->isConditional())1504return nullptr;15051506ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());1507if (!Cond)1508return nullptr;15091510ConstantInt *CmpZero = dyn_cast<ConstantInt>(Cond->getOperand(1));1511if (!CmpZero || !CmpZero->isZero())1512return nullptr;15131514BasicBlock *TrueSucc = BI->getSuccessor(0);1515BasicBlock *FalseSucc = BI->getSuccessor(1);1516if (JmpOnZero)1517std::swap(TrueSucc, FalseSucc);15181519ICmpInst::Predicate Pred = Cond->getPredicate();1520if ((Pred == ICmpInst::ICMP_NE && TrueSucc == LoopEntry) ||1521(Pred == ICmpInst::ICMP_EQ && FalseSucc == LoopEntry))1522return Cond->getOperand(0);15231524return nullptr;1525}15261527/// Check if the given conditional branch is based on an unsigned less-than1528/// comparison between a variable and a constant, and if the comparison is false1529/// the control yields to the loop entry. If the branch matches the behaviour,1530/// the variable involved in the comparison is returned.1531static Value *matchShiftULTCondition(BranchInst *BI, BasicBlock *LoopEntry,1532APInt &Threshold) {1533if (!BI || !BI->isConditional())1534return nullptr;15351536ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());1537if (!Cond)1538return nullptr;15391540ConstantInt *CmpConst = dyn_cast<ConstantInt>(Cond->getOperand(1));1541if (!CmpConst)1542return nullptr;15431544BasicBlock *FalseSucc = BI->getSuccessor(1);1545ICmpInst::Predicate Pred = Cond->getPredicate();15461547if (Pred == ICmpInst::ICMP_ULT && FalseSucc == LoopEntry) {1548Threshold = CmpConst->getValue();1549return Cond->getOperand(0);1550}15511552return nullptr;1553}15541555// Check if the recurrence variable `VarX` is in the right form to create1556// the idiom. Returns the value coerced to a PHINode if so.1557static PHINode *getRecurrenceVar(Value *VarX, Instruction *DefX,1558BasicBlock *LoopEntry) {1559auto *PhiX = dyn_cast<PHINode>(VarX);1560if (PhiX && PhiX->getParent() == LoopEntry &&1561(PhiX->getOperand(0) == DefX || PhiX->getOperand(1) == DefX))1562return PhiX;1563return nullptr;1564}15651566/// Return true if the idiom is detected in the loop.1567///1568/// Additionally:1569/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)1570/// or nullptr if there is no such.1571/// 2) \p CntPhi is set to the corresponding phi node1572/// or nullptr if there is no such.1573/// 3) \p InitX is set to the value whose CTLZ could be used.1574/// 4) \p DefX is set to the instruction calculating Loop exit condition.1575/// 5) \p Threshold is set to the constant involved in the unsigned less-than1576/// comparison.1577///1578/// The core idiom we are trying to detect is:1579/// \code1580/// if (x0 < 2)1581/// goto loop-exit // the precondition of the loop1582/// cnt0 = init-val1583/// do {1584/// x = phi (x0, x.next); //PhiX1585/// cnt = phi (cnt0, cnt.next)1586///1587/// cnt.next = cnt + 1;1588/// ...1589/// x.next = x >> 1; // DefX1590/// } while (x >= 4)1591/// loop-exit:1592/// \endcode1593static bool detectShiftUntilLessThanIdiom(Loop *CurLoop, const DataLayout &DL,1594Intrinsic::ID &IntrinID,1595Value *&InitX, Instruction *&CntInst,1596PHINode *&CntPhi, Instruction *&DefX,1597APInt &Threshold) {1598BasicBlock *LoopEntry;15991600DefX = nullptr;1601CntInst = nullptr;1602CntPhi = nullptr;1603LoopEntry = *(CurLoop->block_begin());16041605// step 1: Check if the loop-back branch is in desirable form.1606if (Value *T = matchShiftULTCondition(1607dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry,1608Threshold))1609DefX = dyn_cast<Instruction>(T);1610else1611return false;16121613// step 2: Check the recurrence of variable X1614if (!DefX || !isa<PHINode>(DefX))1615return false;16161617PHINode *VarPhi = cast<PHINode>(DefX);1618int Idx = VarPhi->getBasicBlockIndex(LoopEntry);1619if (Idx == -1)1620return false;16211622DefX = dyn_cast<Instruction>(VarPhi->getIncomingValue(Idx));1623if (!DefX || DefX->getNumOperands() == 0 || DefX->getOperand(0) != VarPhi)1624return false;16251626// step 3: detect instructions corresponding to "x.next = x >> 1"1627if (DefX->getOpcode() != Instruction::LShr)1628return false;16291630IntrinID = Intrinsic::ctlz;1631ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));1632if (!Shft || !Shft->isOne())1633return false;16341635InitX = VarPhi->getIncomingValueForBlock(CurLoop->getLoopPreheader());16361637// step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 11638// or cnt.next = cnt + -1.1639// TODO: We can skip the step. If loop trip count is known (CTLZ),1640// then all uses of "cnt.next" could be optimized to the trip count1641// plus "cnt0". Currently it is not optimized.1642// This step could be used to detect POPCNT instruction:1643// cnt.next = cnt + (x.next & 1)1644for (Instruction &Inst : llvm::make_range(1645LoopEntry->getFirstNonPHI()->getIterator(), LoopEntry->end())) {1646if (Inst.getOpcode() != Instruction::Add)1647continue;16481649ConstantInt *Inc = dyn_cast<ConstantInt>(Inst.getOperand(1));1650if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))1651continue;16521653PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);1654if (!Phi)1655continue;16561657CntInst = &Inst;1658CntPhi = Phi;1659break;1660}1661if (!CntInst)1662return false;16631664return true;1665}16661667/// Return true iff the idiom is detected in the loop.1668///1669/// Additionally:1670/// 1) \p CntInst is set to the instruction counting the population bit.1671/// 2) \p CntPhi is set to the corresponding phi node.1672/// 3) \p Var is set to the value whose population bits are being counted.1673///1674/// The core idiom we are trying to detect is:1675/// \code1676/// if (x0 != 0)1677/// goto loop-exit // the precondition of the loop1678/// cnt0 = init-val;1679/// do {1680/// x1 = phi (x0, x2);1681/// cnt1 = phi(cnt0, cnt2);1682///1683/// cnt2 = cnt1 + 1;1684/// ...1685/// x2 = x1 & (x1 - 1);1686/// ...1687/// } while(x != 0);1688///1689/// loop-exit:1690/// \endcode1691static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB,1692Instruction *&CntInst, PHINode *&CntPhi,1693Value *&Var) {1694// step 1: Check to see if the look-back branch match this pattern:1695// "if (a!=0) goto loop-entry".1696BasicBlock *LoopEntry;1697Instruction *DefX2, *CountInst;1698Value *VarX1, *VarX0;1699PHINode *PhiX, *CountPhi;17001701DefX2 = CountInst = nullptr;1702VarX1 = VarX0 = nullptr;1703PhiX = CountPhi = nullptr;1704LoopEntry = *(CurLoop->block_begin());17051706// step 1: Check if the loop-back branch is in desirable form.1707{1708if (Value *T = matchCondition(1709dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))1710DefX2 = dyn_cast<Instruction>(T);1711else1712return false;1713}17141715// step 2: detect instructions corresponding to "x2 = x1 & (x1 - 1)"1716{1717if (!DefX2 || DefX2->getOpcode() != Instruction::And)1718return false;17191720BinaryOperator *SubOneOp;17211722if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(0))))1723VarX1 = DefX2->getOperand(1);1724else {1725VarX1 = DefX2->getOperand(0);1726SubOneOp = dyn_cast<BinaryOperator>(DefX2->getOperand(1));1727}1728if (!SubOneOp || SubOneOp->getOperand(0) != VarX1)1729return false;17301731ConstantInt *Dec = dyn_cast<ConstantInt>(SubOneOp->getOperand(1));1732if (!Dec ||1733!((SubOneOp->getOpcode() == Instruction::Sub && Dec->isOne()) ||1734(SubOneOp->getOpcode() == Instruction::Add &&1735Dec->isMinusOne()))) {1736return false;1737}1738}17391740// step 3: Check the recurrence of variable X1741PhiX = getRecurrenceVar(VarX1, DefX2, LoopEntry);1742if (!PhiX)1743return false;17441745// step 4: Find the instruction which count the population: cnt2 = cnt1 + 11746{1747CountInst = nullptr;1748for (Instruction &Inst : llvm::make_range(1749LoopEntry->getFirstNonPHI()->getIterator(), LoopEntry->end())) {1750if (Inst.getOpcode() != Instruction::Add)1751continue;17521753ConstantInt *Inc = dyn_cast<ConstantInt>(Inst.getOperand(1));1754if (!Inc || !Inc->isOne())1755continue;17561757PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);1758if (!Phi)1759continue;17601761// Check if the result of the instruction is live of the loop.1762bool LiveOutLoop = false;1763for (User *U : Inst.users()) {1764if ((cast<Instruction>(U))->getParent() != LoopEntry) {1765LiveOutLoop = true;1766break;1767}1768}17691770if (LiveOutLoop) {1771CountInst = &Inst;1772CountPhi = Phi;1773break;1774}1775}17761777if (!CountInst)1778return false;1779}17801781// step 5: check if the precondition is in this form:1782// "if (x != 0) goto loop-head ; else goto somewhere-we-don't-care;"1783{1784auto *PreCondBr = dyn_cast<BranchInst>(PreCondBB->getTerminator());1785Value *T = matchCondition(PreCondBr, CurLoop->getLoopPreheader());1786if (T != PhiX->getOperand(0) && T != PhiX->getOperand(1))1787return false;17881789CntInst = CountInst;1790CntPhi = CountPhi;1791Var = T;1792}17931794return true;1795}17961797/// Return true if the idiom is detected in the loop.1798///1799/// Additionally:1800/// 1) \p CntInst is set to the instruction Counting Leading Zeros (CTLZ)1801/// or nullptr if there is no such.1802/// 2) \p CntPhi is set to the corresponding phi node1803/// or nullptr if there is no such.1804/// 3) \p Var is set to the value whose CTLZ could be used.1805/// 4) \p DefX is set to the instruction calculating Loop exit condition.1806///1807/// The core idiom we are trying to detect is:1808/// \code1809/// if (x0 == 0)1810/// goto loop-exit // the precondition of the loop1811/// cnt0 = init-val;1812/// do {1813/// x = phi (x0, x.next); //PhiX1814/// cnt = phi(cnt0, cnt.next);1815///1816/// cnt.next = cnt + 1;1817/// ...1818/// x.next = x >> 1; // DefX1819/// ...1820/// } while(x.next != 0);1821///1822/// loop-exit:1823/// \endcode1824static bool detectShiftUntilZeroIdiom(Loop *CurLoop, const DataLayout &DL,1825Intrinsic::ID &IntrinID, Value *&InitX,1826Instruction *&CntInst, PHINode *&CntPhi,1827Instruction *&DefX) {1828BasicBlock *LoopEntry;1829Value *VarX = nullptr;18301831DefX = nullptr;1832CntInst = nullptr;1833CntPhi = nullptr;1834LoopEntry = *(CurLoop->block_begin());18351836// step 1: Check if the loop-back branch is in desirable form.1837if (Value *T = matchCondition(1838dyn_cast<BranchInst>(LoopEntry->getTerminator()), LoopEntry))1839DefX = dyn_cast<Instruction>(T);1840else1841return false;18421843// step 2: detect instructions corresponding to "x.next = x >> 1 or x << 1"1844if (!DefX || !DefX->isShift())1845return false;1846IntrinID = DefX->getOpcode() == Instruction::Shl ? Intrinsic::cttz :1847Intrinsic::ctlz;1848ConstantInt *Shft = dyn_cast<ConstantInt>(DefX->getOperand(1));1849if (!Shft || !Shft->isOne())1850return false;1851VarX = DefX->getOperand(0);18521853// step 3: Check the recurrence of variable X1854PHINode *PhiX = getRecurrenceVar(VarX, DefX, LoopEntry);1855if (!PhiX)1856return false;18571858InitX = PhiX->getIncomingValueForBlock(CurLoop->getLoopPreheader());18591860// Make sure the initial value can't be negative otherwise the ashr in the1861// loop might never reach zero which would make the loop infinite.1862if (DefX->getOpcode() == Instruction::AShr && !isKnownNonNegative(InitX, DL))1863return false;18641865// step 4: Find the instruction which count the CTLZ: cnt.next = cnt + 11866// or cnt.next = cnt + -1.1867// TODO: We can skip the step. If loop trip count is known (CTLZ),1868// then all uses of "cnt.next" could be optimized to the trip count1869// plus "cnt0". Currently it is not optimized.1870// This step could be used to detect POPCNT instruction:1871// cnt.next = cnt + (x.next & 1)1872for (Instruction &Inst : llvm::make_range(1873LoopEntry->getFirstNonPHI()->getIterator(), LoopEntry->end())) {1874if (Inst.getOpcode() != Instruction::Add)1875continue;18761877ConstantInt *Inc = dyn_cast<ConstantInt>(Inst.getOperand(1));1878if (!Inc || (!Inc->isOne() && !Inc->isMinusOne()))1879continue;18801881PHINode *Phi = getRecurrenceVar(Inst.getOperand(0), &Inst, LoopEntry);1882if (!Phi)1883continue;18841885CntInst = &Inst;1886CntPhi = Phi;1887break;1888}1889if (!CntInst)1890return false;18911892return true;1893}18941895// Check if CTLZ / CTTZ intrinsic is profitable. Assume it is always1896// profitable if we delete the loop.1897bool LoopIdiomRecognize::isProfitableToInsertFFS(Intrinsic::ID IntrinID,1898Value *InitX, bool ZeroCheck,1899size_t CanonicalSize) {1900const Value *Args[] = {InitX,1901ConstantInt::getBool(InitX->getContext(), ZeroCheck)};19021903// @llvm.dbg doesn't count as they have no semantic effect.1904auto InstWithoutDebugIt = CurLoop->getHeader()->instructionsWithoutDebug();1905uint32_t HeaderSize =1906std::distance(InstWithoutDebugIt.begin(), InstWithoutDebugIt.end());19071908IntrinsicCostAttributes Attrs(IntrinID, InitX->getType(), Args);1909InstructionCost Cost = TTI->getIntrinsicInstrCost(1910Attrs, TargetTransformInfo::TCK_SizeAndLatency);1911if (HeaderSize != CanonicalSize && Cost > TargetTransformInfo::TCC_Basic)1912return false;19131914return true;1915}19161917/// Convert CTLZ / CTTZ idiom loop into countable loop.1918/// If CTLZ / CTTZ inserted as a new trip count returns true; otherwise,1919/// returns false.1920bool LoopIdiomRecognize::insertFFSIfProfitable(Intrinsic::ID IntrinID,1921Value *InitX, Instruction *DefX,1922PHINode *CntPhi,1923Instruction *CntInst) {1924bool IsCntPhiUsedOutsideLoop = false;1925for (User *U : CntPhi->users())1926if (!CurLoop->contains(cast<Instruction>(U))) {1927IsCntPhiUsedOutsideLoop = true;1928break;1929}1930bool IsCntInstUsedOutsideLoop = false;1931for (User *U : CntInst->users())1932if (!CurLoop->contains(cast<Instruction>(U))) {1933IsCntInstUsedOutsideLoop = true;1934break;1935}1936// If both CntInst and CntPhi are used outside the loop the profitability1937// is questionable.1938if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)1939return false;19401941// For some CPUs result of CTLZ(X) intrinsic is undefined1942// when X is 0. If we can not guarantee X != 0, we need to check this1943// when expand.1944bool ZeroCheck = false;1945// It is safe to assume Preheader exist as it was checked in1946// parent function RunOnLoop.1947BasicBlock *PH = CurLoop->getLoopPreheader();19481949// If we are using the count instruction outside the loop, make sure we1950// have a zero check as a precondition. Without the check the loop would run1951// one iteration for before any check of the input value. This means 0 and 11952// would have identical behavior in the original loop and thus1953if (!IsCntPhiUsedOutsideLoop) {1954auto *PreCondBB = PH->getSinglePredecessor();1955if (!PreCondBB)1956return false;1957auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());1958if (!PreCondBI)1959return false;1960if (matchCondition(PreCondBI, PH) != InitX)1961return false;1962ZeroCheck = true;1963}19641965// FFS idiom loop has only 6 instructions:1966// %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]1967// %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]1968// %shr = ashr %n.addr.0, 11969// %tobool = icmp eq %shr, 01970// %inc = add nsw %i.0, 11971// br i1 %tobool1972size_t IdiomCanonicalSize = 6;1973if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))1974return false;19751976transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,1977DefX->getDebugLoc(), ZeroCheck,1978IsCntPhiUsedOutsideLoop);1979return true;1980}19811982/// Recognize CTLZ or CTTZ idiom in a non-countable loop and convert the loop1983/// to countable (with CTLZ / CTTZ trip count). If CTLZ / CTTZ inserted as a new1984/// trip count returns true; otherwise, returns false.1985bool LoopIdiomRecognize::recognizeAndInsertFFS() {1986// Give up if the loop has multiple blocks or multiple backedges.1987if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)1988return false;19891990Intrinsic::ID IntrinID;1991Value *InitX;1992Instruction *DefX = nullptr;1993PHINode *CntPhi = nullptr;1994Instruction *CntInst = nullptr;19951996if (!detectShiftUntilZeroIdiom(CurLoop, *DL, IntrinID, InitX, CntInst, CntPhi,1997DefX))1998return false;19992000return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);2001}20022003bool LoopIdiomRecognize::recognizeShiftUntilLessThan() {2004// Give up if the loop has multiple blocks or multiple backedges.2005if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)2006return false;20072008Intrinsic::ID IntrinID;2009Value *InitX;2010Instruction *DefX = nullptr;2011PHINode *CntPhi = nullptr;2012Instruction *CntInst = nullptr;20132014APInt LoopThreshold;2015if (!detectShiftUntilLessThanIdiom(CurLoop, *DL, IntrinID, InitX, CntInst,2016CntPhi, DefX, LoopThreshold))2017return false;20182019if (LoopThreshold == 2) {2020// Treat as regular FFS.2021return insertFFSIfProfitable(IntrinID, InitX, DefX, CntPhi, CntInst);2022}20232024// Look for Floor Log2 Idiom.2025if (LoopThreshold != 4)2026return false;20272028// Abort if CntPhi is used outside of the loop.2029for (User *U : CntPhi->users())2030if (!CurLoop->contains(cast<Instruction>(U)))2031return false;20322033// It is safe to assume Preheader exist as it was checked in2034// parent function RunOnLoop.2035BasicBlock *PH = CurLoop->getLoopPreheader();2036auto *PreCondBB = PH->getSinglePredecessor();2037if (!PreCondBB)2038return false;2039auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());2040if (!PreCondBI)2041return false;20422043APInt PreLoopThreshold;2044if (matchShiftULTCondition(PreCondBI, PH, PreLoopThreshold) != InitX ||2045PreLoopThreshold != 2)2046return false;20472048bool ZeroCheck = true;20492050// the loop has only 6 instructions:2051// %n.addr.0 = phi [ %n, %entry ], [ %shr, %while.cond ]2052// %i.0 = phi [ %i0, %entry ], [ %inc, %while.cond ]2053// %shr = ashr %n.addr.0, 12054// %tobool = icmp ult %n.addr.0, C2055// %inc = add nsw %i.0, 12056// br i1 %tobool2057size_t IdiomCanonicalSize = 6;2058if (!isProfitableToInsertFFS(IntrinID, InitX, ZeroCheck, IdiomCanonicalSize))2059return false;20602061// log2(x) = w − 1 − clz(x)2062transformLoopToCountable(IntrinID, PH, CntInst, CntPhi, InitX, DefX,2063DefX->getDebugLoc(), ZeroCheck,2064/*IsCntPhiUsedOutsideLoop=*/false,2065/*InsertSub=*/true);2066return true;2067}20682069/// Recognizes a population count idiom in a non-countable loop.2070///2071/// If detected, transforms the relevant code to issue the popcount intrinsic2072/// function call, and returns true; otherwise, returns false.2073bool LoopIdiomRecognize::recognizePopcount() {2074if (TTI->getPopcntSupport(32) != TargetTransformInfo::PSK_FastHardware)2075return false;20762077// Counting population are usually conducted by few arithmetic instructions.2078// Such instructions can be easily "absorbed" by vacant slots in a2079// non-compact loop. Therefore, recognizing popcount idiom only makes sense2080// in a compact loop.20812082// Give up if the loop has multiple blocks or multiple backedges.2083if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)2084return false;20852086BasicBlock *LoopBody = *(CurLoop->block_begin());2087if (LoopBody->size() >= 20) {2088// The loop is too big, bail out.2089return false;2090}20912092// It should have a preheader containing nothing but an unconditional branch.2093BasicBlock *PH = CurLoop->getLoopPreheader();2094if (!PH || &PH->front() != PH->getTerminator())2095return false;2096auto *EntryBI = dyn_cast<BranchInst>(PH->getTerminator());2097if (!EntryBI || EntryBI->isConditional())2098return false;20992100// It should have a precondition block where the generated popcount intrinsic2101// function can be inserted.2102auto *PreCondBB = PH->getSinglePredecessor();2103if (!PreCondBB)2104return false;2105auto *PreCondBI = dyn_cast<BranchInst>(PreCondBB->getTerminator());2106if (!PreCondBI || PreCondBI->isUnconditional())2107return false;21082109Instruction *CntInst;2110PHINode *CntPhi;2111Value *Val;2112if (!detectPopcountIdiom(CurLoop, PreCondBB, CntInst, CntPhi, Val))2113return false;21142115transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);2116return true;2117}21182119static CallInst *createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val,2120const DebugLoc &DL) {2121Value *Ops[] = {Val};2122Type *Tys[] = {Val->getType()};21232124Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();2125Function *Func = Intrinsic::getDeclaration(M, Intrinsic::ctpop, Tys);2126CallInst *CI = IRBuilder.CreateCall(Func, Ops);2127CI->setDebugLoc(DL);21282129return CI;2130}21312132static CallInst *createFFSIntrinsic(IRBuilder<> &IRBuilder, Value *Val,2133const DebugLoc &DL, bool ZeroCheck,2134Intrinsic::ID IID) {2135Value *Ops[] = {Val, IRBuilder.getInt1(ZeroCheck)};2136Type *Tys[] = {Val->getType()};21372138Module *M = IRBuilder.GetInsertBlock()->getParent()->getParent();2139Function *Func = Intrinsic::getDeclaration(M, IID, Tys);2140CallInst *CI = IRBuilder.CreateCall(Func, Ops);2141CI->setDebugLoc(DL);21422143return CI;2144}21452146/// Transform the following loop (Using CTLZ, CTTZ is similar):2147/// loop:2148/// CntPhi = PHI [Cnt0, CntInst]2149/// PhiX = PHI [InitX, DefX]2150/// CntInst = CntPhi + 12151/// DefX = PhiX >> 12152/// LOOP_BODY2153/// Br: loop if (DefX != 0)2154/// Use(CntPhi) or Use(CntInst)2155///2156/// Into:2157/// If CntPhi used outside the loop:2158/// CountPrev = BitWidth(InitX) - CTLZ(InitX >> 1)2159/// Count = CountPrev + 12160/// else2161/// Count = BitWidth(InitX) - CTLZ(InitX)2162/// loop:2163/// CntPhi = PHI [Cnt0, CntInst]2164/// PhiX = PHI [InitX, DefX]2165/// PhiCount = PHI [Count, Dec]2166/// CntInst = CntPhi + 12167/// DefX = PhiX >> 12168/// Dec = PhiCount - 12169/// LOOP_BODY2170/// Br: loop if (Dec != 0)2171/// Use(CountPrev + Cnt0) // Use(CntPhi)2172/// or2173/// Use(Count + Cnt0) // Use(CntInst)2174///2175/// If LOOP_BODY is empty the loop will be deleted.2176/// If CntInst and DefX are not used in LOOP_BODY they will be removed.2177void LoopIdiomRecognize::transformLoopToCountable(2178Intrinsic::ID IntrinID, BasicBlock *Preheader, Instruction *CntInst,2179PHINode *CntPhi, Value *InitX, Instruction *DefX, const DebugLoc &DL,2180bool ZeroCheck, bool IsCntPhiUsedOutsideLoop, bool InsertSub) {2181BranchInst *PreheaderBr = cast<BranchInst>(Preheader->getTerminator());21822183// Step 1: Insert the CTLZ/CTTZ instruction at the end of the preheader block2184IRBuilder<> Builder(PreheaderBr);2185Builder.SetCurrentDebugLocation(DL);21862187// If there are no uses of CntPhi crate:2188// Count = BitWidth - CTLZ(InitX);2189// NewCount = Count;2190// If there are uses of CntPhi create:2191// NewCount = BitWidth - CTLZ(InitX >> 1);2192// Count = NewCount + 1;2193Value *InitXNext;2194if (IsCntPhiUsedOutsideLoop) {2195if (DefX->getOpcode() == Instruction::AShr)2196InitXNext = Builder.CreateAShr(InitX, 1);2197else if (DefX->getOpcode() == Instruction::LShr)2198InitXNext = Builder.CreateLShr(InitX, 1);2199else if (DefX->getOpcode() == Instruction::Shl) // cttz2200InitXNext = Builder.CreateShl(InitX, 1);2201else2202llvm_unreachable("Unexpected opcode!");2203} else2204InitXNext = InitX;2205Value *Count =2206createFFSIntrinsic(Builder, InitXNext, DL, ZeroCheck, IntrinID);2207Type *CountTy = Count->getType();2208Count = Builder.CreateSub(2209ConstantInt::get(CountTy, CountTy->getIntegerBitWidth()), Count);2210if (InsertSub)2211Count = Builder.CreateSub(Count, ConstantInt::get(CountTy, 1));2212Value *NewCount = Count;2213if (IsCntPhiUsedOutsideLoop)2214Count = Builder.CreateAdd(Count, ConstantInt::get(CountTy, 1));22152216NewCount = Builder.CreateZExtOrTrunc(NewCount, CntInst->getType());22172218Value *CntInitVal = CntPhi->getIncomingValueForBlock(Preheader);2219if (cast<ConstantInt>(CntInst->getOperand(1))->isOne()) {2220// If the counter was being incremented in the loop, add NewCount to the2221// counter's initial value, but only if the initial value is not zero.2222ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);2223if (!InitConst || !InitConst->isZero())2224NewCount = Builder.CreateAdd(NewCount, CntInitVal);2225} else {2226// If the count was being decremented in the loop, subtract NewCount from2227// the counter's initial value.2228NewCount = Builder.CreateSub(CntInitVal, NewCount);2229}22302231// Step 2: Insert new IV and loop condition:2232// loop:2233// ...2234// PhiCount = PHI [Count, Dec]2235// ...2236// Dec = PhiCount - 12237// ...2238// Br: loop if (Dec != 0)2239BasicBlock *Body = *(CurLoop->block_begin());2240auto *LbBr = cast<BranchInst>(Body->getTerminator());2241ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());22422243PHINode *TcPhi = PHINode::Create(CountTy, 2, "tcphi");2244TcPhi->insertBefore(Body->begin());22452246Builder.SetInsertPoint(LbCond);2247Instruction *TcDec = cast<Instruction>(Builder.CreateSub(2248TcPhi, ConstantInt::get(CountTy, 1), "tcdec", false, true));22492250TcPhi->addIncoming(Count, Preheader);2251TcPhi->addIncoming(TcDec, Body);22522253CmpInst::Predicate Pred =2254(LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;2255LbCond->setPredicate(Pred);2256LbCond->setOperand(0, TcDec);2257LbCond->setOperand(1, ConstantInt::get(CountTy, 0));22582259// Step 3: All the references to the original counter outside2260// the loop are replaced with the NewCount2261if (IsCntPhiUsedOutsideLoop)2262CntPhi->replaceUsesOutsideBlock(NewCount, Body);2263else2264CntInst->replaceUsesOutsideBlock(NewCount, Body);22652266// step 4: Forget the "non-computable" trip-count SCEV associated with the2267// loop. The loop would otherwise not be deleted even if it becomes empty.2268SE->forgetLoop(CurLoop);2269}22702271void LoopIdiomRecognize::transformLoopToPopcount(BasicBlock *PreCondBB,2272Instruction *CntInst,2273PHINode *CntPhi, Value *Var) {2274BasicBlock *PreHead = CurLoop->getLoopPreheader();2275auto *PreCondBr = cast<BranchInst>(PreCondBB->getTerminator());2276const DebugLoc &DL = CntInst->getDebugLoc();22772278// Assuming before transformation, the loop is following:2279// if (x) // the precondition2280// do { cnt++; x &= x - 1; } while(x);22812282// Step 1: Insert the ctpop instruction at the end of the precondition block2283IRBuilder<> Builder(PreCondBr);2284Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;2285{2286PopCnt = createPopcntIntrinsic(Builder, Var, DL);2287NewCount = PopCntZext =2288Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->getType()));22892290if (NewCount != PopCnt)2291(cast<Instruction>(NewCount))->setDebugLoc(DL);22922293// TripCnt is exactly the number of iterations the loop has2294TripCnt = NewCount;22952296// If the population counter's initial value is not zero, insert Add Inst.2297Value *CntInitVal = CntPhi->getIncomingValueForBlock(PreHead);2298ConstantInt *InitConst = dyn_cast<ConstantInt>(CntInitVal);2299if (!InitConst || !InitConst->isZero()) {2300NewCount = Builder.CreateAdd(NewCount, CntInitVal);2301(cast<Instruction>(NewCount))->setDebugLoc(DL);2302}2303}23042305// Step 2: Replace the precondition from "if (x == 0) goto loop-exit" to2306// "if (NewCount == 0) loop-exit". Without this change, the intrinsic2307// function would be partial dead code, and downstream passes will drag2308// it back from the precondition block to the preheader.2309{2310ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());23112312Value *Opnd0 = PopCntZext;2313Value *Opnd1 = ConstantInt::get(PopCntZext->getType(), 0);2314if (PreCond->getOperand(0) != Var)2315std::swap(Opnd0, Opnd1);23162317ICmpInst *NewPreCond = cast<ICmpInst>(2318Builder.CreateICmp(PreCond->getPredicate(), Opnd0, Opnd1));2319PreCondBr->setCondition(NewPreCond);23202321RecursivelyDeleteTriviallyDeadInstructions(PreCond, TLI);2322}23232324// Step 3: Note that the population count is exactly the trip count of the2325// loop in question, which enable us to convert the loop from noncountable2326// loop into a countable one. The benefit is twofold:2327//2328// - If the loop only counts population, the entire loop becomes dead after2329// the transformation. It is a lot easier to prove a countable loop dead2330// than to prove a noncountable one. (In some C dialects, an infinite loop2331// isn't dead even if it computes nothing useful. In general, DCE needs2332// to prove a noncountable loop finite before safely delete it.)2333//2334// - If the loop also performs something else, it remains alive.2335// Since it is transformed to countable form, it can be aggressively2336// optimized by some optimizations which are in general not applicable2337// to a noncountable loop.2338//2339// After this step, this loop (conceptually) would look like following:2340// newcnt = __builtin_ctpop(x);2341// t = newcnt;2342// if (x)2343// do { cnt++; x &= x-1; t--) } while (t > 0);2344BasicBlock *Body = *(CurLoop->block_begin());2345{2346auto *LbBr = cast<BranchInst>(Body->getTerminator());2347ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());2348Type *Ty = TripCnt->getType();23492350PHINode *TcPhi = PHINode::Create(Ty, 2, "tcphi");2351TcPhi->insertBefore(Body->begin());23522353Builder.SetInsertPoint(LbCond);2354Instruction *TcDec = cast<Instruction>(2355Builder.CreateSub(TcPhi, ConstantInt::get(Ty, 1),2356"tcdec", false, true));23572358TcPhi->addIncoming(TripCnt, PreHead);2359TcPhi->addIncoming(TcDec, Body);23602361CmpInst::Predicate Pred =2362(LbBr->getSuccessor(0) == Body) ? CmpInst::ICMP_UGT : CmpInst::ICMP_SLE;2363LbCond->setPredicate(Pred);2364LbCond->setOperand(0, TcDec);2365LbCond->setOperand(1, ConstantInt::get(Ty, 0));2366}23672368// Step 4: All the references to the original population counter outside2369// the loop are replaced with the NewCount -- the value returned from2370// __builtin_ctpop().2371CntInst->replaceUsesOutsideBlock(NewCount, Body);23722373// step 5: Forget the "non-computable" trip-count SCEV associated with the2374// loop. The loop would otherwise not be deleted even if it becomes empty.2375SE->forgetLoop(CurLoop);2376}23772378/// Match loop-invariant value.2379template <typename SubPattern_t> struct match_LoopInvariant {2380SubPattern_t SubPattern;2381const Loop *L;23822383match_LoopInvariant(const SubPattern_t &SP, const Loop *L)2384: SubPattern(SP), L(L) {}23852386template <typename ITy> bool match(ITy *V) {2387return L->isLoopInvariant(V) && SubPattern.match(V);2388}2389};23902391/// Matches if the value is loop-invariant.2392template <typename Ty>2393inline match_LoopInvariant<Ty> m_LoopInvariant(const Ty &M, const Loop *L) {2394return match_LoopInvariant<Ty>(M, L);2395}23962397/// Return true if the idiom is detected in the loop.2398///2399/// The core idiom we are trying to detect is:2400/// \code2401/// entry:2402/// <...>2403/// %bitmask = shl i32 1, %bitpos2404/// br label %loop2405///2406/// loop:2407/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]2408/// %x.curr.bitmasked = and i32 %x.curr, %bitmask2409/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 02410/// %x.next = shl i32 %x.curr, 12411/// <...>2412/// br i1 %x.curr.isbitunset, label %loop, label %end2413///2414/// end:2415/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>2416/// %x.next.res = phi i32 [ %x.next, %loop ] <...>2417/// <...>2418/// \endcode2419static bool detectShiftUntilBitTestIdiom(Loop *CurLoop, Value *&BaseX,2420Value *&BitMask, Value *&BitPos,2421Value *&CurrX, Instruction *&NextX) {2422LLVM_DEBUG(dbgs() << DEBUG_TYPE2423" Performing shift-until-bittest idiom detection.\n");24242425// Give up if the loop has multiple blocks or multiple backedges.2426if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {2427LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");2428return false;2429}24302431BasicBlock *LoopHeaderBB = CurLoop->getHeader();2432BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();2433assert(LoopPreheaderBB && "There is always a loop preheader.");24342435using namespace PatternMatch;24362437// Step 1: Check if the loop backedge is in desirable form.24382439ICmpInst::Predicate Pred;2440Value *CmpLHS, *CmpRHS;2441BasicBlock *TrueBB, *FalseBB;2442if (!match(LoopHeaderBB->getTerminator(),2443m_Br(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),2444m_BasicBlock(TrueBB), m_BasicBlock(FalseBB)))) {2445LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");2446return false;2447}24482449// Step 2: Check if the backedge's condition is in desirable form.24502451auto MatchVariableBitMask = [&]() {2452return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&2453match(CmpLHS,2454m_c_And(m_Value(CurrX),2455m_CombineAnd(2456m_Value(BitMask),2457m_LoopInvariant(m_Shl(m_One(), m_Value(BitPos)),2458CurLoop))));2459};2460auto MatchConstantBitMask = [&]() {2461return ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero()) &&2462match(CmpLHS, m_And(m_Value(CurrX),2463m_CombineAnd(m_Value(BitMask), m_Power2()))) &&2464(BitPos = ConstantExpr::getExactLogBase2(cast<Constant>(BitMask)));2465};2466auto MatchDecomposableConstantBitMask = [&]() {2467APInt Mask;2468return llvm::decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, CurrX, Mask) &&2469ICmpInst::isEquality(Pred) && Mask.isPowerOf2() &&2470(BitMask = ConstantInt::get(CurrX->getType(), Mask)) &&2471(BitPos = ConstantInt::get(CurrX->getType(), Mask.logBase2()));2472};24732474if (!MatchVariableBitMask() && !MatchConstantBitMask() &&2475!MatchDecomposableConstantBitMask()) {2476LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge comparison.\n");2477return false;2478}24792480// Step 3: Check if the recurrence is in desirable form.2481auto *CurrXPN = dyn_cast<PHINode>(CurrX);2482if (!CurrXPN || CurrXPN->getParent() != LoopHeaderBB) {2483LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");2484return false;2485}24862487BaseX = CurrXPN->getIncomingValueForBlock(LoopPreheaderBB);2488NextX =2489dyn_cast<Instruction>(CurrXPN->getIncomingValueForBlock(LoopHeaderBB));24902491assert(CurLoop->isLoopInvariant(BaseX) &&2492"Expected BaseX to be avaliable in the preheader!");24932494if (!NextX || !match(NextX, m_Shl(m_Specific(CurrX), m_One()))) {2495// FIXME: support right-shift?2496LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");2497return false;2498}24992500// Step 4: Check if the backedge's destinations are in desirable form.25012502assert(ICmpInst::isEquality(Pred) &&2503"Should only get equality predicates here.");25042505// cmp-br is commutative, so canonicalize to a single variant.2506if (Pred != ICmpInst::Predicate::ICMP_EQ) {2507Pred = ICmpInst::getInversePredicate(Pred);2508std::swap(TrueBB, FalseBB);2509}25102511// We expect to exit loop when comparison yields false,2512// so when it yields true we should branch back to loop header.2513if (TrueBB != LoopHeaderBB) {2514LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");2515return false;2516}25172518// Okay, idiom checks out.2519return true;2520}25212522/// Look for the following loop:2523/// \code2524/// entry:2525/// <...>2526/// %bitmask = shl i32 1, %bitpos2527/// br label %loop2528///2529/// loop:2530/// %x.curr = phi i32 [ %x, %entry ], [ %x.next, %loop ]2531/// %x.curr.bitmasked = and i32 %x.curr, %bitmask2532/// %x.curr.isbitunset = icmp eq i32 %x.curr.bitmasked, 02533/// %x.next = shl i32 %x.curr, 12534/// <...>2535/// br i1 %x.curr.isbitunset, label %loop, label %end2536///2537/// end:2538/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>2539/// %x.next.res = phi i32 [ %x.next, %loop ] <...>2540/// <...>2541/// \endcode2542///2543/// And transform it into:2544/// \code2545/// entry:2546/// %bitmask = shl i32 1, %bitpos2547/// %lowbitmask = add i32 %bitmask, -12548/// %mask = or i32 %lowbitmask, %bitmask2549/// %x.masked = and i32 %x, %mask2550/// %x.masked.numleadingzeros = call i32 @llvm.ctlz.i32(i32 %x.masked,2551/// i1 true)2552/// %x.masked.numactivebits = sub i32 32, %x.masked.numleadingzeros2553/// %x.masked.leadingonepos = add i32 %x.masked.numactivebits, -12554/// %backedgetakencount = sub i32 %bitpos, %x.masked.leadingonepos2555/// %tripcount = add i32 %backedgetakencount, 12556/// %x.curr = shl i32 %x, %backedgetakencount2557/// %x.next = shl i32 %x, %tripcount2558/// br label %loop2559///2560/// loop:2561/// %loop.iv = phi i32 [ 0, %entry ], [ %loop.iv.next, %loop ]2562/// %loop.iv.next = add nuw i32 %loop.iv, 12563/// %loop.ivcheck = icmp eq i32 %loop.iv.next, %tripcount2564/// <...>2565/// br i1 %loop.ivcheck, label %end, label %loop2566///2567/// end:2568/// %x.curr.res = phi i32 [ %x.curr, %loop ] <...>2569/// %x.next.res = phi i32 [ %x.next, %loop ] <...>2570/// <...>2571/// \endcode2572bool LoopIdiomRecognize::recognizeShiftUntilBitTest() {2573bool MadeChange = false;25742575Value *X, *BitMask, *BitPos, *XCurr;2576Instruction *XNext;2577if (!detectShiftUntilBitTestIdiom(CurLoop, X, BitMask, BitPos, XCurr,2578XNext)) {2579LLVM_DEBUG(dbgs() << DEBUG_TYPE2580" shift-until-bittest idiom detection failed.\n");2581return MadeChange;2582}2583LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom detected!\n");25842585// Ok, it is the idiom we were looking for, we *could* transform this loop,2586// but is it profitable to transform?25872588BasicBlock *LoopHeaderBB = CurLoop->getHeader();2589BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();2590assert(LoopPreheaderBB && "There is always a loop preheader.");25912592BasicBlock *SuccessorBB = CurLoop->getExitBlock();2593assert(SuccessorBB && "There is only a single successor.");25942595IRBuilder<> Builder(LoopPreheaderBB->getTerminator());2596Builder.SetCurrentDebugLocation(cast<Instruction>(XCurr)->getDebugLoc());25972598Intrinsic::ID IntrID = Intrinsic::ctlz;2599Type *Ty = X->getType();2600unsigned Bitwidth = Ty->getScalarSizeInBits();26012602TargetTransformInfo::TargetCostKind CostKind =2603TargetTransformInfo::TCK_SizeAndLatency;26042605// The rewrite is considered to be unprofitable iff and only iff the2606// intrinsic/shift we'll use are not cheap. Note that we are okay with *just*2607// making the loop countable, even if nothing else changes.2608IntrinsicCostAttributes Attrs(2609IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getTrue()});2610InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);2611if (Cost > TargetTransformInfo::TCC_Basic) {2612LLVM_DEBUG(dbgs() << DEBUG_TYPE2613" Intrinsic is too costly, not beneficial\n");2614return MadeChange;2615}2616if (TTI->getArithmeticInstrCost(Instruction::Shl, Ty, CostKind) >2617TargetTransformInfo::TCC_Basic) {2618LLVM_DEBUG(dbgs() << DEBUG_TYPE " Shift is too costly, not beneficial\n");2619return MadeChange;2620}26212622// Ok, transform appears worthwhile.2623MadeChange = true;26242625if (!isGuaranteedNotToBeUndefOrPoison(BitPos)) {2626// BitMask may be computed from BitPos, Freeze BitPos so we can increase2627// it's use count.2628std::optional<BasicBlock::iterator> InsertPt = std::nullopt;2629if (auto *BitPosI = dyn_cast<Instruction>(BitPos))2630InsertPt = BitPosI->getInsertionPointAfterDef();2631else2632InsertPt = DT->getRoot()->getFirstNonPHIOrDbgOrAlloca();2633if (!InsertPt)2634return false;2635FreezeInst *BitPosFrozen =2636new FreezeInst(BitPos, BitPos->getName() + ".fr", *InsertPt);2637BitPos->replaceUsesWithIf(BitPosFrozen, [BitPosFrozen](Use &U) {2638return U.getUser() != BitPosFrozen;2639});2640BitPos = BitPosFrozen;2641}26422643// Step 1: Compute the loop trip count.26442645Value *LowBitMask = Builder.CreateAdd(BitMask, Constant::getAllOnesValue(Ty),2646BitPos->getName() + ".lowbitmask");2647Value *Mask =2648Builder.CreateOr(LowBitMask, BitMask, BitPos->getName() + ".mask");2649Value *XMasked = Builder.CreateAnd(X, Mask, X->getName() + ".masked");2650CallInst *XMaskedNumLeadingZeros = Builder.CreateIntrinsic(2651IntrID, Ty, {XMasked, /*is_zero_poison=*/Builder.getTrue()},2652/*FMFSource=*/nullptr, XMasked->getName() + ".numleadingzeros");2653Value *XMaskedNumActiveBits = Builder.CreateSub(2654ConstantInt::get(Ty, Ty->getScalarSizeInBits()), XMaskedNumLeadingZeros,2655XMasked->getName() + ".numactivebits", /*HasNUW=*/true,2656/*HasNSW=*/Bitwidth != 2);2657Value *XMaskedLeadingOnePos =2658Builder.CreateAdd(XMaskedNumActiveBits, Constant::getAllOnesValue(Ty),2659XMasked->getName() + ".leadingonepos", /*HasNUW=*/false,2660/*HasNSW=*/Bitwidth > 2);26612662Value *LoopBackedgeTakenCount = Builder.CreateSub(2663BitPos, XMaskedLeadingOnePos, CurLoop->getName() + ".backedgetakencount",2664/*HasNUW=*/true, /*HasNSW=*/true);2665// We know loop's backedge-taken count, but what's loop's trip count?2666// Note that while NUW is always safe, while NSW is only for bitwidths != 2.2667Value *LoopTripCount =2668Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),2669CurLoop->getName() + ".tripcount", /*HasNUW=*/true,2670/*HasNSW=*/Bitwidth != 2);26712672// Step 2: Compute the recurrence's final value without a loop.26732674// NewX is always safe to compute, because `LoopBackedgeTakenCount`2675// will always be smaller than `bitwidth(X)`, i.e. we never get poison.2676Value *NewX = Builder.CreateShl(X, LoopBackedgeTakenCount);2677NewX->takeName(XCurr);2678if (auto *I = dyn_cast<Instruction>(NewX))2679I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);26802681Value *NewXNext;2682// Rewriting XNext is more complicated, however, because `X << LoopTripCount`2683// will be poison iff `LoopTripCount == bitwidth(X)` (which will happen2684// iff `BitPos` is `bitwidth(x) - 1` and `X` is `1`). So unless we know2685// that isn't the case, we'll need to emit an alternative, safe IR.2686if (XNext->hasNoSignedWrap() || XNext->hasNoUnsignedWrap() ||2687PatternMatch::match(2688BitPos, PatternMatch::m_SpecificInt_ICMP(2689ICmpInst::ICMP_NE, APInt(Ty->getScalarSizeInBits(),2690Ty->getScalarSizeInBits() - 1))))2691NewXNext = Builder.CreateShl(X, LoopTripCount);2692else {2693// Otherwise, just additionally shift by one. It's the smallest solution,2694// alternatively, we could check that NewX is INT_MIN (or BitPos is )2695// and select 0 instead.2696NewXNext = Builder.CreateShl(NewX, ConstantInt::get(Ty, 1));2697}26982699NewXNext->takeName(XNext);2700if (auto *I = dyn_cast<Instruction>(NewXNext))2701I->copyIRFlags(XNext, /*IncludeWrapFlags=*/true);27022703// Step 3: Adjust the successor basic block to recieve the computed2704// recurrence's final value instead of the recurrence itself.27052706XCurr->replaceUsesOutsideBlock(NewX, LoopHeaderBB);2707XNext->replaceUsesOutsideBlock(NewXNext, LoopHeaderBB);27082709// Step 4: Rewrite the loop into a countable form, with canonical IV.27102711// The new canonical induction variable.2712Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->begin());2713auto *IV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");27142715// The induction itself.2716// Note that while NUW is always safe, while NSW is only for bitwidths != 2.2717Builder.SetInsertPoint(LoopHeaderBB->getTerminator());2718auto *IVNext =2719Builder.CreateAdd(IV, ConstantInt::get(Ty, 1), IV->getName() + ".next",2720/*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);27212722// The loop trip count check.2723auto *IVCheck = Builder.CreateICmpEQ(IVNext, LoopTripCount,2724CurLoop->getName() + ".ivcheck");2725Builder.CreateCondBr(IVCheck, SuccessorBB, LoopHeaderBB);2726LoopHeaderBB->getTerminator()->eraseFromParent();27272728// Populate the IV PHI.2729IV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);2730IV->addIncoming(IVNext, LoopHeaderBB);27312732// Step 5: Forget the "non-computable" trip-count SCEV associated with the2733// loop. The loop would otherwise not be deleted even if it becomes empty.27342735SE->forgetLoop(CurLoop);27362737// Other passes will take care of actually deleting the loop if possible.27382739LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-bittest idiom optimized!\n");27402741++NumShiftUntilBitTest;2742return MadeChange;2743}27442745/// Return true if the idiom is detected in the loop.2746///2747/// The core idiom we are trying to detect is:2748/// \code2749/// entry:2750/// <...>2751/// %start = <...>2752/// %extraoffset = <...>2753/// <...>2754/// br label %for.cond2755///2756/// loop:2757/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]2758/// %nbits = add nsw i8 %iv, %extraoffset2759/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits2760/// %val.shifted.iszero = icmp eq i8 %val.shifted, 02761/// %iv.next = add i8 %iv, 12762/// <...>2763/// br i1 %val.shifted.iszero, label %end, label %loop2764///2765/// end:2766/// %iv.res = phi i8 [ %iv, %loop ] <...>2767/// %nbits.res = phi i8 [ %nbits, %loop ] <...>2768/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>2769/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>2770/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>2771/// <...>2772/// \endcode2773static bool detectShiftUntilZeroIdiom(Loop *CurLoop, ScalarEvolution *SE,2774Instruction *&ValShiftedIsZero,2775Intrinsic::ID &IntrinID, Instruction *&IV,2776Value *&Start, Value *&Val,2777const SCEV *&ExtraOffsetExpr,2778bool &InvertedCond) {2779LLVM_DEBUG(dbgs() << DEBUG_TYPE2780" Performing shift-until-zero idiom detection.\n");27812782// Give up if the loop has multiple blocks or multiple backedges.2783if (CurLoop->getNumBlocks() != 1 || CurLoop->getNumBackEdges() != 1) {2784LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad block/backedge count.\n");2785return false;2786}27872788Instruction *ValShifted, *NBits, *IVNext;2789Value *ExtraOffset;27902791BasicBlock *LoopHeaderBB = CurLoop->getHeader();2792BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();2793assert(LoopPreheaderBB && "There is always a loop preheader.");27942795using namespace PatternMatch;27962797// Step 1: Check if the loop backedge, condition is in desirable form.27982799ICmpInst::Predicate Pred;2800BasicBlock *TrueBB, *FalseBB;2801if (!match(LoopHeaderBB->getTerminator(),2802m_Br(m_Instruction(ValShiftedIsZero), m_BasicBlock(TrueBB),2803m_BasicBlock(FalseBB))) ||2804!match(ValShiftedIsZero,2805m_ICmp(Pred, m_Instruction(ValShifted), m_Zero())) ||2806!ICmpInst::isEquality(Pred)) {2807LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge structure.\n");2808return false;2809}28102811// Step 2: Check if the comparison's operand is in desirable form.2812// FIXME: Val could be a one-input PHI node, which we should look past.2813if (!match(ValShifted, m_Shift(m_LoopInvariant(m_Value(Val), CurLoop),2814m_Instruction(NBits)))) {2815LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad comparisons value computation.\n");2816return false;2817}2818IntrinID = ValShifted->getOpcode() == Instruction::Shl ? Intrinsic::cttz2819: Intrinsic::ctlz;28202821// Step 3: Check if the shift amount is in desirable form.28222823if (match(NBits, m_c_Add(m_Instruction(IV),2824m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&2825(NBits->hasNoSignedWrap() || NBits->hasNoUnsignedWrap()))2826ExtraOffsetExpr = SE->getNegativeSCEV(SE->getSCEV(ExtraOffset));2827else if (match(NBits,2828m_Sub(m_Instruction(IV),2829m_LoopInvariant(m_Value(ExtraOffset), CurLoop))) &&2830NBits->hasNoSignedWrap())2831ExtraOffsetExpr = SE->getSCEV(ExtraOffset);2832else {2833IV = NBits;2834ExtraOffsetExpr = SE->getZero(NBits->getType());2835}28362837// Step 4: Check if the recurrence is in desirable form.2838auto *IVPN = dyn_cast<PHINode>(IV);2839if (!IVPN || IVPN->getParent() != LoopHeaderBB) {2840LLVM_DEBUG(dbgs() << DEBUG_TYPE " Not an expected PHI node.\n");2841return false;2842}28432844Start = IVPN->getIncomingValueForBlock(LoopPreheaderBB);2845IVNext = dyn_cast<Instruction>(IVPN->getIncomingValueForBlock(LoopHeaderBB));28462847if (!IVNext || !match(IVNext, m_Add(m_Specific(IVPN), m_One()))) {2848LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad recurrence.\n");2849return false;2850}28512852// Step 4: Check if the backedge's destinations are in desirable form.28532854assert(ICmpInst::isEquality(Pred) &&2855"Should only get equality predicates here.");28562857// cmp-br is commutative, so canonicalize to a single variant.2858InvertedCond = Pred != ICmpInst::Predicate::ICMP_EQ;2859if (InvertedCond) {2860Pred = ICmpInst::getInversePredicate(Pred);2861std::swap(TrueBB, FalseBB);2862}28632864// We expect to exit loop when comparison yields true,2865// so when it yields false we should branch back to loop header.2866if (FalseBB != LoopHeaderBB) {2867LLVM_DEBUG(dbgs() << DEBUG_TYPE " Bad backedge flow.\n");2868return false;2869}28702871// The new, countable, loop will certainly only run a known number of2872// iterations, It won't be infinite. But the old loop might be infinite2873// under certain conditions. For logical shifts, the value will become zero2874// after at most bitwidth(%Val) loop iterations. However, for arithmetic2875// right-shift, iff the sign bit was set, the value will never become zero,2876// and the loop may never finish.2877if (ValShifted->getOpcode() == Instruction::AShr &&2878!isMustProgress(CurLoop) && !SE->isKnownNonNegative(SE->getSCEV(Val))) {2879LLVM_DEBUG(dbgs() << DEBUG_TYPE " Can not prove the loop is finite.\n");2880return false;2881}28822883// Okay, idiom checks out.2884return true;2885}28862887/// Look for the following loop:2888/// \code2889/// entry:2890/// <...>2891/// %start = <...>2892/// %extraoffset = <...>2893/// <...>2894/// br label %for.cond2895///2896/// loop:2897/// %iv = phi i8 [ %start, %entry ], [ %iv.next, %for.cond ]2898/// %nbits = add nsw i8 %iv, %extraoffset2899/// %val.shifted = {{l,a}shr,shl} i8 %val, %nbits2900/// %val.shifted.iszero = icmp eq i8 %val.shifted, 02901/// %iv.next = add i8 %iv, 12902/// <...>2903/// br i1 %val.shifted.iszero, label %end, label %loop2904///2905/// end:2906/// %iv.res = phi i8 [ %iv, %loop ] <...>2907/// %nbits.res = phi i8 [ %nbits, %loop ] <...>2908/// %val.shifted.res = phi i8 [ %val.shifted, %loop ] <...>2909/// %val.shifted.iszero.res = phi i1 [ %val.shifted.iszero, %loop ] <...>2910/// %iv.next.res = phi i8 [ %iv.next, %loop ] <...>2911/// <...>2912/// \endcode2913///2914/// And transform it into:2915/// \code2916/// entry:2917/// <...>2918/// %start = <...>2919/// %extraoffset = <...>2920/// <...>2921/// %val.numleadingzeros = call i8 @llvm.ct{l,t}z.i8(i8 %val, i1 0)2922/// %val.numactivebits = sub i8 8, %val.numleadingzeros2923/// %extraoffset.neg = sub i8 0, %extraoffset2924/// %tmp = add i8 %val.numactivebits, %extraoffset.neg2925/// %iv.final = call i8 @llvm.smax.i8(i8 %tmp, i8 %start)2926/// %loop.tripcount = sub i8 %iv.final, %start2927/// br label %loop2928///2929/// loop:2930/// %loop.iv = phi i8 [ 0, %entry ], [ %loop.iv.next, %loop ]2931/// %loop.iv.next = add i8 %loop.iv, 12932/// %loop.ivcheck = icmp eq i8 %loop.iv.next, %loop.tripcount2933/// %iv = add i8 %loop.iv, %start2934/// <...>2935/// br i1 %loop.ivcheck, label %end, label %loop2936///2937/// end:2938/// %iv.res = phi i8 [ %iv.final, %loop ] <...>2939/// <...>2940/// \endcode2941bool LoopIdiomRecognize::recognizeShiftUntilZero() {2942bool MadeChange = false;29432944Instruction *ValShiftedIsZero;2945Intrinsic::ID IntrID;2946Instruction *IV;2947Value *Start, *Val;2948const SCEV *ExtraOffsetExpr;2949bool InvertedCond;2950if (!detectShiftUntilZeroIdiom(CurLoop, SE, ValShiftedIsZero, IntrID, IV,2951Start, Val, ExtraOffsetExpr, InvertedCond)) {2952LLVM_DEBUG(dbgs() << DEBUG_TYPE2953" shift-until-zero idiom detection failed.\n");2954return MadeChange;2955}2956LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom detected!\n");29572958// Ok, it is the idiom we were looking for, we *could* transform this loop,2959// but is it profitable to transform?29602961BasicBlock *LoopHeaderBB = CurLoop->getHeader();2962BasicBlock *LoopPreheaderBB = CurLoop->getLoopPreheader();2963assert(LoopPreheaderBB && "There is always a loop preheader.");29642965BasicBlock *SuccessorBB = CurLoop->getExitBlock();2966assert(SuccessorBB && "There is only a single successor.");29672968IRBuilder<> Builder(LoopPreheaderBB->getTerminator());2969Builder.SetCurrentDebugLocation(IV->getDebugLoc());29702971Type *Ty = Val->getType();2972unsigned Bitwidth = Ty->getScalarSizeInBits();29732974TargetTransformInfo::TargetCostKind CostKind =2975TargetTransformInfo::TCK_SizeAndLatency;29762977// The rewrite is considered to be unprofitable iff and only iff the2978// intrinsic we'll use are not cheap. Note that we are okay with *just*2979// making the loop countable, even if nothing else changes.2980IntrinsicCostAttributes Attrs(2981IntrID, Ty, {PoisonValue::get(Ty), /*is_zero_poison=*/Builder.getFalse()});2982InstructionCost Cost = TTI->getIntrinsicInstrCost(Attrs, CostKind);2983if (Cost > TargetTransformInfo::TCC_Basic) {2984LLVM_DEBUG(dbgs() << DEBUG_TYPE2985" Intrinsic is too costly, not beneficial\n");2986return MadeChange;2987}29882989// Ok, transform appears worthwhile.2990MadeChange = true;29912992bool OffsetIsZero = false;2993if (auto *ExtraOffsetExprC = dyn_cast<SCEVConstant>(ExtraOffsetExpr))2994OffsetIsZero = ExtraOffsetExprC->isZero();29952996// Step 1: Compute the loop's final IV value / trip count.29972998CallInst *ValNumLeadingZeros = Builder.CreateIntrinsic(2999IntrID, Ty, {Val, /*is_zero_poison=*/Builder.getFalse()},3000/*FMFSource=*/nullptr, Val->getName() + ".numleadingzeros");3001Value *ValNumActiveBits = Builder.CreateSub(3002ConstantInt::get(Ty, Ty->getScalarSizeInBits()), ValNumLeadingZeros,3003Val->getName() + ".numactivebits", /*HasNUW=*/true,3004/*HasNSW=*/Bitwidth != 2);30053006SCEVExpander Expander(*SE, *DL, "loop-idiom");3007Expander.setInsertPoint(&*Builder.GetInsertPoint());3008Value *ExtraOffset = Expander.expandCodeFor(ExtraOffsetExpr);30093010Value *ValNumActiveBitsOffset = Builder.CreateAdd(3011ValNumActiveBits, ExtraOffset, ValNumActiveBits->getName() + ".offset",3012/*HasNUW=*/OffsetIsZero, /*HasNSW=*/true);3013Value *IVFinal = Builder.CreateIntrinsic(Intrinsic::smax, {Ty},3014{ValNumActiveBitsOffset, Start},3015/*FMFSource=*/nullptr, "iv.final");30163017auto *LoopBackedgeTakenCount = cast<Instruction>(Builder.CreateSub(3018IVFinal, Start, CurLoop->getName() + ".backedgetakencount",3019/*HasNUW=*/OffsetIsZero, /*HasNSW=*/true));3020// FIXME: or when the offset was `add nuw`30213022// We know loop's backedge-taken count, but what's loop's trip count?3023Value *LoopTripCount =3024Builder.CreateAdd(LoopBackedgeTakenCount, ConstantInt::get(Ty, 1),3025CurLoop->getName() + ".tripcount", /*HasNUW=*/true,3026/*HasNSW=*/Bitwidth != 2);30273028// Step 2: Adjust the successor basic block to recieve the original3029// induction variable's final value instead of the orig. IV itself.30303031IV->replaceUsesOutsideBlock(IVFinal, LoopHeaderBB);30323033// Step 3: Rewrite the loop into a countable form, with canonical IV.30343035// The new canonical induction variable.3036Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->begin());3037auto *CIV = Builder.CreatePHI(Ty, 2, CurLoop->getName() + ".iv");30383039// The induction itself.3040Builder.SetInsertPoint(LoopHeaderBB, LoopHeaderBB->getFirstNonPHIIt());3041auto *CIVNext =3042Builder.CreateAdd(CIV, ConstantInt::get(Ty, 1), CIV->getName() + ".next",3043/*HasNUW=*/true, /*HasNSW=*/Bitwidth != 2);30443045// The loop trip count check.3046auto *CIVCheck = Builder.CreateICmpEQ(CIVNext, LoopTripCount,3047CurLoop->getName() + ".ivcheck");3048auto *NewIVCheck = CIVCheck;3049if (InvertedCond) {3050NewIVCheck = Builder.CreateNot(CIVCheck);3051NewIVCheck->takeName(ValShiftedIsZero);3052}30533054// The original IV, but rebased to be an offset to the CIV.3055auto *IVDePHId = Builder.CreateAdd(CIV, Start, "", /*HasNUW=*/false,3056/*HasNSW=*/true); // FIXME: what about NUW?3057IVDePHId->takeName(IV);30583059// The loop terminator.3060Builder.SetInsertPoint(LoopHeaderBB->getTerminator());3061Builder.CreateCondBr(CIVCheck, SuccessorBB, LoopHeaderBB);3062LoopHeaderBB->getTerminator()->eraseFromParent();30633064// Populate the IV PHI.3065CIV->addIncoming(ConstantInt::get(Ty, 0), LoopPreheaderBB);3066CIV->addIncoming(CIVNext, LoopHeaderBB);30673068// Step 4: Forget the "non-computable" trip-count SCEV associated with the3069// loop. The loop would otherwise not be deleted even if it becomes empty.30703071SE->forgetLoop(CurLoop);30723073// Step 5: Try to cleanup the loop's body somewhat.3074IV->replaceAllUsesWith(IVDePHId);3075IV->eraseFromParent();30763077ValShiftedIsZero->replaceAllUsesWith(NewIVCheck);3078ValShiftedIsZero->eraseFromParent();30793080// Other passes will take care of actually deleting the loop if possible.30813082LLVM_DEBUG(dbgs() << DEBUG_TYPE " shift-until-zero idiom optimized!\n");30833084++NumShiftUntilZero;3085return MadeChange;3086}308730883089