10b57cec5SDimitry Andric //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements induction variable simplification. It does 100b57cec5SDimitry Andric // not define any actual pass or policy, but provides a single function to 110b57cec5SDimitry Andric // simplify a loop's induction variables based on ScalarEvolution. 120b57cec5SDimitry Andric // 130b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 140b57cec5SDimitry Andric 150b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h" 160b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 170b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 180b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 1956727255SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 200b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 210b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h" 220b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 230b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 240b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h" 250b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 260b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 270b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 280fca6ea1SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 295ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 300b57cec5SDimitry Andric 310b57cec5SDimitry Andric using namespace llvm; 32cb14a3feSDimitry Andric using namespace llvm::PatternMatch; 330b57cec5SDimitry Andric 340b57cec5SDimitry Andric #define DEBUG_TYPE "indvars" 350b57cec5SDimitry Andric 360b57cec5SDimitry Andric STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); 370b57cec5SDimitry Andric STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); 380b57cec5SDimitry Andric STATISTIC(NumFoldedUser, "Number of IV users folded into a constant"); 390b57cec5SDimitry Andric STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); 400b57cec5SDimitry Andric STATISTIC( 410b57cec5SDimitry Andric NumSimplifiedSDiv, 420b57cec5SDimitry Andric "Number of IV signed division operations converted to unsigned division"); 430b57cec5SDimitry Andric STATISTIC( 440b57cec5SDimitry Andric NumSimplifiedSRem, 450b57cec5SDimitry Andric "Number of IV signed remainder operations converted to unsigned remainder"); 460b57cec5SDimitry Andric STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); 470b57cec5SDimitry Andric 480b57cec5SDimitry Andric namespace { 490b57cec5SDimitry Andric /// This is a utility for simplifying induction variables 500b57cec5SDimitry Andric /// based on ScalarEvolution. It is the primary instrument of the 510b57cec5SDimitry Andric /// IndvarSimplify pass, but it may also be directly invoked to cleanup after 520b57cec5SDimitry Andric /// other loop passes that preserve SCEV. 530b57cec5SDimitry Andric class SimplifyIndvar { 540b57cec5SDimitry Andric Loop *L; 550b57cec5SDimitry Andric LoopInfo *LI; 560b57cec5SDimitry Andric ScalarEvolution *SE; 570b57cec5SDimitry Andric DominatorTree *DT; 585ffd83dbSDimitry Andric const TargetTransformInfo *TTI; 590b57cec5SDimitry Andric SCEVExpander &Rewriter; 600b57cec5SDimitry Andric SmallVectorImpl<WeakTrackingVH> &DeadInsts; 610b57cec5SDimitry Andric 6281ad6265SDimitry Andric bool Changed = false; 630fca6ea1SDimitry Andric bool RunUnswitching = false; 640b57cec5SDimitry Andric 650b57cec5SDimitry Andric public: 660b57cec5SDimitry Andric SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT, 675ffd83dbSDimitry Andric LoopInfo *LI, const TargetTransformInfo *TTI, 685ffd83dbSDimitry Andric SCEVExpander &Rewriter, 690b57cec5SDimitry Andric SmallVectorImpl<WeakTrackingVH> &Dead) 705ffd83dbSDimitry Andric : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter), 7181ad6265SDimitry Andric DeadInsts(Dead) { 720b57cec5SDimitry Andric assert(LI && "IV simplification requires LoopInfo"); 730b57cec5SDimitry Andric } 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric bool hasChanged() const { return Changed; } 760fca6ea1SDimitry Andric bool runUnswitching() const { return RunUnswitching; } 770b57cec5SDimitry Andric 780b57cec5SDimitry Andric /// Iteratively perform simplification on a worklist of users of the 790b57cec5SDimitry Andric /// specified induction variable. This is the top-level driver that applies 800b57cec5SDimitry Andric /// all simplifications to users of an IV. 810b57cec5SDimitry Andric void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr); 820b57cec5SDimitry Andric 830fca6ea1SDimitry Andric void pushIVUsers(Instruction *Def, 840fca6ea1SDimitry Andric SmallPtrSet<Instruction *, 16> &Simplified, 850fca6ea1SDimitry Andric SmallVectorImpl<std::pair<Instruction *, Instruction *>> 860fca6ea1SDimitry Andric &SimpleIVUsers); 870fca6ea1SDimitry Andric 880b57cec5SDimitry Andric Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand); 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand); 910b57cec5SDimitry Andric bool replaceIVUserWithLoopInvariant(Instruction *UseInst); 92753f127fSDimitry Andric bool replaceFloatIVWithIntegerIV(Instruction *UseInst); 930b57cec5SDimitry Andric 940b57cec5SDimitry Andric bool eliminateOverflowIntrinsic(WithOverflowInst *WO); 950b57cec5SDimitry Andric bool eliminateSaturatingIntrinsic(SaturatingInst *SI); 960b57cec5SDimitry Andric bool eliminateTrunc(TruncInst *TI); 970b57cec5SDimitry Andric bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); 98753f127fSDimitry Andric bool makeIVComparisonInvariant(ICmpInst *ICmp, Instruction *IVOperand); 99753f127fSDimitry Andric void eliminateIVComparison(ICmpInst *ICmp, Instruction *IVOperand); 100753f127fSDimitry Andric void simplifyIVRemainder(BinaryOperator *Rem, Instruction *IVOperand, 1010b57cec5SDimitry Andric bool IsSigned); 1020b57cec5SDimitry Andric void replaceRemWithNumerator(BinaryOperator *Rem); 1030b57cec5SDimitry Andric void replaceRemWithNumeratorOrZero(BinaryOperator *Rem); 1040b57cec5SDimitry Andric void replaceSRemWithURem(BinaryOperator *Rem); 1050b57cec5SDimitry Andric bool eliminateSDiv(BinaryOperator *SDiv); 10606c3fb27SDimitry Andric bool strengthenBinaryOp(BinaryOperator *BO, Instruction *IVOperand); 107753f127fSDimitry Andric bool strengthenOverflowingOperation(BinaryOperator *OBO, 108753f127fSDimitry Andric Instruction *IVOperand); 109753f127fSDimitry Andric bool strengthenRightShift(BinaryOperator *BO, Instruction *IVOperand); 1100b57cec5SDimitry Andric }; 1110b57cec5SDimitry Andric } 1120b57cec5SDimitry Andric 113fe6060f1SDimitry Andric /// Find a point in code which dominates all given instructions. We can safely 114fe6060f1SDimitry Andric /// assume that, whatever fact we can prove at the found point, this fact is 115fe6060f1SDimitry Andric /// also true for each of the given instructions. 116fe6060f1SDimitry Andric static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions, 117fe6060f1SDimitry Andric DominatorTree &DT) { 118fe6060f1SDimitry Andric Instruction *CommonDom = nullptr; 119fe6060f1SDimitry Andric for (auto *Insn : Instructions) 120fe6060f1SDimitry Andric CommonDom = 121bdd1243dSDimitry Andric CommonDom ? DT.findNearestCommonDominator(CommonDom, Insn) : Insn; 122fe6060f1SDimitry Andric assert(CommonDom && "Common dominator not found?"); 123fe6060f1SDimitry Andric return CommonDom; 124fe6060f1SDimitry Andric } 125fe6060f1SDimitry Andric 1260b57cec5SDimitry Andric /// Fold an IV operand into its use. This removes increments of an 1270b57cec5SDimitry Andric /// aligned IV when used by a instruction that ignores the low bits. 1280b57cec5SDimitry Andric /// 1290b57cec5SDimitry Andric /// IVOperand is guaranteed SCEVable, but UseInst may not be. 1300b57cec5SDimitry Andric /// 1310b57cec5SDimitry Andric /// Return the operand of IVOperand for this induction variable if IVOperand can 1320b57cec5SDimitry Andric /// be folded (in case more folding opportunities have been exposed). 1330b57cec5SDimitry Andric /// Otherwise return null. 1340b57cec5SDimitry Andric Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { 1350b57cec5SDimitry Andric Value *IVSrc = nullptr; 1360b57cec5SDimitry Andric const unsigned OperIdx = 0; 1370b57cec5SDimitry Andric const SCEV *FoldedExpr = nullptr; 1380b57cec5SDimitry Andric bool MustDropExactFlag = false; 1390b57cec5SDimitry Andric switch (UseInst->getOpcode()) { 1400b57cec5SDimitry Andric default: 1410b57cec5SDimitry Andric return nullptr; 1420b57cec5SDimitry Andric case Instruction::UDiv: 1430b57cec5SDimitry Andric case Instruction::LShr: 1440b57cec5SDimitry Andric // We're only interested in the case where we know something about 1450b57cec5SDimitry Andric // the numerator and have a constant denominator. 1460b57cec5SDimitry Andric if (IVOperand != UseInst->getOperand(OperIdx) || 1470b57cec5SDimitry Andric !isa<ConstantInt>(UseInst->getOperand(1))) 1480b57cec5SDimitry Andric return nullptr; 1490b57cec5SDimitry Andric 1500b57cec5SDimitry Andric // Attempt to fold a binary operator with constant operand. 1510b57cec5SDimitry Andric // e.g. ((I + 1) >> 2) => I >> 2 1520b57cec5SDimitry Andric if (!isa<BinaryOperator>(IVOperand) 1530b57cec5SDimitry Andric || !isa<ConstantInt>(IVOperand->getOperand(1))) 1540b57cec5SDimitry Andric return nullptr; 1550b57cec5SDimitry Andric 1560b57cec5SDimitry Andric IVSrc = IVOperand->getOperand(0); 1570b57cec5SDimitry Andric // IVSrc must be the (SCEVable) IV, since the other operand is const. 1580b57cec5SDimitry Andric assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); 1590b57cec5SDimitry Andric 1600b57cec5SDimitry Andric ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); 1610b57cec5SDimitry Andric if (UseInst->getOpcode() == Instruction::LShr) { 1620b57cec5SDimitry Andric // Get a constant for the divisor. See createSCEV. 1630b57cec5SDimitry Andric uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); 1640b57cec5SDimitry Andric if (D->getValue().uge(BitWidth)) 1650b57cec5SDimitry Andric return nullptr; 1660b57cec5SDimitry Andric 1670b57cec5SDimitry Andric D = ConstantInt::get(UseInst->getContext(), 1680b57cec5SDimitry Andric APInt::getOneBitSet(BitWidth, D->getZExtValue())); 1690b57cec5SDimitry Andric } 17081ad6265SDimitry Andric const auto *LHS = SE->getSCEV(IVSrc); 17181ad6265SDimitry Andric const auto *RHS = SE->getSCEV(D); 17281ad6265SDimitry Andric FoldedExpr = SE->getUDivExpr(LHS, RHS); 1730b57cec5SDimitry Andric // We might have 'exact' flag set at this point which will no longer be 1740b57cec5SDimitry Andric // correct after we make the replacement. 17581ad6265SDimitry Andric if (UseInst->isExact() && LHS != SE->getMulExpr(FoldedExpr, RHS)) 1760b57cec5SDimitry Andric MustDropExactFlag = true; 1770b57cec5SDimitry Andric } 1780b57cec5SDimitry Andric // We have something that might fold it's operand. Compare SCEVs. 1790b57cec5SDimitry Andric if (!SE->isSCEVable(UseInst->getType())) 1800b57cec5SDimitry Andric return nullptr; 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric // Bypass the operand if SCEV can prove it has no effect. 1830b57cec5SDimitry Andric if (SE->getSCEV(UseInst) != FoldedExpr) 1840b57cec5SDimitry Andric return nullptr; 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand 1870b57cec5SDimitry Andric << " -> " << *UseInst << '\n'); 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric UseInst->setOperand(OperIdx, IVSrc); 1900b57cec5SDimitry Andric assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric if (MustDropExactFlag) 1930b57cec5SDimitry Andric UseInst->dropPoisonGeneratingFlags(); 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric ++NumElimOperand; 1960b57cec5SDimitry Andric Changed = true; 1970b57cec5SDimitry Andric if (IVOperand->use_empty()) 1980b57cec5SDimitry Andric DeadInsts.emplace_back(IVOperand); 1990b57cec5SDimitry Andric return IVSrc; 2000b57cec5SDimitry Andric } 2010b57cec5SDimitry Andric 2020b57cec5SDimitry Andric bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp, 203753f127fSDimitry Andric Instruction *IVOperand) { 204bdd1243dSDimitry Andric auto *Preheader = L->getLoopPreheader(); 205bdd1243dSDimitry Andric if (!Preheader) 206bdd1243dSDimitry Andric return false; 2070b57cec5SDimitry Andric unsigned IVOperIdx = 0; 2080b57cec5SDimitry Andric ICmpInst::Predicate Pred = ICmp->getPredicate(); 2090b57cec5SDimitry Andric if (IVOperand != ICmp->getOperand(0)) { 2100b57cec5SDimitry Andric // Swapped 2110b57cec5SDimitry Andric assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 2120b57cec5SDimitry Andric IVOperIdx = 1; 2130b57cec5SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred); 2140b57cec5SDimitry Andric } 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric // Get the SCEVs for the ICmp operands (in the specific context of the 2170b57cec5SDimitry Andric // current loop) 2180b57cec5SDimitry Andric const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 2190b57cec5SDimitry Andric const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); 2200b57cec5SDimitry Andric const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); 221bdd1243dSDimitry Andric auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L, ICmp); 222e8d8bef9SDimitry Andric if (!LIP) 2230b57cec5SDimitry Andric return false; 224e8d8bef9SDimitry Andric ICmpInst::Predicate InvariantPredicate = LIP->Pred; 225e8d8bef9SDimitry Andric const SCEV *InvariantLHS = LIP->LHS; 226e8d8bef9SDimitry Andric const SCEV *InvariantRHS = LIP->RHS; 2270b57cec5SDimitry Andric 228bdd1243dSDimitry Andric // Do not generate something ridiculous. 229bdd1243dSDimitry Andric auto *PHTerm = Preheader->getTerminator(); 230bdd1243dSDimitry Andric if (Rewriter.isHighCostExpansion({InvariantLHS, InvariantRHS}, L, 23106c3fb27SDimitry Andric 2 * SCEVCheapExpansionBudget, TTI, PHTerm) || 23206c3fb27SDimitry Andric !Rewriter.isSafeToExpandAt(InvariantLHS, PHTerm) || 23306c3fb27SDimitry Andric !Rewriter.isSafeToExpandAt(InvariantRHS, PHTerm)) 2340b57cec5SDimitry Andric return false; 235bdd1243dSDimitry Andric auto *NewLHS = 236bdd1243dSDimitry Andric Rewriter.expandCodeFor(InvariantLHS, IVOperand->getType(), PHTerm); 237bdd1243dSDimitry Andric auto *NewRHS = 238bdd1243dSDimitry Andric Rewriter.expandCodeFor(InvariantRHS, IVOperand->getType(), PHTerm); 2390b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n'); 2400b57cec5SDimitry Andric ICmp->setPredicate(InvariantPredicate); 2410b57cec5SDimitry Andric ICmp->setOperand(0, NewLHS); 2420b57cec5SDimitry Andric ICmp->setOperand(1, NewRHS); 2430fca6ea1SDimitry Andric RunUnswitching = true; 2440b57cec5SDimitry Andric return true; 2450b57cec5SDimitry Andric } 2460b57cec5SDimitry Andric 2470b57cec5SDimitry Andric /// SimplifyIVUsers helper for eliminating useless 2480b57cec5SDimitry Andric /// comparisons against an induction variable. 249753f127fSDimitry Andric void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, 250753f127fSDimitry Andric Instruction *IVOperand) { 2510b57cec5SDimitry Andric unsigned IVOperIdx = 0; 2520b57cec5SDimitry Andric ICmpInst::Predicate Pred = ICmp->getPredicate(); 2530b57cec5SDimitry Andric ICmpInst::Predicate OriginalPred = Pred; 2540b57cec5SDimitry Andric if (IVOperand != ICmp->getOperand(0)) { 2550b57cec5SDimitry Andric // Swapped 2560b57cec5SDimitry Andric assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); 2570b57cec5SDimitry Andric IVOperIdx = 1; 2580b57cec5SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred); 2590b57cec5SDimitry Andric } 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric // Get the SCEVs for the ICmp operands (in the specific context of the 2620b57cec5SDimitry Andric // current loop) 2630b57cec5SDimitry Andric const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); 2640b57cec5SDimitry Andric const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); 2650b57cec5SDimitry Andric const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); 2660b57cec5SDimitry Andric 267fe6060f1SDimitry Andric // If the condition is always true or always false in the given context, 268fe6060f1SDimitry Andric // replace it with a constant value. 269fe6060f1SDimitry Andric SmallVector<Instruction *, 4> Users; 270fe6060f1SDimitry Andric for (auto *U : ICmp->users()) 271fe6060f1SDimitry Andric Users.push_back(cast<Instruction>(U)); 272fe6060f1SDimitry Andric const Instruction *CtxI = findCommonDominator(Users, *DT); 273fe6060f1SDimitry Andric if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) { 274bdd1243dSDimitry Andric SE->forgetValue(ICmp); 275fe6060f1SDimitry Andric ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev)); 2760b57cec5SDimitry Andric DeadInsts.emplace_back(ICmp); 2770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); 2780b57cec5SDimitry Andric } else if (makeIVComparisonInvariant(ICmp, IVOperand)) { 2790b57cec5SDimitry Andric // fallthrough to end of function 2800b57cec5SDimitry Andric } else if (ICmpInst::isSigned(OriginalPred) && 2810b57cec5SDimitry Andric SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) { 2820b57cec5SDimitry Andric // If we were unable to make anything above, all we can is to canonicalize 2830b57cec5SDimitry Andric // the comparison hoping that it will open the doors for other 2840b57cec5SDimitry Andric // optimizations. If we find out that we compare two non-negative values, 2850b57cec5SDimitry Andric // we turn the instruction's predicate to its unsigned version. Note that 2860b57cec5SDimitry Andric // we cannot rely on Pred here unless we check if we have swapped it. 2870b57cec5SDimitry Andric assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?"); 2880b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp 2890b57cec5SDimitry Andric << '\n'); 2900b57cec5SDimitry Andric ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred)); 2910b57cec5SDimitry Andric } else 2920b57cec5SDimitry Andric return; 2930b57cec5SDimitry Andric 2940b57cec5SDimitry Andric ++NumElimCmp; 2950b57cec5SDimitry Andric Changed = true; 2960b57cec5SDimitry Andric } 2970b57cec5SDimitry Andric 2980b57cec5SDimitry Andric bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) { 2990b57cec5SDimitry Andric // Get the SCEVs for the ICmp operands. 3000b57cec5SDimitry Andric auto *N = SE->getSCEV(SDiv->getOperand(0)); 3010b57cec5SDimitry Andric auto *D = SE->getSCEV(SDiv->getOperand(1)); 3020b57cec5SDimitry Andric 3030b57cec5SDimitry Andric // Simplify unnecessary loops away. 3040b57cec5SDimitry Andric const Loop *L = LI->getLoopFor(SDiv->getParent()); 3050b57cec5SDimitry Andric N = SE->getSCEVAtScope(N, L); 3060b57cec5SDimitry Andric D = SE->getSCEVAtScope(D, L); 3070b57cec5SDimitry Andric 3080b57cec5SDimitry Andric // Replace sdiv by udiv if both of the operands are non-negative 3090b57cec5SDimitry Andric if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) { 3100b57cec5SDimitry Andric auto *UDiv = BinaryOperator::Create( 3110b57cec5SDimitry Andric BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1), 3120fca6ea1SDimitry Andric SDiv->getName() + ".udiv", SDiv->getIterator()); 3130b57cec5SDimitry Andric UDiv->setIsExact(SDiv->isExact()); 3140b57cec5SDimitry Andric SDiv->replaceAllUsesWith(UDiv); 3150fca6ea1SDimitry Andric UDiv->setDebugLoc(SDiv->getDebugLoc()); 3160b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n'); 3170b57cec5SDimitry Andric ++NumSimplifiedSDiv; 3180b57cec5SDimitry Andric Changed = true; 3190b57cec5SDimitry Andric DeadInsts.push_back(SDiv); 3200b57cec5SDimitry Andric return true; 3210b57cec5SDimitry Andric } 3220b57cec5SDimitry Andric 3230b57cec5SDimitry Andric return false; 3240b57cec5SDimitry Andric } 3250b57cec5SDimitry Andric 3260b57cec5SDimitry Andric // i %s n -> i %u n if i >= 0 and n >= 0 3270b57cec5SDimitry Andric void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) { 3280b57cec5SDimitry Andric auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 3290b57cec5SDimitry Andric auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D, 3300fca6ea1SDimitry Andric Rem->getName() + ".urem", Rem->getIterator()); 3310b57cec5SDimitry Andric Rem->replaceAllUsesWith(URem); 3320fca6ea1SDimitry Andric URem->setDebugLoc(Rem->getDebugLoc()); 3330b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n'); 3340b57cec5SDimitry Andric ++NumSimplifiedSRem; 3350b57cec5SDimitry Andric Changed = true; 3360b57cec5SDimitry Andric DeadInsts.emplace_back(Rem); 3370b57cec5SDimitry Andric } 3380b57cec5SDimitry Andric 3390b57cec5SDimitry Andric // i % n --> i if i is in [0,n). 3400b57cec5SDimitry Andric void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) { 3410b57cec5SDimitry Andric Rem->replaceAllUsesWith(Rem->getOperand(0)); 3420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 3430b57cec5SDimitry Andric ++NumElimRem; 3440b57cec5SDimitry Andric Changed = true; 3450b57cec5SDimitry Andric DeadInsts.emplace_back(Rem); 3460b57cec5SDimitry Andric } 3470b57cec5SDimitry Andric 3480b57cec5SDimitry Andric // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). 3490b57cec5SDimitry Andric void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) { 3500b57cec5SDimitry Andric auto *T = Rem->getType(); 3510b57cec5SDimitry Andric auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); 3520fca6ea1SDimitry Andric ICmpInst *ICmp = new ICmpInst(Rem->getIterator(), ICmpInst::ICMP_EQ, N, D); 3530b57cec5SDimitry Andric SelectInst *Sel = 3540fca6ea1SDimitry Andric SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem->getIterator()); 3550b57cec5SDimitry Andric Rem->replaceAllUsesWith(Sel); 3560fca6ea1SDimitry Andric Sel->setDebugLoc(Rem->getDebugLoc()); 3570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); 3580b57cec5SDimitry Andric ++NumElimRem; 3590b57cec5SDimitry Andric Changed = true; 3600b57cec5SDimitry Andric DeadInsts.emplace_back(Rem); 3610b57cec5SDimitry Andric } 3620b57cec5SDimitry Andric 3630b57cec5SDimitry Andric /// SimplifyIVUsers helper for eliminating useless remainder operations 3640b57cec5SDimitry Andric /// operating on an induction variable or replacing srem by urem. 365753f127fSDimitry Andric void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, 366753f127fSDimitry Andric Instruction *IVOperand, 3670b57cec5SDimitry Andric bool IsSigned) { 3680b57cec5SDimitry Andric auto *NValue = Rem->getOperand(0); 3690b57cec5SDimitry Andric auto *DValue = Rem->getOperand(1); 3700b57cec5SDimitry Andric // We're only interested in the case where we know something about 3710b57cec5SDimitry Andric // the numerator, unless it is a srem, because we want to replace srem by urem 3720b57cec5SDimitry Andric // in general. 3730b57cec5SDimitry Andric bool UsedAsNumerator = IVOperand == NValue; 3740b57cec5SDimitry Andric if (!UsedAsNumerator && !IsSigned) 3750b57cec5SDimitry Andric return; 3760b57cec5SDimitry Andric 3770b57cec5SDimitry Andric const SCEV *N = SE->getSCEV(NValue); 3780b57cec5SDimitry Andric 3790b57cec5SDimitry Andric // Simplify unnecessary loops away. 3800b57cec5SDimitry Andric const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); 3810b57cec5SDimitry Andric N = SE->getSCEVAtScope(N, ICmpLoop); 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N); 3840b57cec5SDimitry Andric 3850b57cec5SDimitry Andric // Do not proceed if the Numerator may be negative 3860b57cec5SDimitry Andric if (!IsNumeratorNonNegative) 3870b57cec5SDimitry Andric return; 3880b57cec5SDimitry Andric 3890b57cec5SDimitry Andric const SCEV *D = SE->getSCEV(DValue); 3900b57cec5SDimitry Andric D = SE->getSCEVAtScope(D, ICmpLoop); 3910b57cec5SDimitry Andric 3920b57cec5SDimitry Andric if (UsedAsNumerator) { 3930b57cec5SDimitry Andric auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 3940b57cec5SDimitry Andric if (SE->isKnownPredicate(LT, N, D)) { 3950b57cec5SDimitry Andric replaceRemWithNumerator(Rem); 3960b57cec5SDimitry Andric return; 3970b57cec5SDimitry Andric } 3980b57cec5SDimitry Andric 3990b57cec5SDimitry Andric auto *T = Rem->getType(); 4000b57cec5SDimitry Andric const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T)); 4010b57cec5SDimitry Andric if (SE->isKnownPredicate(LT, NLessOne, D)) { 4020b57cec5SDimitry Andric replaceRemWithNumeratorOrZero(Rem); 4030b57cec5SDimitry Andric return; 4040b57cec5SDimitry Andric } 4050b57cec5SDimitry Andric } 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric // Try to replace SRem with URem, if both N and D are known non-negative. 4080b57cec5SDimitry Andric // Since we had already check N, we only need to check D now 4090b57cec5SDimitry Andric if (!IsSigned || !SE->isKnownNonNegative(D)) 4100b57cec5SDimitry Andric return; 4110b57cec5SDimitry Andric 4120b57cec5SDimitry Andric replaceSRemWithURem(Rem); 4130b57cec5SDimitry Andric } 4140b57cec5SDimitry Andric 4150b57cec5SDimitry Andric bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) { 4160b57cec5SDimitry Andric const SCEV *LHS = SE->getSCEV(WO->getLHS()); 4170b57cec5SDimitry Andric const SCEV *RHS = SE->getSCEV(WO->getRHS()); 418fe6060f1SDimitry Andric if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS)) 4190b57cec5SDimitry Andric return false; 4200b57cec5SDimitry Andric 4210b57cec5SDimitry Andric // Proved no overflow, nuke the overflow check and, if possible, the overflow 4220b57cec5SDimitry Andric // intrinsic as well. 4230b57cec5SDimitry Andric 4240b57cec5SDimitry Andric BinaryOperator *NewResult = BinaryOperator::Create( 4250fca6ea1SDimitry Andric WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO->getIterator()); 4260b57cec5SDimitry Andric 4270b57cec5SDimitry Andric if (WO->isSigned()) 4280b57cec5SDimitry Andric NewResult->setHasNoSignedWrap(true); 4290b57cec5SDimitry Andric else 4300b57cec5SDimitry Andric NewResult->setHasNoUnsignedWrap(true); 4310b57cec5SDimitry Andric 4320b57cec5SDimitry Andric SmallVector<ExtractValueInst *, 4> ToDelete; 4330b57cec5SDimitry Andric 4340b57cec5SDimitry Andric for (auto *U : WO->users()) { 4350b57cec5SDimitry Andric if (auto *EVI = dyn_cast<ExtractValueInst>(U)) { 4360b57cec5SDimitry Andric if (EVI->getIndices()[0] == 1) 4370b57cec5SDimitry Andric EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext())); 4380b57cec5SDimitry Andric else { 4390b57cec5SDimitry Andric assert(EVI->getIndices()[0] == 0 && "Only two possibilities!"); 4400b57cec5SDimitry Andric EVI->replaceAllUsesWith(NewResult); 4410fca6ea1SDimitry Andric NewResult->setDebugLoc(EVI->getDebugLoc()); 4420b57cec5SDimitry Andric } 4430b57cec5SDimitry Andric ToDelete.push_back(EVI); 4440b57cec5SDimitry Andric } 4450b57cec5SDimitry Andric } 4460b57cec5SDimitry Andric 4470b57cec5SDimitry Andric for (auto *EVI : ToDelete) 4480b57cec5SDimitry Andric EVI->eraseFromParent(); 4490b57cec5SDimitry Andric 4500b57cec5SDimitry Andric if (WO->use_empty()) 4510b57cec5SDimitry Andric WO->eraseFromParent(); 4520b57cec5SDimitry Andric 453e8d8bef9SDimitry Andric Changed = true; 4540b57cec5SDimitry Andric return true; 4550b57cec5SDimitry Andric } 4560b57cec5SDimitry Andric 4570b57cec5SDimitry Andric bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) { 4580b57cec5SDimitry Andric const SCEV *LHS = SE->getSCEV(SI->getLHS()); 4590b57cec5SDimitry Andric const SCEV *RHS = SE->getSCEV(SI->getRHS()); 460fe6060f1SDimitry Andric if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS)) 4610b57cec5SDimitry Andric return false; 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric BinaryOperator *BO = BinaryOperator::Create( 4640fca6ea1SDimitry Andric SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI->getIterator()); 4650b57cec5SDimitry Andric if (SI->isSigned()) 4660b57cec5SDimitry Andric BO->setHasNoSignedWrap(); 4670b57cec5SDimitry Andric else 4680b57cec5SDimitry Andric BO->setHasNoUnsignedWrap(); 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric SI->replaceAllUsesWith(BO); 4710fca6ea1SDimitry Andric BO->setDebugLoc(SI->getDebugLoc()); 4720b57cec5SDimitry Andric DeadInsts.emplace_back(SI); 4730b57cec5SDimitry Andric Changed = true; 4740b57cec5SDimitry Andric return true; 4750b57cec5SDimitry Andric } 4760b57cec5SDimitry Andric 4770b57cec5SDimitry Andric bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) { 4780b57cec5SDimitry Andric // It is always legal to replace 4790b57cec5SDimitry Andric // icmp <pred> i32 trunc(iv), n 4800b57cec5SDimitry Andric // with 4810b57cec5SDimitry Andric // icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate. 4820b57cec5SDimitry Andric // Or with 4830b57cec5SDimitry Andric // icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate. 4840b57cec5SDimitry Andric // Or with either of these if pred is an equality predicate. 4850b57cec5SDimitry Andric // 4860b57cec5SDimitry Andric // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for 4870b57cec5SDimitry Andric // every comparison which uses trunc, it means that we can replace each of 4880b57cec5SDimitry Andric // them with comparison of iv against sext/zext(n). We no longer need trunc 4890b57cec5SDimitry Andric // after that. 4900b57cec5SDimitry Andric // 4910b57cec5SDimitry Andric // TODO: Should we do this if we can widen *some* comparisons, but not all 4920b57cec5SDimitry Andric // of them? Sometimes it is enough to enable other optimizations, but the 4930b57cec5SDimitry Andric // trunc instruction will stay in the loop. 4940b57cec5SDimitry Andric Value *IV = TI->getOperand(0); 4950b57cec5SDimitry Andric Type *IVTy = IV->getType(); 4960b57cec5SDimitry Andric const SCEV *IVSCEV = SE->getSCEV(IV); 4970b57cec5SDimitry Andric const SCEV *TISCEV = SE->getSCEV(TI); 4980b57cec5SDimitry Andric 4990b57cec5SDimitry Andric // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can 5000b57cec5SDimitry Andric // get rid of trunc 5010b57cec5SDimitry Andric bool DoesSExtCollapse = false; 5020b57cec5SDimitry Andric bool DoesZExtCollapse = false; 5030b57cec5SDimitry Andric if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy)) 5040b57cec5SDimitry Andric DoesSExtCollapse = true; 5050b57cec5SDimitry Andric if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy)) 5060b57cec5SDimitry Andric DoesZExtCollapse = true; 5070b57cec5SDimitry Andric 5080b57cec5SDimitry Andric // If neither sext nor zext does collapse, it is not profitable to do any 5090b57cec5SDimitry Andric // transform. Bail. 5100b57cec5SDimitry Andric if (!DoesSExtCollapse && !DoesZExtCollapse) 5110b57cec5SDimitry Andric return false; 5120b57cec5SDimitry Andric 5130b57cec5SDimitry Andric // Collect users of the trunc that look like comparisons against invariants. 5140b57cec5SDimitry Andric // Bail if we find something different. 5150b57cec5SDimitry Andric SmallVector<ICmpInst *, 4> ICmpUsers; 5160b57cec5SDimitry Andric for (auto *U : TI->users()) { 5170b57cec5SDimitry Andric // We don't care about users in unreachable blocks. 5180b57cec5SDimitry Andric if (isa<Instruction>(U) && 5190b57cec5SDimitry Andric !DT->isReachableFromEntry(cast<Instruction>(U)->getParent())) 5200b57cec5SDimitry Andric continue; 5210b57cec5SDimitry Andric ICmpInst *ICI = dyn_cast<ICmpInst>(U); 5220b57cec5SDimitry Andric if (!ICI) return false; 5230b57cec5SDimitry Andric assert(L->contains(ICI->getParent()) && "LCSSA form broken?"); 5240b57cec5SDimitry Andric if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) && 5250b57cec5SDimitry Andric !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0)))) 5260b57cec5SDimitry Andric return false; 5270b57cec5SDimitry Andric // If we cannot get rid of trunc, bail. 5280b57cec5SDimitry Andric if (ICI->isSigned() && !DoesSExtCollapse) 5290b57cec5SDimitry Andric return false; 5300b57cec5SDimitry Andric if (ICI->isUnsigned() && !DoesZExtCollapse) 5310b57cec5SDimitry Andric return false; 5320b57cec5SDimitry Andric // For equality, either signed or unsigned works. 5330b57cec5SDimitry Andric ICmpUsers.push_back(ICI); 5340b57cec5SDimitry Andric } 5350b57cec5SDimitry Andric 5360b57cec5SDimitry Andric auto CanUseZExt = [&](ICmpInst *ICI) { 5370b57cec5SDimitry Andric // Unsigned comparison can be widened as unsigned. 5380b57cec5SDimitry Andric if (ICI->isUnsigned()) 5390b57cec5SDimitry Andric return true; 5400b57cec5SDimitry Andric // Is it profitable to do zext? 5410b57cec5SDimitry Andric if (!DoesZExtCollapse) 5420b57cec5SDimitry Andric return false; 5430b57cec5SDimitry Andric // For equality, we can safely zext both parts. 5440b57cec5SDimitry Andric if (ICI->isEquality()) 5450b57cec5SDimitry Andric return true; 5460b57cec5SDimitry Andric // Otherwise we can only use zext when comparing two non-negative or two 5470b57cec5SDimitry Andric // negative values. But in practice, we will never pass DoesZExtCollapse 5480b57cec5SDimitry Andric // check for a negative value, because zext(trunc(x)) is non-negative. So 5490b57cec5SDimitry Andric // it only make sense to check for non-negativity here. 5500b57cec5SDimitry Andric const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0)); 5510b57cec5SDimitry Andric const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1)); 5520b57cec5SDimitry Andric return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2); 5530b57cec5SDimitry Andric }; 5540b57cec5SDimitry Andric // Replace all comparisons against trunc with comparisons against IV. 5550b57cec5SDimitry Andric for (auto *ICI : ICmpUsers) { 5560b57cec5SDimitry Andric bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0)); 5570b57cec5SDimitry Andric auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1); 5585f757f3fSDimitry Andric IRBuilder<> Builder(ICI); 5595f757f3fSDimitry Andric Value *Ext = nullptr; 5600b57cec5SDimitry Andric // For signed/unsigned predicate, replace the old comparison with comparison 5610b57cec5SDimitry Andric // of immediate IV against sext/zext of the invariant argument. If we can 5620b57cec5SDimitry Andric // use either sext or zext (i.e. we are dealing with equality predicate), 5630b57cec5SDimitry Andric // then prefer zext as a more canonical form. 5640b57cec5SDimitry Andric // TODO: If we see a signed comparison which can be turned into unsigned, 5650b57cec5SDimitry Andric // we can do it here for canonicalization purposes. 5660b57cec5SDimitry Andric ICmpInst::Predicate Pred = ICI->getPredicate(); 5670b57cec5SDimitry Andric if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred); 5680b57cec5SDimitry Andric if (CanUseZExt(ICI)) { 5690b57cec5SDimitry Andric assert(DoesZExtCollapse && "Unprofitable zext?"); 5705f757f3fSDimitry Andric Ext = Builder.CreateZExt(Op1, IVTy, "zext"); 5710b57cec5SDimitry Andric Pred = ICmpInst::getUnsignedPredicate(Pred); 5720b57cec5SDimitry Andric } else { 5730b57cec5SDimitry Andric assert(DoesSExtCollapse && "Unprofitable sext?"); 5745f757f3fSDimitry Andric Ext = Builder.CreateSExt(Op1, IVTy, "sext"); 5750b57cec5SDimitry Andric assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!"); 5760b57cec5SDimitry Andric } 5770b57cec5SDimitry Andric bool Changed; 5780b57cec5SDimitry Andric L->makeLoopInvariant(Ext, Changed); 5790b57cec5SDimitry Andric (void)Changed; 5805f757f3fSDimitry Andric auto *NewCmp = Builder.CreateICmp(Pred, IV, Ext); 5815f757f3fSDimitry Andric ICI->replaceAllUsesWith(NewCmp); 5820b57cec5SDimitry Andric DeadInsts.emplace_back(ICI); 5830b57cec5SDimitry Andric } 5840b57cec5SDimitry Andric 5850b57cec5SDimitry Andric // Trunc no longer needed. 586fcaf7f86SDimitry Andric TI->replaceAllUsesWith(PoisonValue::get(TI->getType())); 5870b57cec5SDimitry Andric DeadInsts.emplace_back(TI); 5880b57cec5SDimitry Andric return true; 5890b57cec5SDimitry Andric } 5900b57cec5SDimitry Andric 5910b57cec5SDimitry Andric /// Eliminate an operation that consumes a simple IV and has no observable 5920b57cec5SDimitry Andric /// side-effect given the range of IV values. IVOperand is guaranteed SCEVable, 5930b57cec5SDimitry Andric /// but UseInst may not be. 5940b57cec5SDimitry Andric bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, 5950b57cec5SDimitry Andric Instruction *IVOperand) { 5960b57cec5SDimitry Andric if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { 5970b57cec5SDimitry Andric eliminateIVComparison(ICmp, IVOperand); 5980b57cec5SDimitry Andric return true; 5990b57cec5SDimitry Andric } 6000b57cec5SDimitry Andric if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) { 6010b57cec5SDimitry Andric bool IsSRem = Bin->getOpcode() == Instruction::SRem; 6020b57cec5SDimitry Andric if (IsSRem || Bin->getOpcode() == Instruction::URem) { 6030b57cec5SDimitry Andric simplifyIVRemainder(Bin, IVOperand, IsSRem); 6040b57cec5SDimitry Andric return true; 6050b57cec5SDimitry Andric } 6060b57cec5SDimitry Andric 6070b57cec5SDimitry Andric if (Bin->getOpcode() == Instruction::SDiv) 6080b57cec5SDimitry Andric return eliminateSDiv(Bin); 6090b57cec5SDimitry Andric } 6100b57cec5SDimitry Andric 6110b57cec5SDimitry Andric if (auto *WO = dyn_cast<WithOverflowInst>(UseInst)) 6120b57cec5SDimitry Andric if (eliminateOverflowIntrinsic(WO)) 6130b57cec5SDimitry Andric return true; 6140b57cec5SDimitry Andric 6150b57cec5SDimitry Andric if (auto *SI = dyn_cast<SaturatingInst>(UseInst)) 6160b57cec5SDimitry Andric if (eliminateSaturatingIntrinsic(SI)) 6170b57cec5SDimitry Andric return true; 6180b57cec5SDimitry Andric 6190b57cec5SDimitry Andric if (auto *TI = dyn_cast<TruncInst>(UseInst)) 6200b57cec5SDimitry Andric if (eliminateTrunc(TI)) 6210b57cec5SDimitry Andric return true; 6220b57cec5SDimitry Andric 6230b57cec5SDimitry Andric if (eliminateIdentitySCEV(UseInst, IVOperand)) 6240b57cec5SDimitry Andric return true; 6250b57cec5SDimitry Andric 6260b57cec5SDimitry Andric return false; 6270b57cec5SDimitry Andric } 6280b57cec5SDimitry Andric 6290b57cec5SDimitry Andric static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) { 6300b57cec5SDimitry Andric if (auto *BB = L->getLoopPreheader()) 6310b57cec5SDimitry Andric return BB->getTerminator(); 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric return Hint; 6340b57cec5SDimitry Andric } 6350b57cec5SDimitry Andric 6365ffd83dbSDimitry Andric /// Replace the UseInst with a loop invariant expression if it is safe. 6370b57cec5SDimitry Andric bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) { 6380b57cec5SDimitry Andric if (!SE->isSCEVable(I->getType())) 6390b57cec5SDimitry Andric return false; 6400b57cec5SDimitry Andric 6410b57cec5SDimitry Andric // Get the symbolic expression for this instruction. 6420b57cec5SDimitry Andric const SCEV *S = SE->getSCEV(I); 6430b57cec5SDimitry Andric 6440b57cec5SDimitry Andric if (!SE->isLoopInvariant(S, L)) 6450b57cec5SDimitry Andric return false; 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric // Do not generate something ridiculous even if S is loop invariant. 6485ffd83dbSDimitry Andric if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I)) 6490b57cec5SDimitry Andric return false; 6500b57cec5SDimitry Andric 6510b57cec5SDimitry Andric auto *IP = GetLoopInvariantInsertPosition(L, I); 6525ffd83dbSDimitry Andric 653fcaf7f86SDimitry Andric if (!Rewriter.isSafeToExpandAt(S, IP)) { 6545ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I 6555ffd83dbSDimitry Andric << " with non-speculable loop invariant: " << *S << '\n'); 6565ffd83dbSDimitry Andric return false; 6575ffd83dbSDimitry Andric } 6585ffd83dbSDimitry Andric 6590b57cec5SDimitry Andric auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP); 6600fca6ea1SDimitry Andric bool NeedToEmitLCSSAPhis = false; 6610fca6ea1SDimitry Andric if (!LI->replacementPreservesLCSSAForm(I, Invariant)) 6620fca6ea1SDimitry Andric NeedToEmitLCSSAPhis = true; 6630b57cec5SDimitry Andric 6640b57cec5SDimitry Andric I->replaceAllUsesWith(Invariant); 6650b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I 6660b57cec5SDimitry Andric << " with loop invariant: " << *S << '\n'); 6670fca6ea1SDimitry Andric 6680fca6ea1SDimitry Andric if (NeedToEmitLCSSAPhis) { 6690fca6ea1SDimitry Andric SmallVector<Instruction *, 1> NeedsLCSSAPhis; 6700fca6ea1SDimitry Andric NeedsLCSSAPhis.push_back(cast<Instruction>(Invariant)); 6710fca6ea1SDimitry Andric formLCSSAForInstructions(NeedsLCSSAPhis, *DT, *LI, SE); 6720fca6ea1SDimitry Andric LLVM_DEBUG(dbgs() << " INDVARS: Replacement breaks LCSSA form" 6730fca6ea1SDimitry Andric << " inserting LCSSA Phis" << '\n'); 6740fca6ea1SDimitry Andric } 6750b57cec5SDimitry Andric ++NumFoldedUser; 6760b57cec5SDimitry Andric Changed = true; 6770b57cec5SDimitry Andric DeadInsts.emplace_back(I); 6780b57cec5SDimitry Andric return true; 6790b57cec5SDimitry Andric } 6800b57cec5SDimitry Andric 681753f127fSDimitry Andric /// Eliminate redundant type cast between integer and float. 682753f127fSDimitry Andric bool SimplifyIndvar::replaceFloatIVWithIntegerIV(Instruction *UseInst) { 683fcaf7f86SDimitry Andric if (UseInst->getOpcode() != CastInst::SIToFP && 684fcaf7f86SDimitry Andric UseInst->getOpcode() != CastInst::UIToFP) 685753f127fSDimitry Andric return false; 686753f127fSDimitry Andric 687bdd1243dSDimitry Andric Instruction *IVOperand = cast<Instruction>(UseInst->getOperand(0)); 688753f127fSDimitry Andric // Get the symbolic expression for this instruction. 689fcaf7f86SDimitry Andric const SCEV *IV = SE->getSCEV(IVOperand); 6905f757f3fSDimitry Andric int MaskBits; 691fcaf7f86SDimitry Andric if (UseInst->getOpcode() == CastInst::SIToFP) 6925f757f3fSDimitry Andric MaskBits = (int)SE->getSignedRange(IV).getMinSignedBits(); 693fcaf7f86SDimitry Andric else 6945f757f3fSDimitry Andric MaskBits = (int)SE->getUnsignedRange(IV).getActiveBits(); 6955f757f3fSDimitry Andric int DestNumSigBits = UseInst->getType()->getFPMantissaWidth(); 696fcaf7f86SDimitry Andric if (MaskBits <= DestNumSigBits) { 697753f127fSDimitry Andric for (User *U : UseInst->users()) { 698fcaf7f86SDimitry Andric // Match for fptosi/fptoui of sitofp and with same type. 699fcaf7f86SDimitry Andric auto *CI = dyn_cast<CastInst>(U); 700bdd1243dSDimitry Andric if (!CI) 701753f127fSDimitry Andric continue; 702753f127fSDimitry Andric 703fcaf7f86SDimitry Andric CastInst::CastOps Opcode = CI->getOpcode(); 704fcaf7f86SDimitry Andric if (Opcode != CastInst::FPToSI && Opcode != CastInst::FPToUI) 705fcaf7f86SDimitry Andric continue; 706fcaf7f86SDimitry Andric 707bdd1243dSDimitry Andric Value *Conv = nullptr; 708bdd1243dSDimitry Andric if (IVOperand->getType() != CI->getType()) { 709bdd1243dSDimitry Andric IRBuilder<> Builder(CI); 710bdd1243dSDimitry Andric StringRef Name = IVOperand->getName(); 711bdd1243dSDimitry Andric // To match InstCombine logic, we only need sext if both fptosi and 712bdd1243dSDimitry Andric // sitofp are used. If one of them is unsigned, then we can use zext. 713bdd1243dSDimitry Andric if (SE->getTypeSizeInBits(IVOperand->getType()) > 714bdd1243dSDimitry Andric SE->getTypeSizeInBits(CI->getType())) { 715bdd1243dSDimitry Andric Conv = Builder.CreateTrunc(IVOperand, CI->getType(), Name + ".trunc"); 716bdd1243dSDimitry Andric } else if (Opcode == CastInst::FPToUI || 717bdd1243dSDimitry Andric UseInst->getOpcode() == CastInst::UIToFP) { 718bdd1243dSDimitry Andric Conv = Builder.CreateZExt(IVOperand, CI->getType(), Name + ".zext"); 719bdd1243dSDimitry Andric } else { 720bdd1243dSDimitry Andric Conv = Builder.CreateSExt(IVOperand, CI->getType(), Name + ".sext"); 721bdd1243dSDimitry Andric } 722bdd1243dSDimitry Andric } else 723bdd1243dSDimitry Andric Conv = IVOperand; 724bdd1243dSDimitry Andric 725bdd1243dSDimitry Andric CI->replaceAllUsesWith(Conv); 726753f127fSDimitry Andric DeadInsts.push_back(CI); 727753f127fSDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *CI 728bdd1243dSDimitry Andric << " with: " << *Conv << '\n'); 729753f127fSDimitry Andric 730753f127fSDimitry Andric ++NumFoldedUser; 731753f127fSDimitry Andric Changed = true; 732753f127fSDimitry Andric } 733753f127fSDimitry Andric } 734753f127fSDimitry Andric 735753f127fSDimitry Andric return Changed; 736753f127fSDimitry Andric } 737753f127fSDimitry Andric 7380b57cec5SDimitry Andric /// Eliminate any operation that SCEV can prove is an identity function. 7390b57cec5SDimitry Andric bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst, 7400b57cec5SDimitry Andric Instruction *IVOperand) { 7410b57cec5SDimitry Andric if (!SE->isSCEVable(UseInst->getType()) || 74256727255SDimitry Andric UseInst->getType() != IVOperand->getType()) 74356727255SDimitry Andric return false; 74456727255SDimitry Andric 74556727255SDimitry Andric const SCEV *UseSCEV = SE->getSCEV(UseInst); 74656727255SDimitry Andric if (UseSCEV != SE->getSCEV(IVOperand)) 7470b57cec5SDimitry Andric return false; 7480b57cec5SDimitry Andric 7490b57cec5SDimitry Andric // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the 7500b57cec5SDimitry Andric // dominator tree, even if X is an operand to Y. For instance, in 7510b57cec5SDimitry Andric // 7520b57cec5SDimitry Andric // %iv = phi i32 {0,+,1} 7530b57cec5SDimitry Andric // br %cond, label %left, label %merge 7540b57cec5SDimitry Andric // 7550b57cec5SDimitry Andric // left: 7560b57cec5SDimitry Andric // %X = add i32 %iv, 0 7570b57cec5SDimitry Andric // br label %merge 7580b57cec5SDimitry Andric // 7590b57cec5SDimitry Andric // merge: 7600b57cec5SDimitry Andric // %M = phi (%X, %iv) 7610b57cec5SDimitry Andric // 7620b57cec5SDimitry Andric // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and 7630b57cec5SDimitry Andric // %M.replaceAllUsesWith(%X) would be incorrect. 7640b57cec5SDimitry Andric 7650b57cec5SDimitry Andric if (isa<PHINode>(UseInst)) 7660b57cec5SDimitry Andric // If UseInst is not a PHI node then we know that IVOperand dominates 7670b57cec5SDimitry Andric // UseInst directly from the legality of SSA. 7680b57cec5SDimitry Andric if (!DT || !DT->dominates(IVOperand, UseInst)) 7690b57cec5SDimitry Andric return false; 7700b57cec5SDimitry Andric 7710b57cec5SDimitry Andric if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand)) 7720b57cec5SDimitry Andric return false; 7730b57cec5SDimitry Andric 77456727255SDimitry Andric // Make sure the operand is not more poisonous than the instruction. 77556727255SDimitry Andric if (!impliesPoison(IVOperand, UseInst)) { 77656727255SDimitry Andric SmallVector<Instruction *> DropPoisonGeneratingInsts; 77756727255SDimitry Andric if (!SE->canReuseInstruction(UseSCEV, IVOperand, DropPoisonGeneratingInsts)) 77856727255SDimitry Andric return false; 77956727255SDimitry Andric 78056727255SDimitry Andric for (Instruction *I : DropPoisonGeneratingInsts) 7810fca6ea1SDimitry Andric I->dropPoisonGeneratingAnnotations(); 78256727255SDimitry Andric } 78356727255SDimitry Andric 7840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); 7850b57cec5SDimitry Andric 786bdd1243dSDimitry Andric SE->forgetValue(UseInst); 7870b57cec5SDimitry Andric UseInst->replaceAllUsesWith(IVOperand); 7880b57cec5SDimitry Andric ++NumElimIdentity; 7890b57cec5SDimitry Andric Changed = true; 7900b57cec5SDimitry Andric DeadInsts.emplace_back(UseInst); 7910b57cec5SDimitry Andric return true; 7920b57cec5SDimitry Andric } 7930b57cec5SDimitry Andric 79406c3fb27SDimitry Andric bool SimplifyIndvar::strengthenBinaryOp(BinaryOperator *BO, 79506c3fb27SDimitry Andric Instruction *IVOperand) { 79606c3fb27SDimitry Andric return (isa<OverflowingBinaryOperator>(BO) && 79706c3fb27SDimitry Andric strengthenOverflowingOperation(BO, IVOperand)) || 79806c3fb27SDimitry Andric (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand)); 79906c3fb27SDimitry Andric } 80006c3fb27SDimitry Andric 8010b57cec5SDimitry Andric /// Annotate BO with nsw / nuw if it provably does not signed-overflow / 8020b57cec5SDimitry Andric /// unsigned-overflow. Returns true if anything changed, false otherwise. 8030b57cec5SDimitry Andric bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO, 804753f127fSDimitry Andric Instruction *IVOperand) { 805753f127fSDimitry Andric auto Flags = SE->getStrengthenedNoWrapFlagsFromBinOp( 806fe6060f1SDimitry Andric cast<OverflowingBinaryOperator>(BO)); 8070b57cec5SDimitry Andric 808753f127fSDimitry Andric if (!Flags) 809753f127fSDimitry Andric return false; 8100b57cec5SDimitry Andric 811753f127fSDimitry Andric BO->setHasNoUnsignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNUW) == 812fe6060f1SDimitry Andric SCEV::FlagNUW); 813753f127fSDimitry Andric BO->setHasNoSignedWrap(ScalarEvolution::maskFlags(*Flags, SCEV::FlagNSW) == 814fe6060f1SDimitry Andric SCEV::FlagNSW); 8150b57cec5SDimitry Andric 816fe6060f1SDimitry Andric // The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap 817fe6060f1SDimitry Andric // flags on addrecs while performing zero/sign extensions. We could call 818fe6060f1SDimitry Andric // forgetValue() here to make sure those flags also propagate to any other 819fe6060f1SDimitry Andric // SCEV expressions based on the addrec. However, this can have pathological 820fe6060f1SDimitry Andric // compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384. 821753f127fSDimitry Andric return true; 8220b57cec5SDimitry Andric } 8230b57cec5SDimitry Andric 8240b57cec5SDimitry Andric /// Annotate the Shr in (X << IVOperand) >> C as exact using the 8250b57cec5SDimitry Andric /// information from the IV's range. Returns true if anything changed, false 8260b57cec5SDimitry Andric /// otherwise. 8270b57cec5SDimitry Andric bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO, 828753f127fSDimitry Andric Instruction *IVOperand) { 8290b57cec5SDimitry Andric if (BO->getOpcode() == Instruction::Shl) { 8300b57cec5SDimitry Andric bool Changed = false; 8310b57cec5SDimitry Andric ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand)); 8320b57cec5SDimitry Andric for (auto *U : BO->users()) { 8330b57cec5SDimitry Andric const APInt *C; 8340b57cec5SDimitry Andric if (match(U, 8350b57cec5SDimitry Andric m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) || 8360b57cec5SDimitry Andric match(U, 8370b57cec5SDimitry Andric m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) { 8380b57cec5SDimitry Andric BinaryOperator *Shr = cast<BinaryOperator>(U); 8390b57cec5SDimitry Andric if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) { 8400b57cec5SDimitry Andric Shr->setIsExact(true); 8410b57cec5SDimitry Andric Changed = true; 8420b57cec5SDimitry Andric } 8430b57cec5SDimitry Andric } 8440b57cec5SDimitry Andric } 8450b57cec5SDimitry Andric return Changed; 8460b57cec5SDimitry Andric } 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric return false; 8490b57cec5SDimitry Andric } 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric /// Add all uses of Def to the current IV's worklist. 8520fca6ea1SDimitry Andric void SimplifyIndvar::pushIVUsers( 8530fca6ea1SDimitry Andric Instruction *Def, SmallPtrSet<Instruction *, 16> &Simplified, 8540b57cec5SDimitry Andric SmallVectorImpl<std::pair<Instruction *, Instruction *>> &SimpleIVUsers) { 8550b57cec5SDimitry Andric for (User *U : Def->users()) { 8560b57cec5SDimitry Andric Instruction *UI = cast<Instruction>(U); 8570b57cec5SDimitry Andric 8580b57cec5SDimitry Andric // Avoid infinite or exponential worklist processing. 8590b57cec5SDimitry Andric // Also ensure unique worklist users. 8600b57cec5SDimitry Andric // If Def is a LoopPhi, it may not be in the Simplified set, so check for 8610b57cec5SDimitry Andric // self edges first. 8620b57cec5SDimitry Andric if (UI == Def) 8630b57cec5SDimitry Andric continue; 8640b57cec5SDimitry Andric 8650b57cec5SDimitry Andric // Only change the current Loop, do not change the other parts (e.g. other 8660b57cec5SDimitry Andric // Loops). 8670b57cec5SDimitry Andric if (!L->contains(UI)) 8680b57cec5SDimitry Andric continue; 8690b57cec5SDimitry Andric 8700b57cec5SDimitry Andric // Do not push the same instruction more than once. 8710b57cec5SDimitry Andric if (!Simplified.insert(UI).second) 8720b57cec5SDimitry Andric continue; 8730b57cec5SDimitry Andric 8740b57cec5SDimitry Andric SimpleIVUsers.push_back(std::make_pair(UI, Def)); 8750b57cec5SDimitry Andric } 8760b57cec5SDimitry Andric } 8770b57cec5SDimitry Andric 8780b57cec5SDimitry Andric /// Return true if this instruction generates a simple SCEV 8790b57cec5SDimitry Andric /// expression in terms of that IV. 8800b57cec5SDimitry Andric /// 8810b57cec5SDimitry Andric /// This is similar to IVUsers' isInteresting() but processes each instruction 8820b57cec5SDimitry Andric /// non-recursively when the operand is already known to be a simpleIVUser. 8830b57cec5SDimitry Andric /// 8840b57cec5SDimitry Andric static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { 8850b57cec5SDimitry Andric if (!SE->isSCEVable(I->getType())) 8860b57cec5SDimitry Andric return false; 8870b57cec5SDimitry Andric 8880b57cec5SDimitry Andric // Get the symbolic expression for this instruction. 8890b57cec5SDimitry Andric const SCEV *S = SE->getSCEV(I); 8900b57cec5SDimitry Andric 8910b57cec5SDimitry Andric // Only consider affine recurrences. 8920b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); 8930b57cec5SDimitry Andric if (AR && AR->getLoop() == L) 8940b57cec5SDimitry Andric return true; 8950b57cec5SDimitry Andric 8960b57cec5SDimitry Andric return false; 8970b57cec5SDimitry Andric } 8980b57cec5SDimitry Andric 8990b57cec5SDimitry Andric /// Iteratively perform simplification on a worklist of users 9000b57cec5SDimitry Andric /// of the specified induction variable. Each successive simplification may push 9010b57cec5SDimitry Andric /// more users which may themselves be candidates for simplification. 9020b57cec5SDimitry Andric /// 9030b57cec5SDimitry Andric /// This algorithm does not require IVUsers analysis. Instead, it simplifies 9040b57cec5SDimitry Andric /// instructions in-place during analysis. Rather than rewriting induction 9050b57cec5SDimitry Andric /// variables bottom-up from their users, it transforms a chain of IVUsers 9060b57cec5SDimitry Andric /// top-down, updating the IR only when it encounters a clear optimization 9070b57cec5SDimitry Andric /// opportunity. 9080b57cec5SDimitry Andric /// 9090b57cec5SDimitry Andric /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. 9100b57cec5SDimitry Andric /// 9110b57cec5SDimitry Andric void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { 9120b57cec5SDimitry Andric if (!SE->isSCEVable(CurrIV->getType())) 9130b57cec5SDimitry Andric return; 9140b57cec5SDimitry Andric 9150b57cec5SDimitry Andric // Instructions processed by SimplifyIndvar for CurrIV. 9160b57cec5SDimitry Andric SmallPtrSet<Instruction*,16> Simplified; 9170b57cec5SDimitry Andric 9180b57cec5SDimitry Andric // Use-def pairs if IV users waiting to be processed for CurrIV. 9190b57cec5SDimitry Andric SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric // Push users of the current LoopPhi. In rare cases, pushIVUsers may be 9220b57cec5SDimitry Andric // called multiple times for the same LoopPhi. This is the proper thing to 9230b57cec5SDimitry Andric // do for loop header phis that use each other. 9240fca6ea1SDimitry Andric pushIVUsers(CurrIV, Simplified, SimpleIVUsers); 9250b57cec5SDimitry Andric 9260b57cec5SDimitry Andric while (!SimpleIVUsers.empty()) { 9270b57cec5SDimitry Andric std::pair<Instruction*, Instruction*> UseOper = 9280b57cec5SDimitry Andric SimpleIVUsers.pop_back_val(); 9290b57cec5SDimitry Andric Instruction *UseInst = UseOper.first; 9300b57cec5SDimitry Andric 9310b57cec5SDimitry Andric // If a user of the IndVar is trivially dead, we prefer just to mark it dead 9320b57cec5SDimitry Andric // rather than try to do some complex analysis or transformation (such as 9330b57cec5SDimitry Andric // widening) basing on it. 9340b57cec5SDimitry Andric // TODO: Propagate TLI and pass it here to handle more cases. 9350b57cec5SDimitry Andric if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) { 9360b57cec5SDimitry Andric DeadInsts.emplace_back(UseInst); 9370b57cec5SDimitry Andric continue; 9380b57cec5SDimitry Andric } 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric // Bypass back edges to avoid extra work. 9410b57cec5SDimitry Andric if (UseInst == CurrIV) continue; 9420b57cec5SDimitry Andric 9430b57cec5SDimitry Andric // Try to replace UseInst with a loop invariant before any other 9440b57cec5SDimitry Andric // simplifications. 9450b57cec5SDimitry Andric if (replaceIVUserWithLoopInvariant(UseInst)) 9460b57cec5SDimitry Andric continue; 9470b57cec5SDimitry Andric 9485f757f3fSDimitry Andric // Go further for the bitcast 'prtoint ptr to i64' or if the cast is done 9495f757f3fSDimitry Andric // by truncation 9505f757f3fSDimitry Andric if ((isa<PtrToIntInst>(UseInst)) || (isa<TruncInst>(UseInst))) 95106c3fb27SDimitry Andric for (Use &U : UseInst->uses()) { 95206c3fb27SDimitry Andric Instruction *User = cast<Instruction>(U.getUser()); 95306c3fb27SDimitry Andric if (replaceIVUserWithLoopInvariant(User)) 95406c3fb27SDimitry Andric break; // done replacing 95506c3fb27SDimitry Andric } 95606c3fb27SDimitry Andric 9570b57cec5SDimitry Andric Instruction *IVOperand = UseOper.second; 9580b57cec5SDimitry Andric for (unsigned N = 0; IVOperand; ++N) { 9590b57cec5SDimitry Andric assert(N <= Simplified.size() && "runaway iteration"); 96081ad6265SDimitry Andric (void) N; 9610b57cec5SDimitry Andric 9620b57cec5SDimitry Andric Value *NewOper = foldIVUser(UseInst, IVOperand); 9630b57cec5SDimitry Andric if (!NewOper) 9640b57cec5SDimitry Andric break; // done folding 9650b57cec5SDimitry Andric IVOperand = dyn_cast<Instruction>(NewOper); 9660b57cec5SDimitry Andric } 9670b57cec5SDimitry Andric if (!IVOperand) 9680b57cec5SDimitry Andric continue; 9690b57cec5SDimitry Andric 9700b57cec5SDimitry Andric if (eliminateIVUser(UseInst, IVOperand)) { 9710fca6ea1SDimitry Andric pushIVUsers(IVOperand, Simplified, SimpleIVUsers); 9720b57cec5SDimitry Andric continue; 9730b57cec5SDimitry Andric } 9740b57cec5SDimitry Andric 9750b57cec5SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) { 97606c3fb27SDimitry Andric if (strengthenBinaryOp(BO, IVOperand)) { 9770b57cec5SDimitry Andric // re-queue uses of the now modified binary operator and fall 9780b57cec5SDimitry Andric // through to the checks that remain. 9790fca6ea1SDimitry Andric pushIVUsers(IVOperand, Simplified, SimpleIVUsers); 9800b57cec5SDimitry Andric } 9810b57cec5SDimitry Andric } 9820b57cec5SDimitry Andric 983753f127fSDimitry Andric // Try to use integer induction for FPToSI of float induction directly. 984753f127fSDimitry Andric if (replaceFloatIVWithIntegerIV(UseInst)) { 985753f127fSDimitry Andric // Re-queue the potentially new direct uses of IVOperand. 9860fca6ea1SDimitry Andric pushIVUsers(IVOperand, Simplified, SimpleIVUsers); 987753f127fSDimitry Andric continue; 988753f127fSDimitry Andric } 989753f127fSDimitry Andric 9900b57cec5SDimitry Andric CastInst *Cast = dyn_cast<CastInst>(UseInst); 9910b57cec5SDimitry Andric if (V && Cast) { 9920b57cec5SDimitry Andric V->visitCast(Cast); 9930b57cec5SDimitry Andric continue; 9940b57cec5SDimitry Andric } 9950b57cec5SDimitry Andric if (isSimpleIVUser(UseInst, L, SE)) { 9960fca6ea1SDimitry Andric pushIVUsers(UseInst, Simplified, SimpleIVUsers); 9970b57cec5SDimitry Andric } 9980b57cec5SDimitry Andric } 9990b57cec5SDimitry Andric } 10000b57cec5SDimitry Andric 10010b57cec5SDimitry Andric namespace llvm { 10020b57cec5SDimitry Andric 10030b57cec5SDimitry Andric void IVVisitor::anchor() { } 10040b57cec5SDimitry Andric 10050b57cec5SDimitry Andric /// Simplify instructions that use this induction variable 10060b57cec5SDimitry Andric /// by using ScalarEvolution to analyze the IV's recurrence. 10070fca6ea1SDimitry Andric /// Returns a pair where the first entry indicates that the function makes 10080fca6ea1SDimitry Andric /// changes and the second entry indicates that it introduced new opportunities 10090fca6ea1SDimitry Andric /// for loop unswitching. 10100fca6ea1SDimitry Andric std::pair<bool, bool> simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, 10110fca6ea1SDimitry Andric DominatorTree *DT, LoopInfo *LI, 10120fca6ea1SDimitry Andric const TargetTransformInfo *TTI, 10135ffd83dbSDimitry Andric SmallVectorImpl<WeakTrackingVH> &Dead, 10140b57cec5SDimitry Andric SCEVExpander &Rewriter, IVVisitor *V) { 10155ffd83dbSDimitry Andric SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI, 10165ffd83dbSDimitry Andric Rewriter, Dead); 10170b57cec5SDimitry Andric SIV.simplifyUsers(CurrIV, V); 10180fca6ea1SDimitry Andric return {SIV.hasChanged(), SIV.runUnswitching()}; 10190b57cec5SDimitry Andric } 10200b57cec5SDimitry Andric 10210b57cec5SDimitry Andric /// Simplify users of induction variables within this 10220b57cec5SDimitry Andric /// loop. This does not actually change or add IVs. 10230b57cec5SDimitry Andric bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, 10245ffd83dbSDimitry Andric LoopInfo *LI, const TargetTransformInfo *TTI, 10255ffd83dbSDimitry Andric SmallVectorImpl<WeakTrackingVH> &Dead) { 10260b57cec5SDimitry Andric SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars"); 10270b57cec5SDimitry Andric #ifndef NDEBUG 10280b57cec5SDimitry Andric Rewriter.setDebugType(DEBUG_TYPE); 10290b57cec5SDimitry Andric #endif 10300b57cec5SDimitry Andric bool Changed = false; 10310b57cec5SDimitry Andric for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 10320fca6ea1SDimitry Andric const auto &[C, _] = 10335ffd83dbSDimitry Andric simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter); 10340fca6ea1SDimitry Andric Changed |= C; 10350b57cec5SDimitry Andric } 10360b57cec5SDimitry Andric return Changed; 10370b57cec5SDimitry Andric } 10380b57cec5SDimitry Andric 10390b57cec5SDimitry Andric } // namespace llvm 1040e8d8bef9SDimitry Andric 1041349cc55cSDimitry Andric namespace { 1042e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 1043e8d8bef9SDimitry Andric // Widen Induction Variables - Extend the width of an IV to cover its 1044e8d8bef9SDimitry Andric // widest uses. 1045e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 1046e8d8bef9SDimitry Andric 1047e8d8bef9SDimitry Andric class WidenIV { 1048e8d8bef9SDimitry Andric // Parameters 1049e8d8bef9SDimitry Andric PHINode *OrigPhi; 1050e8d8bef9SDimitry Andric Type *WideType; 1051e8d8bef9SDimitry Andric 1052e8d8bef9SDimitry Andric // Context 1053e8d8bef9SDimitry Andric LoopInfo *LI; 1054e8d8bef9SDimitry Andric Loop *L; 1055e8d8bef9SDimitry Andric ScalarEvolution *SE; 1056e8d8bef9SDimitry Andric DominatorTree *DT; 1057e8d8bef9SDimitry Andric 1058e8d8bef9SDimitry Andric // Does the module have any calls to the llvm.experimental.guard intrinsic 1059e8d8bef9SDimitry Andric // at all? If not we can avoid scanning instructions looking for guards. 1060e8d8bef9SDimitry Andric bool HasGuards; 1061e8d8bef9SDimitry Andric 1062e8d8bef9SDimitry Andric bool UsePostIncrementRanges; 1063e8d8bef9SDimitry Andric 1064e8d8bef9SDimitry Andric // Statistics 1065e8d8bef9SDimitry Andric unsigned NumElimExt = 0; 1066e8d8bef9SDimitry Andric unsigned NumWidened = 0; 1067e8d8bef9SDimitry Andric 1068e8d8bef9SDimitry Andric // Result 1069e8d8bef9SDimitry Andric PHINode *WidePhi = nullptr; 1070e8d8bef9SDimitry Andric Instruction *WideInc = nullptr; 1071e8d8bef9SDimitry Andric const SCEV *WideIncExpr = nullptr; 1072e8d8bef9SDimitry Andric SmallVectorImpl<WeakTrackingVH> &DeadInsts; 1073e8d8bef9SDimitry Andric 1074e8d8bef9SDimitry Andric SmallPtrSet<Instruction *,16> Widened; 1075e8d8bef9SDimitry Andric 1076fcaf7f86SDimitry Andric enum class ExtendKind { Zero, Sign, Unknown }; 1077e8d8bef9SDimitry Andric 1078e8d8bef9SDimitry Andric // A map tracking the kind of extension used to widen each narrow IV 1079e8d8bef9SDimitry Andric // and narrow IV user. 1080e8d8bef9SDimitry Andric // Key: pointer to a narrow IV or IV user. 1081e8d8bef9SDimitry Andric // Value: the kind of extension used to widen this Instruction. 1082e8d8bef9SDimitry Andric DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap; 1083e8d8bef9SDimitry Andric 1084e8d8bef9SDimitry Andric using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>; 1085e8d8bef9SDimitry Andric 1086e8d8bef9SDimitry Andric // A map with control-dependent ranges for post increment IV uses. The key is 1087e8d8bef9SDimitry Andric // a pair of IV def and a use of this def denoting the context. The value is 1088e8d8bef9SDimitry Andric // a ConstantRange representing possible values of the def at the given 1089e8d8bef9SDimitry Andric // context. 1090e8d8bef9SDimitry Andric DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos; 1091e8d8bef9SDimitry Andric 1092bdd1243dSDimitry Andric std::optional<ConstantRange> getPostIncRangeInfo(Value *Def, 1093e8d8bef9SDimitry Andric Instruction *UseI) { 1094e8d8bef9SDimitry Andric DefUserPair Key(Def, UseI); 1095e8d8bef9SDimitry Andric auto It = PostIncRangeInfos.find(Key); 1096e8d8bef9SDimitry Andric return It == PostIncRangeInfos.end() 1097bdd1243dSDimitry Andric ? std::optional<ConstantRange>(std::nullopt) 1098bdd1243dSDimitry Andric : std::optional<ConstantRange>(It->second); 1099e8d8bef9SDimitry Andric } 1100e8d8bef9SDimitry Andric 1101e8d8bef9SDimitry Andric void calculatePostIncRanges(PHINode *OrigPhi); 1102e8d8bef9SDimitry Andric void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser); 1103e8d8bef9SDimitry Andric 1104e8d8bef9SDimitry Andric void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) { 1105e8d8bef9SDimitry Andric DefUserPair Key(Def, UseI); 1106e8d8bef9SDimitry Andric auto It = PostIncRangeInfos.find(Key); 1107e8d8bef9SDimitry Andric if (It == PostIncRangeInfos.end()) 1108e8d8bef9SDimitry Andric PostIncRangeInfos.insert({Key, R}); 1109e8d8bef9SDimitry Andric else 1110e8d8bef9SDimitry Andric It->second = R.intersectWith(It->second); 1111e8d8bef9SDimitry Andric } 1112e8d8bef9SDimitry Andric 1113e8d8bef9SDimitry Andric public: 1114e8d8bef9SDimitry Andric /// Record a link in the Narrow IV def-use chain along with the WideIV that 1115e8d8bef9SDimitry Andric /// computes the same value as the Narrow IV def. This avoids caching Use* 1116e8d8bef9SDimitry Andric /// pointers. 1117e8d8bef9SDimitry Andric struct NarrowIVDefUse { 1118e8d8bef9SDimitry Andric Instruction *NarrowDef = nullptr; 1119e8d8bef9SDimitry Andric Instruction *NarrowUse = nullptr; 1120e8d8bef9SDimitry Andric Instruction *WideDef = nullptr; 1121e8d8bef9SDimitry Andric 1122e8d8bef9SDimitry Andric // True if the narrow def is never negative. Tracking this information lets 1123e8d8bef9SDimitry Andric // us use a sign extension instead of a zero extension or vice versa, when 1124e8d8bef9SDimitry Andric // profitable and legal. 1125e8d8bef9SDimitry Andric bool NeverNegative = false; 1126e8d8bef9SDimitry Andric 1127e8d8bef9SDimitry Andric NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD, 1128e8d8bef9SDimitry Andric bool NeverNegative) 1129e8d8bef9SDimitry Andric : NarrowDef(ND), NarrowUse(NU), WideDef(WD), 1130e8d8bef9SDimitry Andric NeverNegative(NeverNegative) {} 1131e8d8bef9SDimitry Andric }; 1132e8d8bef9SDimitry Andric 1133e8d8bef9SDimitry Andric WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv, 1134e8d8bef9SDimitry Andric DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI, 1135e8d8bef9SDimitry Andric bool HasGuards, bool UsePostIncrementRanges = true); 1136e8d8bef9SDimitry Andric 1137e8d8bef9SDimitry Andric PHINode *createWideIV(SCEVExpander &Rewriter); 1138e8d8bef9SDimitry Andric 1139e8d8bef9SDimitry Andric unsigned getNumElimExt() { return NumElimExt; }; 1140e8d8bef9SDimitry Andric unsigned getNumWidened() { return NumWidened; }; 1141e8d8bef9SDimitry Andric 1142e8d8bef9SDimitry Andric protected: 1143e8d8bef9SDimitry Andric Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned, 1144e8d8bef9SDimitry Andric Instruction *Use); 1145e8d8bef9SDimitry Andric 1146e8d8bef9SDimitry Andric Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR); 1147e8d8bef9SDimitry Andric Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU, 1148e8d8bef9SDimitry Andric const SCEVAddRecExpr *WideAR); 1149e8d8bef9SDimitry Andric Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU); 1150e8d8bef9SDimitry Andric 1151e8d8bef9SDimitry Andric ExtendKind getExtendKind(Instruction *I); 1152e8d8bef9SDimitry Andric 1153e8d8bef9SDimitry Andric using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>; 1154e8d8bef9SDimitry Andric 1155e8d8bef9SDimitry Andric WidenedRecTy getWideRecurrence(NarrowIVDefUse DU); 1156e8d8bef9SDimitry Andric 1157e8d8bef9SDimitry Andric WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU); 1158e8d8bef9SDimitry Andric 1159e8d8bef9SDimitry Andric const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1160e8d8bef9SDimitry Andric unsigned OpCode) const; 1161e8d8bef9SDimitry Andric 11620fca6ea1SDimitry Andric Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter, 11630fca6ea1SDimitry Andric PHINode *OrigPhi, PHINode *WidePhi); 11640fca6ea1SDimitry Andric void truncateIVUse(NarrowIVDefUse DU); 1165e8d8bef9SDimitry Andric 1166e8d8bef9SDimitry Andric bool widenLoopCompare(NarrowIVDefUse DU); 1167e8d8bef9SDimitry Andric bool widenWithVariantUse(NarrowIVDefUse DU); 1168e8d8bef9SDimitry Andric 1169e8d8bef9SDimitry Andric void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef); 1170e8d8bef9SDimitry Andric 1171e8d8bef9SDimitry Andric private: 1172e8d8bef9SDimitry Andric SmallVector<NarrowIVDefUse, 8> NarrowIVUsers; 1173e8d8bef9SDimitry Andric }; 1174349cc55cSDimitry Andric } // namespace 1175e8d8bef9SDimitry Andric 1176e8d8bef9SDimitry Andric /// Determine the insertion point for this user. By default, insert immediately 1177e8d8bef9SDimitry Andric /// before the user. SCEVExpander or LICM will hoist loop invariants out of the 1178e8d8bef9SDimitry Andric /// loop. For PHI nodes, there may be multiple uses, so compute the nearest 1179e8d8bef9SDimitry Andric /// common dominator for the incoming blocks. A nullptr can be returned if no 1180e8d8bef9SDimitry Andric /// viable location is found: it may happen if User is a PHI and Def only comes 1181e8d8bef9SDimitry Andric /// to this PHI from unreachable blocks. 1182e8d8bef9SDimitry Andric static Instruction *getInsertPointForUses(Instruction *User, Value *Def, 1183e8d8bef9SDimitry Andric DominatorTree *DT, LoopInfo *LI) { 1184e8d8bef9SDimitry Andric PHINode *PHI = dyn_cast<PHINode>(User); 1185e8d8bef9SDimitry Andric if (!PHI) 1186e8d8bef9SDimitry Andric return User; 1187e8d8bef9SDimitry Andric 1188e8d8bef9SDimitry Andric Instruction *InsertPt = nullptr; 1189e8d8bef9SDimitry Andric for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) { 1190e8d8bef9SDimitry Andric if (PHI->getIncomingValue(i) != Def) 1191e8d8bef9SDimitry Andric continue; 1192e8d8bef9SDimitry Andric 1193e8d8bef9SDimitry Andric BasicBlock *InsertBB = PHI->getIncomingBlock(i); 1194e8d8bef9SDimitry Andric 1195e8d8bef9SDimitry Andric if (!DT->isReachableFromEntry(InsertBB)) 1196e8d8bef9SDimitry Andric continue; 1197e8d8bef9SDimitry Andric 1198e8d8bef9SDimitry Andric if (!InsertPt) { 1199e8d8bef9SDimitry Andric InsertPt = InsertBB->getTerminator(); 1200e8d8bef9SDimitry Andric continue; 1201e8d8bef9SDimitry Andric } 1202e8d8bef9SDimitry Andric InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB); 1203e8d8bef9SDimitry Andric InsertPt = InsertBB->getTerminator(); 1204e8d8bef9SDimitry Andric } 1205e8d8bef9SDimitry Andric 1206e8d8bef9SDimitry Andric // If we have skipped all inputs, it means that Def only comes to Phi from 1207e8d8bef9SDimitry Andric // unreachable blocks. 1208e8d8bef9SDimitry Andric if (!InsertPt) 1209e8d8bef9SDimitry Andric return nullptr; 1210e8d8bef9SDimitry Andric 1211e8d8bef9SDimitry Andric auto *DefI = dyn_cast<Instruction>(Def); 1212e8d8bef9SDimitry Andric if (!DefI) 1213e8d8bef9SDimitry Andric return InsertPt; 1214e8d8bef9SDimitry Andric 1215e8d8bef9SDimitry Andric assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses"); 1216e8d8bef9SDimitry Andric 1217e8d8bef9SDimitry Andric auto *L = LI->getLoopFor(DefI->getParent()); 1218e8d8bef9SDimitry Andric assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent()))); 1219e8d8bef9SDimitry Andric 1220e8d8bef9SDimitry Andric for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom()) 1221e8d8bef9SDimitry Andric if (LI->getLoopFor(DTN->getBlock()) == L) 1222e8d8bef9SDimitry Andric return DTN->getBlock()->getTerminator(); 1223e8d8bef9SDimitry Andric 1224e8d8bef9SDimitry Andric llvm_unreachable("DefI dominates InsertPt!"); 1225e8d8bef9SDimitry Andric } 1226e8d8bef9SDimitry Andric 1227e8d8bef9SDimitry Andric WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv, 1228e8d8bef9SDimitry Andric DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI, 1229e8d8bef9SDimitry Andric bool HasGuards, bool UsePostIncrementRanges) 1230e8d8bef9SDimitry Andric : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo), 1231e8d8bef9SDimitry Andric L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree), 1232e8d8bef9SDimitry Andric HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges), 1233e8d8bef9SDimitry Andric DeadInsts(DI) { 1234e8d8bef9SDimitry Andric assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV"); 1235fcaf7f86SDimitry Andric ExtendKindMap[OrigPhi] = WI.IsSigned ? ExtendKind::Sign : ExtendKind::Zero; 1236e8d8bef9SDimitry Andric } 1237e8d8bef9SDimitry Andric 1238e8d8bef9SDimitry Andric Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType, 1239e8d8bef9SDimitry Andric bool IsSigned, Instruction *Use) { 1240e8d8bef9SDimitry Andric // Set the debug location and conservative insertion point. 1241e8d8bef9SDimitry Andric IRBuilder<> Builder(Use); 1242e8d8bef9SDimitry Andric // Hoist the insertion point into loop preheaders as far as possible. 1243e8d8bef9SDimitry Andric for (const Loop *L = LI->getLoopFor(Use->getParent()); 1244e8d8bef9SDimitry Andric L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper); 1245e8d8bef9SDimitry Andric L = L->getParentLoop()) 1246e8d8bef9SDimitry Andric Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator()); 1247e8d8bef9SDimitry Andric 1248e8d8bef9SDimitry Andric return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) : 1249e8d8bef9SDimitry Andric Builder.CreateZExt(NarrowOper, WideType); 1250e8d8bef9SDimitry Andric } 1251e8d8bef9SDimitry Andric 1252e8d8bef9SDimitry Andric /// Instantiate a wide operation to replace a narrow operation. This only needs 1253e8d8bef9SDimitry Andric /// to handle operations that can evaluation to SCEVAddRec. It can safely return 1254e8d8bef9SDimitry Andric /// 0 for any operation we decide not to clone. 1255e8d8bef9SDimitry Andric Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU, 1256e8d8bef9SDimitry Andric const SCEVAddRecExpr *WideAR) { 1257e8d8bef9SDimitry Andric unsigned Opcode = DU.NarrowUse->getOpcode(); 1258e8d8bef9SDimitry Andric switch (Opcode) { 1259e8d8bef9SDimitry Andric default: 1260e8d8bef9SDimitry Andric return nullptr; 1261e8d8bef9SDimitry Andric case Instruction::Add: 1262e8d8bef9SDimitry Andric case Instruction::Mul: 1263e8d8bef9SDimitry Andric case Instruction::UDiv: 1264e8d8bef9SDimitry Andric case Instruction::Sub: 1265e8d8bef9SDimitry Andric return cloneArithmeticIVUser(DU, WideAR); 1266e8d8bef9SDimitry Andric 1267e8d8bef9SDimitry Andric case Instruction::And: 1268e8d8bef9SDimitry Andric case Instruction::Or: 1269e8d8bef9SDimitry Andric case Instruction::Xor: 1270e8d8bef9SDimitry Andric case Instruction::Shl: 1271e8d8bef9SDimitry Andric case Instruction::LShr: 1272e8d8bef9SDimitry Andric case Instruction::AShr: 1273e8d8bef9SDimitry Andric return cloneBitwiseIVUser(DU); 1274e8d8bef9SDimitry Andric } 1275e8d8bef9SDimitry Andric } 1276e8d8bef9SDimitry Andric 1277e8d8bef9SDimitry Andric Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) { 1278e8d8bef9SDimitry Andric Instruction *NarrowUse = DU.NarrowUse; 1279e8d8bef9SDimitry Andric Instruction *NarrowDef = DU.NarrowDef; 1280e8d8bef9SDimitry Andric Instruction *WideDef = DU.WideDef; 1281e8d8bef9SDimitry Andric 1282e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n"); 1283e8d8bef9SDimitry Andric 1284e8d8bef9SDimitry Andric // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything 1285e8d8bef9SDimitry Andric // about the narrow operand yet so must insert a [sz]ext. It is probably loop 1286e8d8bef9SDimitry Andric // invariant and will be folded or hoisted. If it actually comes from a 1287e8d8bef9SDimitry Andric // widened IV, it should be removed during a future call to widenIVUse. 1288fcaf7f86SDimitry Andric bool IsSigned = getExtendKind(NarrowDef) == ExtendKind::Sign; 1289e8d8bef9SDimitry Andric Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1290e8d8bef9SDimitry Andric ? WideDef 1291e8d8bef9SDimitry Andric : createExtendInst(NarrowUse->getOperand(0), WideType, 1292e8d8bef9SDimitry Andric IsSigned, NarrowUse); 1293e8d8bef9SDimitry Andric Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1294e8d8bef9SDimitry Andric ? WideDef 1295e8d8bef9SDimitry Andric : createExtendInst(NarrowUse->getOperand(1), WideType, 1296e8d8bef9SDimitry Andric IsSigned, NarrowUse); 1297e8d8bef9SDimitry Andric 1298e8d8bef9SDimitry Andric auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1299e8d8bef9SDimitry Andric auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1300e8d8bef9SDimitry Andric NarrowBO->getName()); 1301e8d8bef9SDimitry Andric IRBuilder<> Builder(NarrowUse); 1302e8d8bef9SDimitry Andric Builder.Insert(WideBO); 1303e8d8bef9SDimitry Andric WideBO->copyIRFlags(NarrowBO); 1304e8d8bef9SDimitry Andric return WideBO; 1305e8d8bef9SDimitry Andric } 1306e8d8bef9SDimitry Andric 1307e8d8bef9SDimitry Andric Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU, 1308e8d8bef9SDimitry Andric const SCEVAddRecExpr *WideAR) { 1309e8d8bef9SDimitry Andric Instruction *NarrowUse = DU.NarrowUse; 1310e8d8bef9SDimitry Andric Instruction *NarrowDef = DU.NarrowDef; 1311e8d8bef9SDimitry Andric Instruction *WideDef = DU.WideDef; 1312e8d8bef9SDimitry Andric 1313e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n"); 1314e8d8bef9SDimitry Andric 1315e8d8bef9SDimitry Andric unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1; 1316e8d8bef9SDimitry Andric 1317e8d8bef9SDimitry Andric // We're trying to find X such that 1318e8d8bef9SDimitry Andric // 1319e8d8bef9SDimitry Andric // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X 1320e8d8bef9SDimitry Andric // 1321e8d8bef9SDimitry Andric // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef), 1322e8d8bef9SDimitry Andric // and check using SCEV if any of them are correct. 1323e8d8bef9SDimitry Andric 1324e8d8bef9SDimitry Andric // Returns true if extending NonIVNarrowDef according to `SignExt` is a 1325e8d8bef9SDimitry Andric // correct solution to X. 1326e8d8bef9SDimitry Andric auto GuessNonIVOperand = [&](bool SignExt) { 1327e8d8bef9SDimitry Andric const SCEV *WideLHS; 1328e8d8bef9SDimitry Andric const SCEV *WideRHS; 1329e8d8bef9SDimitry Andric 1330e8d8bef9SDimitry Andric auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) { 1331e8d8bef9SDimitry Andric if (SignExt) 1332e8d8bef9SDimitry Andric return SE->getSignExtendExpr(S, Ty); 1333e8d8bef9SDimitry Andric return SE->getZeroExtendExpr(S, Ty); 1334e8d8bef9SDimitry Andric }; 1335e8d8bef9SDimitry Andric 1336e8d8bef9SDimitry Andric if (IVOpIdx == 0) { 1337e8d8bef9SDimitry Andric WideLHS = SE->getSCEV(WideDef); 1338e8d8bef9SDimitry Andric const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1)); 1339e8d8bef9SDimitry Andric WideRHS = GetExtend(NarrowRHS, WideType); 1340e8d8bef9SDimitry Andric } else { 1341e8d8bef9SDimitry Andric const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0)); 1342e8d8bef9SDimitry Andric WideLHS = GetExtend(NarrowLHS, WideType); 1343e8d8bef9SDimitry Andric WideRHS = SE->getSCEV(WideDef); 1344e8d8bef9SDimitry Andric } 1345e8d8bef9SDimitry Andric 1346e8d8bef9SDimitry Andric // WideUse is "WideDef `op.wide` X" as described in the comment. 1347e8d8bef9SDimitry Andric const SCEV *WideUse = 1348e8d8bef9SDimitry Andric getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode()); 1349e8d8bef9SDimitry Andric 1350e8d8bef9SDimitry Andric return WideUse == WideAR; 1351e8d8bef9SDimitry Andric }; 1352e8d8bef9SDimitry Andric 1353fcaf7f86SDimitry Andric bool SignExtend = getExtendKind(NarrowDef) == ExtendKind::Sign; 1354e8d8bef9SDimitry Andric if (!GuessNonIVOperand(SignExtend)) { 1355e8d8bef9SDimitry Andric SignExtend = !SignExtend; 1356e8d8bef9SDimitry Andric if (!GuessNonIVOperand(SignExtend)) 1357e8d8bef9SDimitry Andric return nullptr; 1358e8d8bef9SDimitry Andric } 1359e8d8bef9SDimitry Andric 1360e8d8bef9SDimitry Andric Value *LHS = (NarrowUse->getOperand(0) == NarrowDef) 1361e8d8bef9SDimitry Andric ? WideDef 1362e8d8bef9SDimitry Andric : createExtendInst(NarrowUse->getOperand(0), WideType, 1363e8d8bef9SDimitry Andric SignExtend, NarrowUse); 1364e8d8bef9SDimitry Andric Value *RHS = (NarrowUse->getOperand(1) == NarrowDef) 1365e8d8bef9SDimitry Andric ? WideDef 1366e8d8bef9SDimitry Andric : createExtendInst(NarrowUse->getOperand(1), WideType, 1367e8d8bef9SDimitry Andric SignExtend, NarrowUse); 1368e8d8bef9SDimitry Andric 1369e8d8bef9SDimitry Andric auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1370e8d8bef9SDimitry Andric auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1371e8d8bef9SDimitry Andric NarrowBO->getName()); 1372e8d8bef9SDimitry Andric 1373e8d8bef9SDimitry Andric IRBuilder<> Builder(NarrowUse); 1374e8d8bef9SDimitry Andric Builder.Insert(WideBO); 1375e8d8bef9SDimitry Andric WideBO->copyIRFlags(NarrowBO); 1376e8d8bef9SDimitry Andric return WideBO; 1377e8d8bef9SDimitry Andric } 1378e8d8bef9SDimitry Andric 1379e8d8bef9SDimitry Andric WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) { 1380e8d8bef9SDimitry Andric auto It = ExtendKindMap.find(I); 1381e8d8bef9SDimitry Andric assert(It != ExtendKindMap.end() && "Instruction not yet extended!"); 1382e8d8bef9SDimitry Andric return It->second; 1383e8d8bef9SDimitry Andric } 1384e8d8bef9SDimitry Andric 1385e8d8bef9SDimitry Andric const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS, 1386e8d8bef9SDimitry Andric unsigned OpCode) const { 1387e8d8bef9SDimitry Andric switch (OpCode) { 1388e8d8bef9SDimitry Andric case Instruction::Add: 1389e8d8bef9SDimitry Andric return SE->getAddExpr(LHS, RHS); 1390e8d8bef9SDimitry Andric case Instruction::Sub: 1391e8d8bef9SDimitry Andric return SE->getMinusSCEV(LHS, RHS); 1392e8d8bef9SDimitry Andric case Instruction::Mul: 1393e8d8bef9SDimitry Andric return SE->getMulExpr(LHS, RHS); 1394e8d8bef9SDimitry Andric case Instruction::UDiv: 1395e8d8bef9SDimitry Andric return SE->getUDivExpr(LHS, RHS); 1396e8d8bef9SDimitry Andric default: 1397e8d8bef9SDimitry Andric llvm_unreachable("Unsupported opcode."); 1398e8d8bef9SDimitry Andric }; 1399e8d8bef9SDimitry Andric } 1400e8d8bef9SDimitry Andric 14010fca6ea1SDimitry Andric namespace { 14020fca6ea1SDimitry Andric 14030fca6ea1SDimitry Andric // Represents a interesting integer binary operation for 14040fca6ea1SDimitry Andric // getExtendedOperandRecurrence. This may be a shl that is being treated as a 14050fca6ea1SDimitry Andric // multiply or a 'or disjoint' that is being treated as 'add nsw nuw'. 14060fca6ea1SDimitry Andric struct BinaryOp { 14070fca6ea1SDimitry Andric unsigned Opcode; 14080fca6ea1SDimitry Andric std::array<Value *, 2> Operands; 14090fca6ea1SDimitry Andric bool IsNSW = false; 14100fca6ea1SDimitry Andric bool IsNUW = false; 14110fca6ea1SDimitry Andric 14120fca6ea1SDimitry Andric explicit BinaryOp(Instruction *Op) 14130fca6ea1SDimitry Andric : Opcode(Op->getOpcode()), 14140fca6ea1SDimitry Andric Operands({Op->getOperand(0), Op->getOperand(1)}) { 14150fca6ea1SDimitry Andric if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 14160fca6ea1SDimitry Andric IsNSW = OBO->hasNoSignedWrap(); 14170fca6ea1SDimitry Andric IsNUW = OBO->hasNoUnsignedWrap(); 14180fca6ea1SDimitry Andric } 14190fca6ea1SDimitry Andric } 14200fca6ea1SDimitry Andric 14210fca6ea1SDimitry Andric explicit BinaryOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS, 14220fca6ea1SDimitry Andric bool IsNSW = false, bool IsNUW = false) 14230fca6ea1SDimitry Andric : Opcode(Opcode), Operands({LHS, RHS}), IsNSW(IsNSW), IsNUW(IsNUW) {} 14240fca6ea1SDimitry Andric }; 14250fca6ea1SDimitry Andric 14260fca6ea1SDimitry Andric } // end anonymous namespace 14270fca6ea1SDimitry Andric 14280fca6ea1SDimitry Andric static std::optional<BinaryOp> matchBinaryOp(Instruction *Op) { 14290fca6ea1SDimitry Andric switch (Op->getOpcode()) { 14300fca6ea1SDimitry Andric case Instruction::Add: 14310fca6ea1SDimitry Andric case Instruction::Sub: 14320fca6ea1SDimitry Andric case Instruction::Mul: 14330fca6ea1SDimitry Andric return BinaryOp(Op); 14340fca6ea1SDimitry Andric case Instruction::Or: { 14350fca6ea1SDimitry Andric // Convert or disjoint into add nuw nsw. 14360fca6ea1SDimitry Andric if (cast<PossiblyDisjointInst>(Op)->isDisjoint()) 14370fca6ea1SDimitry Andric return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1), 14380fca6ea1SDimitry Andric /*IsNSW=*/true, /*IsNUW=*/true); 14390fca6ea1SDimitry Andric break; 14400fca6ea1SDimitry Andric } 14410fca6ea1SDimitry Andric case Instruction::Shl: { 14420fca6ea1SDimitry Andric if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 14430fca6ea1SDimitry Andric unsigned BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 14440fca6ea1SDimitry Andric 14450fca6ea1SDimitry Andric // If the shift count is not less than the bitwidth, the result of 14460fca6ea1SDimitry Andric // the shift is undefined. Don't try to analyze it, because the 14470fca6ea1SDimitry Andric // resolution chosen here may differ from the resolution chosen in 14480fca6ea1SDimitry Andric // other parts of the compiler. 14490fca6ea1SDimitry Andric if (SA->getValue().ult(BitWidth)) { 14500fca6ea1SDimitry Andric // We can safely preserve the nuw flag in all cases. It's also safe to 14510fca6ea1SDimitry Andric // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 14520fca6ea1SDimitry Andric // requires special handling. It can be preserved as long as we're not 14530fca6ea1SDimitry Andric // left shifting by bitwidth - 1. 14540fca6ea1SDimitry Andric bool IsNUW = Op->hasNoUnsignedWrap(); 14550fca6ea1SDimitry Andric bool IsNSW = Op->hasNoSignedWrap() && 14560fca6ea1SDimitry Andric (IsNUW || SA->getValue().ult(BitWidth - 1)); 14570fca6ea1SDimitry Andric 14580fca6ea1SDimitry Andric ConstantInt *X = 14590fca6ea1SDimitry Andric ConstantInt::get(Op->getContext(), 14600fca6ea1SDimitry Andric APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 14610fca6ea1SDimitry Andric return BinaryOp(Instruction::Mul, Op->getOperand(0), X, IsNSW, IsNUW); 14620fca6ea1SDimitry Andric } 14630fca6ea1SDimitry Andric } 14640fca6ea1SDimitry Andric 14650fca6ea1SDimitry Andric break; 14660fca6ea1SDimitry Andric } 14670fca6ea1SDimitry Andric } 14680fca6ea1SDimitry Andric 14690fca6ea1SDimitry Andric return std::nullopt; 14700fca6ea1SDimitry Andric } 14710fca6ea1SDimitry Andric 1472e8d8bef9SDimitry Andric /// No-wrap operations can transfer sign extension of their result to their 1473e8d8bef9SDimitry Andric /// operands. Generate the SCEV value for the widened operation without 1474e8d8bef9SDimitry Andric /// actually modifying the IR yet. If the expression after extending the 1475e8d8bef9SDimitry Andric /// operands is an AddRec for this loop, return the AddRec and the kind of 1476e8d8bef9SDimitry Andric /// extension used. 1477e8d8bef9SDimitry Andric WidenIV::WidenedRecTy 1478e8d8bef9SDimitry Andric WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) { 14790fca6ea1SDimitry Andric auto Op = matchBinaryOp(DU.NarrowUse); 14800fca6ea1SDimitry Andric if (!Op) 1481fcaf7f86SDimitry Andric return {nullptr, ExtendKind::Unknown}; 1482e8d8bef9SDimitry Andric 14830fca6ea1SDimitry Andric assert((Op->Opcode == Instruction::Add || Op->Opcode == Instruction::Sub || 14840fca6ea1SDimitry Andric Op->Opcode == Instruction::Mul) && 14850fca6ea1SDimitry Andric "Unexpected opcode"); 14860fca6ea1SDimitry Andric 1487e8d8bef9SDimitry Andric // One operand (NarrowDef) has already been extended to WideDef. Now determine 1488e8d8bef9SDimitry Andric // if extending the other will lead to a recurrence. 14890fca6ea1SDimitry Andric const unsigned ExtendOperIdx = Op->Operands[0] == DU.NarrowDef ? 1 : 0; 14900fca6ea1SDimitry Andric assert(Op->Operands[1 - ExtendOperIdx] == DU.NarrowDef && "bad DU"); 1491e8d8bef9SDimitry Andric 1492e8d8bef9SDimitry Andric ExtendKind ExtKind = getExtendKind(DU.NarrowDef); 14930fca6ea1SDimitry Andric if (!(ExtKind == ExtendKind::Sign && Op->IsNSW) && 14940fca6ea1SDimitry Andric !(ExtKind == ExtendKind::Zero && Op->IsNUW)) { 14955f757f3fSDimitry Andric ExtKind = ExtendKind::Unknown; 14965f757f3fSDimitry Andric 14975f757f3fSDimitry Andric // For a non-negative NarrowDef, we can choose either type of 14985f757f3fSDimitry Andric // extension. We want to use the current extend kind if legal 14995f757f3fSDimitry Andric // (see above), and we only hit this code if we need to check 15005f757f3fSDimitry Andric // the opposite case. 15015f757f3fSDimitry Andric if (DU.NeverNegative) { 15020fca6ea1SDimitry Andric if (Op->IsNSW) { 15035f757f3fSDimitry Andric ExtKind = ExtendKind::Sign; 15040fca6ea1SDimitry Andric } else if (Op->IsNUW) { 15055f757f3fSDimitry Andric ExtKind = ExtendKind::Zero; 15065f757f3fSDimitry Andric } 15075f757f3fSDimitry Andric } 15085f757f3fSDimitry Andric } 15095f757f3fSDimitry Andric 15100fca6ea1SDimitry Andric const SCEV *ExtendOperExpr = SE->getSCEV(Op->Operands[ExtendOperIdx]); 15115f757f3fSDimitry Andric if (ExtKind == ExtendKind::Sign) 15125f757f3fSDimitry Andric ExtendOperExpr = SE->getSignExtendExpr(ExtendOperExpr, WideType); 15135f757f3fSDimitry Andric else if (ExtKind == ExtendKind::Zero) 15145f757f3fSDimitry Andric ExtendOperExpr = SE->getZeroExtendExpr(ExtendOperExpr, WideType); 1515e8d8bef9SDimitry Andric else 1516fcaf7f86SDimitry Andric return {nullptr, ExtendKind::Unknown}; 1517e8d8bef9SDimitry Andric 1518e8d8bef9SDimitry Andric // When creating this SCEV expr, don't apply the current operations NSW or NUW 1519e8d8bef9SDimitry Andric // flags. This instruction may be guarded by control flow that the no-wrap 1520e8d8bef9SDimitry Andric // behavior depends on. Non-control-equivalent instructions can be mapped to 1521e8d8bef9SDimitry Andric // the same SCEV expression, and it would be incorrect to transfer NSW/NUW 1522e8d8bef9SDimitry Andric // semantics to those operations. 1523e8d8bef9SDimitry Andric const SCEV *lhs = SE->getSCEV(DU.WideDef); 1524e8d8bef9SDimitry Andric const SCEV *rhs = ExtendOperExpr; 1525e8d8bef9SDimitry Andric 1526e8d8bef9SDimitry Andric // Let's swap operands to the initial order for the case of non-commutative 1527e8d8bef9SDimitry Andric // operations, like SUB. See PR21014. 1528e8d8bef9SDimitry Andric if (ExtendOperIdx == 0) 1529e8d8bef9SDimitry Andric std::swap(lhs, rhs); 1530e8d8bef9SDimitry Andric const SCEVAddRecExpr *AddRec = 15310fca6ea1SDimitry Andric dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, Op->Opcode)); 1532e8d8bef9SDimitry Andric 1533e8d8bef9SDimitry Andric if (!AddRec || AddRec->getLoop() != L) 1534fcaf7f86SDimitry Andric return {nullptr, ExtendKind::Unknown}; 1535e8d8bef9SDimitry Andric 1536e8d8bef9SDimitry Andric return {AddRec, ExtKind}; 1537e8d8bef9SDimitry Andric } 1538e8d8bef9SDimitry Andric 1539e8d8bef9SDimitry Andric /// Is this instruction potentially interesting for further simplification after 1540e8d8bef9SDimitry Andric /// widening it's type? In other words, can the extend be safely hoisted out of 1541e8d8bef9SDimitry Andric /// the loop with SCEV reducing the value to a recurrence on the same loop. If 1542e8d8bef9SDimitry Andric /// so, return the extended recurrence and the kind of extension used. Otherwise 1543fcaf7f86SDimitry Andric /// return {nullptr, ExtendKind::Unknown}. 1544e8d8bef9SDimitry Andric WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) { 1545fe6060f1SDimitry Andric if (!DU.NarrowUse->getType()->isIntegerTy()) 1546fcaf7f86SDimitry Andric return {nullptr, ExtendKind::Unknown}; 1547e8d8bef9SDimitry Andric 1548e8d8bef9SDimitry Andric const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse); 1549e8d8bef9SDimitry Andric if (SE->getTypeSizeInBits(NarrowExpr->getType()) >= 1550e8d8bef9SDimitry Andric SE->getTypeSizeInBits(WideType)) { 1551e8d8bef9SDimitry Andric // NarrowUse implicitly widens its operand. e.g. a gep with a narrow 1552e8d8bef9SDimitry Andric // index. So don't follow this use. 1553fcaf7f86SDimitry Andric return {nullptr, ExtendKind::Unknown}; 1554e8d8bef9SDimitry Andric } 1555e8d8bef9SDimitry Andric 1556e8d8bef9SDimitry Andric const SCEV *WideExpr; 1557e8d8bef9SDimitry Andric ExtendKind ExtKind; 1558e8d8bef9SDimitry Andric if (DU.NeverNegative) { 1559e8d8bef9SDimitry Andric WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1560e8d8bef9SDimitry Andric if (isa<SCEVAddRecExpr>(WideExpr)) 1561fcaf7f86SDimitry Andric ExtKind = ExtendKind::Sign; 1562e8d8bef9SDimitry Andric else { 1563e8d8bef9SDimitry Andric WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1564fcaf7f86SDimitry Andric ExtKind = ExtendKind::Zero; 1565e8d8bef9SDimitry Andric } 1566fcaf7f86SDimitry Andric } else if (getExtendKind(DU.NarrowDef) == ExtendKind::Sign) { 1567e8d8bef9SDimitry Andric WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType); 1568fcaf7f86SDimitry Andric ExtKind = ExtendKind::Sign; 1569e8d8bef9SDimitry Andric } else { 1570e8d8bef9SDimitry Andric WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType); 1571fcaf7f86SDimitry Andric ExtKind = ExtendKind::Zero; 1572e8d8bef9SDimitry Andric } 1573e8d8bef9SDimitry Andric const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr); 1574e8d8bef9SDimitry Andric if (!AddRec || AddRec->getLoop() != L) 1575fcaf7f86SDimitry Andric return {nullptr, ExtendKind::Unknown}; 1576e8d8bef9SDimitry Andric return {AddRec, ExtKind}; 1577e8d8bef9SDimitry Andric } 1578e8d8bef9SDimitry Andric 1579e8d8bef9SDimitry Andric /// This IV user cannot be widened. Replace this use of the original narrow IV 1580e8d8bef9SDimitry Andric /// with a truncation of the new wide IV to isolate and eliminate the narrow IV. 15810fca6ea1SDimitry Andric void WidenIV::truncateIVUse(NarrowIVDefUse DU) { 1582e8d8bef9SDimitry Andric auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI); 1583e8d8bef9SDimitry Andric if (!InsertPt) 1584e8d8bef9SDimitry Andric return; 1585e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user " 1586e8d8bef9SDimitry Andric << *DU.NarrowUse << "\n"); 15870fca6ea1SDimitry Andric ExtendKind ExtKind = getExtendKind(DU.NarrowDef); 1588e8d8bef9SDimitry Andric IRBuilder<> Builder(InsertPt); 15890fca6ea1SDimitry Andric Value *Trunc = 15900fca6ea1SDimitry Andric Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType(), "", 15910fca6ea1SDimitry Andric DU.NeverNegative || ExtKind == ExtendKind::Zero, 15920fca6ea1SDimitry Andric DU.NeverNegative || ExtKind == ExtendKind::Sign); 1593e8d8bef9SDimitry Andric DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc); 1594e8d8bef9SDimitry Andric } 1595e8d8bef9SDimitry Andric 1596e8d8bef9SDimitry Andric /// If the narrow use is a compare instruction, then widen the compare 1597e8d8bef9SDimitry Andric // (and possibly the other operand). The extend operation is hoisted into the 1598e8d8bef9SDimitry Andric // loop preheader as far as possible. 1599e8d8bef9SDimitry Andric bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) { 1600e8d8bef9SDimitry Andric ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse); 1601e8d8bef9SDimitry Andric if (!Cmp) 1602e8d8bef9SDimitry Andric return false; 1603e8d8bef9SDimitry Andric 1604e8d8bef9SDimitry Andric // We can legally widen the comparison in the following two cases: 1605e8d8bef9SDimitry Andric // 1606e8d8bef9SDimitry Andric // - The signedness of the IV extension and comparison match 1607e8d8bef9SDimitry Andric // 1608e8d8bef9SDimitry Andric // - The narrow IV is always positive (and thus its sign extension is equal 1609e8d8bef9SDimitry Andric // to its zero extension). For instance, let's say we're zero extending 1610e8d8bef9SDimitry Andric // %narrow for the following use 1611e8d8bef9SDimitry Andric // 1612e8d8bef9SDimitry Andric // icmp slt i32 %narrow, %val ... (A) 1613e8d8bef9SDimitry Andric // 1614e8d8bef9SDimitry Andric // and %narrow is always positive. Then 1615e8d8bef9SDimitry Andric // 1616e8d8bef9SDimitry Andric // (A) == icmp slt i32 sext(%narrow), sext(%val) 1617e8d8bef9SDimitry Andric // == icmp slt i32 zext(%narrow), sext(%val) 1618fcaf7f86SDimitry Andric bool IsSigned = getExtendKind(DU.NarrowDef) == ExtendKind::Sign; 1619e8d8bef9SDimitry Andric if (!(DU.NeverNegative || IsSigned == Cmp->isSigned())) 1620e8d8bef9SDimitry Andric return false; 1621e8d8bef9SDimitry Andric 1622e8d8bef9SDimitry Andric Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0); 1623e8d8bef9SDimitry Andric unsigned CastWidth = SE->getTypeSizeInBits(Op->getType()); 1624e8d8bef9SDimitry Andric unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1625e8d8bef9SDimitry Andric assert(CastWidth <= IVWidth && "Unexpected width while widening compare."); 1626e8d8bef9SDimitry Andric 1627e8d8bef9SDimitry Andric // Widen the compare instruction. 1628e8d8bef9SDimitry Andric DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1629e8d8bef9SDimitry Andric 1630e8d8bef9SDimitry Andric // Widen the other operand of the compare, if necessary. 1631e8d8bef9SDimitry Andric if (CastWidth < IVWidth) { 1632e8d8bef9SDimitry Andric Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp); 1633e8d8bef9SDimitry Andric DU.NarrowUse->replaceUsesOfWith(Op, ExtOp); 1634e8d8bef9SDimitry Andric } 1635e8d8bef9SDimitry Andric return true; 1636e8d8bef9SDimitry Andric } 1637e8d8bef9SDimitry Andric 1638e8d8bef9SDimitry Andric // The widenIVUse avoids generating trunc by evaluating the use as AddRec, this 1639e8d8bef9SDimitry Andric // will not work when: 1640e8d8bef9SDimitry Andric // 1) SCEV traces back to an instruction inside the loop that SCEV can not 1641e8d8bef9SDimitry Andric // expand, eg. add %indvar, (load %addr) 1642e8d8bef9SDimitry Andric // 2) SCEV finds a loop variant, eg. add %indvar, %loopvariant 1643e8d8bef9SDimitry Andric // While SCEV fails to avoid trunc, we can still try to use instruction 1644e8d8bef9SDimitry Andric // combining approach to prove trunc is not required. This can be further 1645e8d8bef9SDimitry Andric // extended with other instruction combining checks, but for now we handle the 1646e8d8bef9SDimitry Andric // following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext") 1647e8d8bef9SDimitry Andric // 1648e8d8bef9SDimitry Andric // Src: 1649e8d8bef9SDimitry Andric // %c = sub nsw %b, %indvar 1650e8d8bef9SDimitry Andric // %d = sext %c to i64 1651e8d8bef9SDimitry Andric // Dst: 1652e8d8bef9SDimitry Andric // %indvar.ext1 = sext %indvar to i64 1653e8d8bef9SDimitry Andric // %m = sext %b to i64 1654e8d8bef9SDimitry Andric // %d = sub nsw i64 %m, %indvar.ext1 1655e8d8bef9SDimitry Andric // Therefore, as long as the result of add/sub/mul is extended to wide type, no 1656e8d8bef9SDimitry Andric // trunc is required regardless of how %b is generated. This pattern is common 1657e8d8bef9SDimitry Andric // when calculating address in 64 bit architecture 1658e8d8bef9SDimitry Andric bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) { 1659e8d8bef9SDimitry Andric Instruction *NarrowUse = DU.NarrowUse; 1660e8d8bef9SDimitry Andric Instruction *NarrowDef = DU.NarrowDef; 1661e8d8bef9SDimitry Andric Instruction *WideDef = DU.WideDef; 1662e8d8bef9SDimitry Andric 1663e8d8bef9SDimitry Andric // Handle the common case of add<nsw/nuw> 1664e8d8bef9SDimitry Andric const unsigned OpCode = NarrowUse->getOpcode(); 1665e8d8bef9SDimitry Andric // Only Add/Sub/Mul instructions are supported. 1666e8d8bef9SDimitry Andric if (OpCode != Instruction::Add && OpCode != Instruction::Sub && 1667e8d8bef9SDimitry Andric OpCode != Instruction::Mul) 1668e8d8bef9SDimitry Andric return false; 1669e8d8bef9SDimitry Andric 1670e8d8bef9SDimitry Andric // The operand that is not defined by NarrowDef of DU. Let's call it the 1671e8d8bef9SDimitry Andric // other operand. 1672e8d8bef9SDimitry Andric assert((NarrowUse->getOperand(0) == NarrowDef || 1673e8d8bef9SDimitry Andric NarrowUse->getOperand(1) == NarrowDef) && 1674e8d8bef9SDimitry Andric "bad DU"); 1675e8d8bef9SDimitry Andric 1676e8d8bef9SDimitry Andric const OverflowingBinaryOperator *OBO = 1677e8d8bef9SDimitry Andric cast<OverflowingBinaryOperator>(NarrowUse); 1678e8d8bef9SDimitry Andric ExtendKind ExtKind = getExtendKind(NarrowDef); 1679fcaf7f86SDimitry Andric bool CanSignExtend = ExtKind == ExtendKind::Sign && OBO->hasNoSignedWrap(); 1680fcaf7f86SDimitry Andric bool CanZeroExtend = ExtKind == ExtendKind::Zero && OBO->hasNoUnsignedWrap(); 1681e8d8bef9SDimitry Andric auto AnotherOpExtKind = ExtKind; 1682e8d8bef9SDimitry Andric 1683e8d8bef9SDimitry Andric // Check that all uses are either: 1684e8d8bef9SDimitry Andric // - narrow def (in case of we are widening the IV increment); 1685e8d8bef9SDimitry Andric // - single-input LCSSA Phis; 1686e8d8bef9SDimitry Andric // - comparison of the chosen type; 1687e8d8bef9SDimitry Andric // - extend of the chosen type (raison d'etre). 1688e8d8bef9SDimitry Andric SmallVector<Instruction *, 4> ExtUsers; 1689e8d8bef9SDimitry Andric SmallVector<PHINode *, 4> LCSSAPhiUsers; 1690e8d8bef9SDimitry Andric SmallVector<ICmpInst *, 4> ICmpUsers; 1691e8d8bef9SDimitry Andric for (Use &U : NarrowUse->uses()) { 1692e8d8bef9SDimitry Andric Instruction *User = cast<Instruction>(U.getUser()); 1693e8d8bef9SDimitry Andric if (User == NarrowDef) 1694e8d8bef9SDimitry Andric continue; 1695e8d8bef9SDimitry Andric if (!L->contains(User)) { 1696e8d8bef9SDimitry Andric auto *LCSSAPhi = cast<PHINode>(User); 1697e8d8bef9SDimitry Andric // Make sure there is only 1 input, so that we don't have to split 1698e8d8bef9SDimitry Andric // critical edges. 1699e8d8bef9SDimitry Andric if (LCSSAPhi->getNumOperands() != 1) 1700e8d8bef9SDimitry Andric return false; 1701e8d8bef9SDimitry Andric LCSSAPhiUsers.push_back(LCSSAPhi); 1702e8d8bef9SDimitry Andric continue; 1703e8d8bef9SDimitry Andric } 1704e8d8bef9SDimitry Andric if (auto *ICmp = dyn_cast<ICmpInst>(User)) { 1705e8d8bef9SDimitry Andric auto Pred = ICmp->getPredicate(); 1706e8d8bef9SDimitry Andric // We have 3 types of predicates: signed, unsigned and equality 1707e8d8bef9SDimitry Andric // predicates. For equality, it's legal to widen icmp for either sign and 1708e8d8bef9SDimitry Andric // zero extend. For sign extend, we can also do so for signed predicates, 1709e8d8bef9SDimitry Andric // likeweise for zero extend we can widen icmp for unsigned predicates. 1710fcaf7f86SDimitry Andric if (ExtKind == ExtendKind::Zero && ICmpInst::isSigned(Pred)) 1711e8d8bef9SDimitry Andric return false; 1712fcaf7f86SDimitry Andric if (ExtKind == ExtendKind::Sign && ICmpInst::isUnsigned(Pred)) 1713e8d8bef9SDimitry Andric return false; 1714e8d8bef9SDimitry Andric ICmpUsers.push_back(ICmp); 1715e8d8bef9SDimitry Andric continue; 1716e8d8bef9SDimitry Andric } 1717fcaf7f86SDimitry Andric if (ExtKind == ExtendKind::Sign) 1718e8d8bef9SDimitry Andric User = dyn_cast<SExtInst>(User); 1719e8d8bef9SDimitry Andric else 1720e8d8bef9SDimitry Andric User = dyn_cast<ZExtInst>(User); 1721e8d8bef9SDimitry Andric if (!User || User->getType() != WideType) 1722e8d8bef9SDimitry Andric return false; 1723e8d8bef9SDimitry Andric ExtUsers.push_back(User); 1724e8d8bef9SDimitry Andric } 1725e8d8bef9SDimitry Andric if (ExtUsers.empty()) { 1726e8d8bef9SDimitry Andric DeadInsts.emplace_back(NarrowUse); 1727e8d8bef9SDimitry Andric return true; 1728e8d8bef9SDimitry Andric } 1729e8d8bef9SDimitry Andric 1730e8d8bef9SDimitry Andric // We'll prove some facts that should be true in the context of ext users. If 1731e8d8bef9SDimitry Andric // there is no users, we are done now. If there are some, pick their common 1732e8d8bef9SDimitry Andric // dominator as context. 1733fe6060f1SDimitry Andric const Instruction *CtxI = findCommonDominator(ExtUsers, *DT); 1734e8d8bef9SDimitry Andric 1735e8d8bef9SDimitry Andric if (!CanSignExtend && !CanZeroExtend) { 1736e8d8bef9SDimitry Andric // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we 1737e8d8bef9SDimitry Andric // will most likely not see it. Let's try to prove it. 1738e8d8bef9SDimitry Andric if (OpCode != Instruction::Add) 1739e8d8bef9SDimitry Andric return false; 1740fcaf7f86SDimitry Andric if (ExtKind != ExtendKind::Zero) 1741e8d8bef9SDimitry Andric return false; 1742e8d8bef9SDimitry Andric const SCEV *LHS = SE->getSCEV(OBO->getOperand(0)); 1743e8d8bef9SDimitry Andric const SCEV *RHS = SE->getSCEV(OBO->getOperand(1)); 1744e8d8bef9SDimitry Andric // TODO: Support case for NarrowDef = NarrowUse->getOperand(1). 1745e8d8bef9SDimitry Andric if (NarrowUse->getOperand(0) != NarrowDef) 1746e8d8bef9SDimitry Andric return false; 1747e8d8bef9SDimitry Andric if (!SE->isKnownNegative(RHS)) 1748e8d8bef9SDimitry Andric return false; 1749fe6060f1SDimitry Andric bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS, 1750fe6060f1SDimitry Andric SE->getNegativeSCEV(RHS), CtxI); 1751e8d8bef9SDimitry Andric if (!ProvedSubNUW) 1752e8d8bef9SDimitry Andric return false; 1753e8d8bef9SDimitry Andric // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as 1754e8d8bef9SDimitry Andric // neg(zext(neg(op))), which is basically sext(op). 1755fcaf7f86SDimitry Andric AnotherOpExtKind = ExtendKind::Sign; 1756e8d8bef9SDimitry Andric } 1757e8d8bef9SDimitry Andric 1758e8d8bef9SDimitry Andric // Verifying that Defining operand is an AddRec 1759e8d8bef9SDimitry Andric const SCEV *Op1 = SE->getSCEV(WideDef); 1760e8d8bef9SDimitry Andric const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1); 1761e8d8bef9SDimitry Andric if (!AddRecOp1 || AddRecOp1->getLoop() != L) 1762e8d8bef9SDimitry Andric return false; 1763e8d8bef9SDimitry Andric 1764e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n"); 1765e8d8bef9SDimitry Andric 1766e8d8bef9SDimitry Andric // Generating a widening use instruction. 1767fcaf7f86SDimitry Andric Value *LHS = 1768fcaf7f86SDimitry Andric (NarrowUse->getOperand(0) == NarrowDef) 1769e8d8bef9SDimitry Andric ? WideDef 1770e8d8bef9SDimitry Andric : createExtendInst(NarrowUse->getOperand(0), WideType, 1771fcaf7f86SDimitry Andric AnotherOpExtKind == ExtendKind::Sign, NarrowUse); 1772fcaf7f86SDimitry Andric Value *RHS = 1773fcaf7f86SDimitry Andric (NarrowUse->getOperand(1) == NarrowDef) 1774e8d8bef9SDimitry Andric ? WideDef 1775e8d8bef9SDimitry Andric : createExtendInst(NarrowUse->getOperand(1), WideType, 1776fcaf7f86SDimitry Andric AnotherOpExtKind == ExtendKind::Sign, NarrowUse); 1777e8d8bef9SDimitry Andric 1778e8d8bef9SDimitry Andric auto *NarrowBO = cast<BinaryOperator>(NarrowUse); 1779e8d8bef9SDimitry Andric auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS, 1780e8d8bef9SDimitry Andric NarrowBO->getName()); 1781e8d8bef9SDimitry Andric IRBuilder<> Builder(NarrowUse); 1782e8d8bef9SDimitry Andric Builder.Insert(WideBO); 1783e8d8bef9SDimitry Andric WideBO->copyIRFlags(NarrowBO); 1784e8d8bef9SDimitry Andric ExtendKindMap[NarrowUse] = ExtKind; 1785e8d8bef9SDimitry Andric 1786e8d8bef9SDimitry Andric for (Instruction *User : ExtUsers) { 1787e8d8bef9SDimitry Andric assert(User->getType() == WideType && "Checked before!"); 1788e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by " 1789e8d8bef9SDimitry Andric << *WideBO << "\n"); 1790e8d8bef9SDimitry Andric ++NumElimExt; 1791e8d8bef9SDimitry Andric User->replaceAllUsesWith(WideBO); 1792e8d8bef9SDimitry Andric DeadInsts.emplace_back(User); 1793e8d8bef9SDimitry Andric } 1794e8d8bef9SDimitry Andric 1795e8d8bef9SDimitry Andric for (PHINode *User : LCSSAPhiUsers) { 1796e8d8bef9SDimitry Andric assert(User->getNumOperands() == 1 && "Checked before!"); 1797e8d8bef9SDimitry Andric Builder.SetInsertPoint(User); 1798e8d8bef9SDimitry Andric auto *WidePN = 1799e8d8bef9SDimitry Andric Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide"); 1800e8d8bef9SDimitry Andric BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor(); 1801e8d8bef9SDimitry Andric assert(LoopExitingBlock && L->contains(LoopExitingBlock) && 1802e8d8bef9SDimitry Andric "Not a LCSSA Phi?"); 1803e8d8bef9SDimitry Andric WidePN->addIncoming(WideBO, LoopExitingBlock); 18045f757f3fSDimitry Andric Builder.SetInsertPoint(User->getParent(), 18055f757f3fSDimitry Andric User->getParent()->getFirstInsertionPt()); 1806e8d8bef9SDimitry Andric auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType()); 1807e8d8bef9SDimitry Andric User->replaceAllUsesWith(TruncPN); 1808e8d8bef9SDimitry Andric DeadInsts.emplace_back(User); 1809e8d8bef9SDimitry Andric } 1810e8d8bef9SDimitry Andric 1811e8d8bef9SDimitry Andric for (ICmpInst *User : ICmpUsers) { 1812e8d8bef9SDimitry Andric Builder.SetInsertPoint(User); 1813e8d8bef9SDimitry Andric auto ExtendedOp = [&](Value * V)->Value * { 1814e8d8bef9SDimitry Andric if (V == NarrowUse) 1815e8d8bef9SDimitry Andric return WideBO; 1816fcaf7f86SDimitry Andric if (ExtKind == ExtendKind::Zero) 1817e8d8bef9SDimitry Andric return Builder.CreateZExt(V, WideBO->getType()); 1818e8d8bef9SDimitry Andric else 1819e8d8bef9SDimitry Andric return Builder.CreateSExt(V, WideBO->getType()); 1820e8d8bef9SDimitry Andric }; 1821e8d8bef9SDimitry Andric auto Pred = User->getPredicate(); 1822e8d8bef9SDimitry Andric auto *LHS = ExtendedOp(User->getOperand(0)); 1823e8d8bef9SDimitry Andric auto *RHS = ExtendedOp(User->getOperand(1)); 1824e8d8bef9SDimitry Andric auto *WideCmp = 1825e8d8bef9SDimitry Andric Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide"); 1826e8d8bef9SDimitry Andric User->replaceAllUsesWith(WideCmp); 1827e8d8bef9SDimitry Andric DeadInsts.emplace_back(User); 1828e8d8bef9SDimitry Andric } 1829e8d8bef9SDimitry Andric 1830e8d8bef9SDimitry Andric return true; 1831e8d8bef9SDimitry Andric } 1832e8d8bef9SDimitry Andric 1833e8d8bef9SDimitry Andric /// Determine whether an individual user of the narrow IV can be widened. If so, 1834e8d8bef9SDimitry Andric /// return the wide clone of the user. 18350fca6ea1SDimitry Andric Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU, 18360fca6ea1SDimitry Andric SCEVExpander &Rewriter, PHINode *OrigPhi, 18370fca6ea1SDimitry Andric PHINode *WidePhi) { 1838e8d8bef9SDimitry Andric assert(ExtendKindMap.count(DU.NarrowDef) && 1839e8d8bef9SDimitry Andric "Should already know the kind of extension used to widen NarrowDef"); 1840e8d8bef9SDimitry Andric 18410fca6ea1SDimitry Andric // This narrow use can be widened by a sext if it's non-negative or its narrow 18420fca6ea1SDimitry Andric // def was widened by a sext. Same for zext. 18430fca6ea1SDimitry Andric bool CanWidenBySExt = 18440fca6ea1SDimitry Andric DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Sign; 18450fca6ea1SDimitry Andric bool CanWidenByZExt = 18460fca6ea1SDimitry Andric DU.NeverNegative || getExtendKind(DU.NarrowDef) == ExtendKind::Zero; 18470fca6ea1SDimitry Andric 1848e8d8bef9SDimitry Andric // Stop traversing the def-use chain at inner-loop phis or post-loop phis. 1849e8d8bef9SDimitry Andric if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) { 1850e8d8bef9SDimitry Andric if (LI->getLoopFor(UsePhi->getParent()) != L) { 1851e8d8bef9SDimitry Andric // For LCSSA phis, sink the truncate outside the loop. 1852e8d8bef9SDimitry Andric // After SimplifyCFG most loop exit targets have a single predecessor. 1853e8d8bef9SDimitry Andric // Otherwise fall back to a truncate within the loop. 1854e8d8bef9SDimitry Andric if (UsePhi->getNumOperands() != 1) 18550fca6ea1SDimitry Andric truncateIVUse(DU); 1856e8d8bef9SDimitry Andric else { 1857e8d8bef9SDimitry Andric // Widening the PHI requires us to insert a trunc. The logical place 1858e8d8bef9SDimitry Andric // for this trunc is in the same BB as the PHI. This is not possible if 1859e8d8bef9SDimitry Andric // the BB is terminated by a catchswitch. 1860e8d8bef9SDimitry Andric if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator())) 1861e8d8bef9SDimitry Andric return nullptr; 1862e8d8bef9SDimitry Andric 1863e8d8bef9SDimitry Andric PHINode *WidePhi = 1864e8d8bef9SDimitry Andric PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide", 18650fca6ea1SDimitry Andric UsePhi->getIterator()); 1866e8d8bef9SDimitry Andric WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0)); 18675f757f3fSDimitry Andric BasicBlock *WidePhiBB = WidePhi->getParent(); 18685f757f3fSDimitry Andric IRBuilder<> Builder(WidePhiBB, WidePhiBB->getFirstInsertionPt()); 18690fca6ea1SDimitry Andric Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType(), "", 18700fca6ea1SDimitry Andric CanWidenByZExt, CanWidenBySExt); 1871e8d8bef9SDimitry Andric UsePhi->replaceAllUsesWith(Trunc); 1872e8d8bef9SDimitry Andric DeadInsts.emplace_back(UsePhi); 1873e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to " 1874e8d8bef9SDimitry Andric << *WidePhi << "\n"); 1875e8d8bef9SDimitry Andric } 1876e8d8bef9SDimitry Andric return nullptr; 1877e8d8bef9SDimitry Andric } 1878e8d8bef9SDimitry Andric } 1879e8d8bef9SDimitry Andric 1880e8d8bef9SDimitry Andric // Our raison d'etre! Eliminate sign and zero extension. 18810fca6ea1SDimitry Andric if ((match(DU.NarrowUse, m_SExtLike(m_Value())) && CanWidenBySExt) || 18820fca6ea1SDimitry Andric (isa<ZExtInst>(DU.NarrowUse) && CanWidenByZExt)) { 1883e8d8bef9SDimitry Andric Value *NewDef = DU.WideDef; 1884e8d8bef9SDimitry Andric if (DU.NarrowUse->getType() != WideType) { 1885e8d8bef9SDimitry Andric unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType()); 1886e8d8bef9SDimitry Andric unsigned IVWidth = SE->getTypeSizeInBits(WideType); 1887e8d8bef9SDimitry Andric if (CastWidth < IVWidth) { 1888e8d8bef9SDimitry Andric // The cast isn't as wide as the IV, so insert a Trunc. 1889e8d8bef9SDimitry Andric IRBuilder<> Builder(DU.NarrowUse); 18900fca6ea1SDimitry Andric NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType(), "", 18910fca6ea1SDimitry Andric CanWidenByZExt, CanWidenBySExt); 1892e8d8bef9SDimitry Andric } 1893e8d8bef9SDimitry Andric else { 1894e8d8bef9SDimitry Andric // A wider extend was hidden behind a narrower one. This may induce 1895e8d8bef9SDimitry Andric // another round of IV widening in which the intermediate IV becomes 1896e8d8bef9SDimitry Andric // dead. It should be very rare. 1897e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi 1898e8d8bef9SDimitry Andric << " not wide enough to subsume " << *DU.NarrowUse 1899e8d8bef9SDimitry Andric << "\n"); 1900e8d8bef9SDimitry Andric DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef); 1901e8d8bef9SDimitry Andric NewDef = DU.NarrowUse; 1902e8d8bef9SDimitry Andric } 1903e8d8bef9SDimitry Andric } 1904e8d8bef9SDimitry Andric if (NewDef != DU.NarrowUse) { 1905e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse 1906e8d8bef9SDimitry Andric << " replaced by " << *DU.WideDef << "\n"); 1907e8d8bef9SDimitry Andric ++NumElimExt; 1908e8d8bef9SDimitry Andric DU.NarrowUse->replaceAllUsesWith(NewDef); 1909e8d8bef9SDimitry Andric DeadInsts.emplace_back(DU.NarrowUse); 1910e8d8bef9SDimitry Andric } 1911e8d8bef9SDimitry Andric // Now that the extend is gone, we want to expose it's uses for potential 1912e8d8bef9SDimitry Andric // further simplification. We don't need to directly inform SimplifyIVUsers 1913e8d8bef9SDimitry Andric // of the new users, because their parent IV will be processed later as a 1914e8d8bef9SDimitry Andric // new loop phi. If we preserved IVUsers analysis, we would also want to 1915e8d8bef9SDimitry Andric // push the uses of WideDef here. 1916e8d8bef9SDimitry Andric 1917e8d8bef9SDimitry Andric // No further widening is needed. The deceased [sz]ext had done it for us. 1918e8d8bef9SDimitry Andric return nullptr; 1919e8d8bef9SDimitry Andric } 1920e8d8bef9SDimitry Andric 19215f757f3fSDimitry Andric auto tryAddRecExpansion = [&]() -> Instruction* { 1922e8d8bef9SDimitry Andric // Does this user itself evaluate to a recurrence after widening? 1923e8d8bef9SDimitry Andric WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU); 1924e8d8bef9SDimitry Andric if (!WideAddRec.first) 1925e8d8bef9SDimitry Andric WideAddRec = getWideRecurrence(DU); 1926fcaf7f86SDimitry Andric assert((WideAddRec.first == nullptr) == 1927fcaf7f86SDimitry Andric (WideAddRec.second == ExtendKind::Unknown)); 19285f757f3fSDimitry Andric if (!WideAddRec.first) 1929e8d8bef9SDimitry Andric return nullptr; 1930e8d8bef9SDimitry Andric 1931*6c4b055cSDimitry Andric auto CanUseWideInc = [&]() { 1932*6c4b055cSDimitry Andric if (!WideInc) 1933*6c4b055cSDimitry Andric return false; 1934*6c4b055cSDimitry Andric // Reuse the IV increment that SCEVExpander created. Recompute flags, 1935*6c4b055cSDimitry Andric // unless the flags for both increments agree and it is safe to use the 1936*6c4b055cSDimitry Andric // ones from the original inc. In that case, the new use of the wide 1937*6c4b055cSDimitry Andric // increment won't be more poisonous. 19380fca6ea1SDimitry Andric bool NeedToRecomputeFlags = 1939*6c4b055cSDimitry Andric !SCEVExpander::canReuseFlagsFromOriginalIVInc( 1940*6c4b055cSDimitry Andric OrigPhi, WidePhi, DU.NarrowUse, WideInc) || 19410fca6ea1SDimitry Andric DU.NarrowUse->hasNoUnsignedWrap() != WideInc->hasNoUnsignedWrap() || 19420fca6ea1SDimitry Andric DU.NarrowUse->hasNoSignedWrap() != WideInc->hasNoSignedWrap(); 1943*6c4b055cSDimitry Andric return WideAddRec.first == WideIncExpr && 1944*6c4b055cSDimitry Andric Rewriter.hoistIVInc(WideInc, DU.NarrowUse, NeedToRecomputeFlags); 1945*6c4b055cSDimitry Andric }; 1946*6c4b055cSDimitry Andric 1947e8d8bef9SDimitry Andric Instruction *WideUse = nullptr; 1948*6c4b055cSDimitry Andric if (CanUseWideInc()) 1949e8d8bef9SDimitry Andric WideUse = WideInc; 1950e8d8bef9SDimitry Andric else { 1951e8d8bef9SDimitry Andric WideUse = cloneIVUser(DU, WideAddRec.first); 1952e8d8bef9SDimitry Andric if (!WideUse) 1953e8d8bef9SDimitry Andric return nullptr; 1954e8d8bef9SDimitry Andric } 1955e8d8bef9SDimitry Andric // Evaluation of WideAddRec ensured that the narrow expression could be 1956e8d8bef9SDimitry Andric // extended outside the loop without overflow. This suggests that the wide use 1957e8d8bef9SDimitry Andric // evaluates to the same expression as the extended narrow use, but doesn't 1958e8d8bef9SDimitry Andric // absolutely guarantee it. Hence the following failsafe check. In rare cases 1959e8d8bef9SDimitry Andric // where it fails, we simply throw away the newly created wide use. 1960e8d8bef9SDimitry Andric if (WideAddRec.first != SE->getSCEV(WideUse)) { 1961e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": " 1962e8d8bef9SDimitry Andric << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first 1963e8d8bef9SDimitry Andric << "\n"); 1964e8d8bef9SDimitry Andric DeadInsts.emplace_back(WideUse); 1965e8d8bef9SDimitry Andric return nullptr; 19665f757f3fSDimitry Andric }; 1967e8d8bef9SDimitry Andric 1968e8d8bef9SDimitry Andric // if we reached this point then we are going to replace 1969e8d8bef9SDimitry Andric // DU.NarrowUse with WideUse. Reattach DbgValue then. 1970e8d8bef9SDimitry Andric replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT); 1971e8d8bef9SDimitry Andric 1972e8d8bef9SDimitry Andric ExtendKindMap[DU.NarrowUse] = WideAddRec.second; 1973e8d8bef9SDimitry Andric // Returning WideUse pushes it on the worklist. 1974e8d8bef9SDimitry Andric return WideUse; 19755f757f3fSDimitry Andric }; 19765f757f3fSDimitry Andric 19775f757f3fSDimitry Andric if (auto *I = tryAddRecExpansion()) 19785f757f3fSDimitry Andric return I; 19795f757f3fSDimitry Andric 19805f757f3fSDimitry Andric // If use is a loop condition, try to promote the condition instead of 19815f757f3fSDimitry Andric // truncating the IV first. 19825f757f3fSDimitry Andric if (widenLoopCompare(DU)) 19835f757f3fSDimitry Andric return nullptr; 19845f757f3fSDimitry Andric 19855f757f3fSDimitry Andric // We are here about to generate a truncate instruction that may hurt 19865f757f3fSDimitry Andric // performance because the scalar evolution expression computed earlier 19875f757f3fSDimitry Andric // in WideAddRec.first does not indicate a polynomial induction expression. 19885f757f3fSDimitry Andric // In that case, look at the operands of the use instruction to determine 19895f757f3fSDimitry Andric // if we can still widen the use instead of truncating its operand. 19905f757f3fSDimitry Andric if (widenWithVariantUse(DU)) 19915f757f3fSDimitry Andric return nullptr; 19925f757f3fSDimitry Andric 19935f757f3fSDimitry Andric // This user does not evaluate to a recurrence after widening, so don't 19945f757f3fSDimitry Andric // follow it. Instead insert a Trunc to kill off the original use, 19955f757f3fSDimitry Andric // eventually isolating the original narrow IV so it can be removed. 19960fca6ea1SDimitry Andric truncateIVUse(DU); 19975f757f3fSDimitry Andric return nullptr; 1998e8d8bef9SDimitry Andric } 1999e8d8bef9SDimitry Andric 2000e8d8bef9SDimitry Andric /// Add eligible users of NarrowDef to NarrowIVUsers. 2001e8d8bef9SDimitry Andric void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) { 2002e8d8bef9SDimitry Andric const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef); 2003e8d8bef9SDimitry Andric bool NonNegativeDef = 2004e8d8bef9SDimitry Andric SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV, 2005e8d8bef9SDimitry Andric SE->getZero(NarrowSCEV->getType())); 2006e8d8bef9SDimitry Andric for (User *U : NarrowDef->users()) { 2007e8d8bef9SDimitry Andric Instruction *NarrowUser = cast<Instruction>(U); 2008e8d8bef9SDimitry Andric 2009e8d8bef9SDimitry Andric // Handle data flow merges and bizarre phi cycles. 2010e8d8bef9SDimitry Andric if (!Widened.insert(NarrowUser).second) 2011e8d8bef9SDimitry Andric continue; 2012e8d8bef9SDimitry Andric 2013e8d8bef9SDimitry Andric bool NonNegativeUse = false; 2014e8d8bef9SDimitry Andric if (!NonNegativeDef) { 2015e8d8bef9SDimitry Andric // We might have a control-dependent range information for this context. 2016e8d8bef9SDimitry Andric if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser)) 2017e8d8bef9SDimitry Andric NonNegativeUse = RangeInfo->getSignedMin().isNonNegative(); 2018e8d8bef9SDimitry Andric } 2019e8d8bef9SDimitry Andric 2020e8d8bef9SDimitry Andric NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef, 2021e8d8bef9SDimitry Andric NonNegativeDef || NonNegativeUse); 2022e8d8bef9SDimitry Andric } 2023e8d8bef9SDimitry Andric } 2024e8d8bef9SDimitry Andric 2025e8d8bef9SDimitry Andric /// Process a single induction variable. First use the SCEVExpander to create a 2026e8d8bef9SDimitry Andric /// wide induction variable that evaluates to the same recurrence as the 2027e8d8bef9SDimitry Andric /// original narrow IV. Then use a worklist to forward traverse the narrow IV's 2028e8d8bef9SDimitry Andric /// def-use chain. After widenIVUse has processed all interesting IV users, the 2029e8d8bef9SDimitry Andric /// narrow IV will be isolated for removal by DeleteDeadPHIs. 2030e8d8bef9SDimitry Andric /// 2031e8d8bef9SDimitry Andric /// It would be simpler to delete uses as they are processed, but we must avoid 2032e8d8bef9SDimitry Andric /// invalidating SCEV expressions. 2033e8d8bef9SDimitry Andric PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) { 2034e8d8bef9SDimitry Andric // Is this phi an induction variable? 2035e8d8bef9SDimitry Andric const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi)); 2036e8d8bef9SDimitry Andric if (!AddRec) 2037e8d8bef9SDimitry Andric return nullptr; 2038e8d8bef9SDimitry Andric 2039e8d8bef9SDimitry Andric // Widen the induction variable expression. 2040fcaf7f86SDimitry Andric const SCEV *WideIVExpr = getExtendKind(OrigPhi) == ExtendKind::Sign 2041e8d8bef9SDimitry Andric ? SE->getSignExtendExpr(AddRec, WideType) 2042e8d8bef9SDimitry Andric : SE->getZeroExtendExpr(AddRec, WideType); 2043e8d8bef9SDimitry Andric 2044e8d8bef9SDimitry Andric assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType && 2045e8d8bef9SDimitry Andric "Expect the new IV expression to preserve its type"); 2046e8d8bef9SDimitry Andric 2047e8d8bef9SDimitry Andric // Can the IV be extended outside the loop without overflow? 2048e8d8bef9SDimitry Andric AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr); 2049e8d8bef9SDimitry Andric if (!AddRec || AddRec->getLoop() != L) 2050e8d8bef9SDimitry Andric return nullptr; 2051e8d8bef9SDimitry Andric 2052e8d8bef9SDimitry Andric // An AddRec must have loop-invariant operands. Since this AddRec is 2053e8d8bef9SDimitry Andric // materialized by a loop header phi, the expression cannot have any post-loop 2054e8d8bef9SDimitry Andric // operands, so they must dominate the loop header. 2055e8d8bef9SDimitry Andric assert( 2056e8d8bef9SDimitry Andric SE->properlyDominates(AddRec->getStart(), L->getHeader()) && 2057e8d8bef9SDimitry Andric SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) && 2058e8d8bef9SDimitry Andric "Loop header phi recurrence inputs do not dominate the loop"); 2059e8d8bef9SDimitry Andric 2060e8d8bef9SDimitry Andric // Iterate over IV uses (including transitive ones) looking for IV increments 2061e8d8bef9SDimitry Andric // of the form 'add nsw %iv, <const>'. For each increment and each use of 2062e8d8bef9SDimitry Andric // the increment calculate control-dependent range information basing on 2063e8d8bef9SDimitry Andric // dominating conditions inside of the loop (e.g. a range check inside of the 2064e8d8bef9SDimitry Andric // loop). Calculated ranges are stored in PostIncRangeInfos map. 2065e8d8bef9SDimitry Andric // 2066e8d8bef9SDimitry Andric // Control-dependent range information is later used to prove that a narrow 2067e8d8bef9SDimitry Andric // definition is not negative (see pushNarrowIVUsers). It's difficult to do 2068e8d8bef9SDimitry Andric // this on demand because when pushNarrowIVUsers needs this information some 2069e8d8bef9SDimitry Andric // of the dominating conditions might be already widened. 2070e8d8bef9SDimitry Andric if (UsePostIncrementRanges) 2071e8d8bef9SDimitry Andric calculatePostIncRanges(OrigPhi); 2072e8d8bef9SDimitry Andric 2073e8d8bef9SDimitry Andric // The rewriter provides a value for the desired IV expression. This may 2074e8d8bef9SDimitry Andric // either find an existing phi or materialize a new one. Either way, we 2075e8d8bef9SDimitry Andric // expect a well-formed cyclic phi-with-increments. i.e. any operand not part 2076e8d8bef9SDimitry Andric // of the phi-SCC dominates the loop entry. 2077e8d8bef9SDimitry Andric Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt(); 2078e8d8bef9SDimitry Andric Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt); 2079e8d8bef9SDimitry Andric // If the wide phi is not a phi node, for example a cast node, like bitcast, 2080e8d8bef9SDimitry Andric // inttoptr, ptrtoint, just skip for now. 2081e8d8bef9SDimitry Andric if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) { 2082e8d8bef9SDimitry Andric // if the cast node is an inserted instruction without any user, we should 2083e8d8bef9SDimitry Andric // remove it to make sure the pass don't touch the function as we can not 2084e8d8bef9SDimitry Andric // wide the phi. 2085e8d8bef9SDimitry Andric if (ExpandInst->hasNUses(0) && 2086e8d8bef9SDimitry Andric Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst))) 2087e8d8bef9SDimitry Andric DeadInsts.emplace_back(ExpandInst); 2088e8d8bef9SDimitry Andric return nullptr; 2089e8d8bef9SDimitry Andric } 2090e8d8bef9SDimitry Andric 2091e8d8bef9SDimitry Andric // Remembering the WideIV increment generated by SCEVExpander allows 2092e8d8bef9SDimitry Andric // widenIVUse to reuse it when widening the narrow IV's increment. We don't 2093e8d8bef9SDimitry Andric // employ a general reuse mechanism because the call above is the only call to 2094e8d8bef9SDimitry Andric // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses. 2095e8d8bef9SDimitry Andric if (BasicBlock *LatchBlock = L->getLoopLatch()) { 2096e8d8bef9SDimitry Andric WideInc = 20975f757f3fSDimitry Andric dyn_cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock)); 20985f757f3fSDimitry Andric if (WideInc) { 2099e8d8bef9SDimitry Andric WideIncExpr = SE->getSCEV(WideInc); 21005f757f3fSDimitry Andric // Propagate the debug location associated with the original loop 21015f757f3fSDimitry Andric // increment to the new (widened) increment. 2102e8d8bef9SDimitry Andric auto *OrigInc = 2103e8d8bef9SDimitry Andric cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock)); 21040fca6ea1SDimitry Andric 2105e8d8bef9SDimitry Andric WideInc->setDebugLoc(OrigInc->getDebugLoc()); 21060fca6ea1SDimitry Andric // We are replacing a narrow IV increment with a wider IV increment. If 21070fca6ea1SDimitry Andric // the original (narrow) increment did not wrap, the wider increment one 21080fca6ea1SDimitry Andric // should not wrap either. Set the flags to be the union of both wide 21090fca6ea1SDimitry Andric // increment and original increment; this ensures we preserve flags SCEV 21100fca6ea1SDimitry Andric // could infer for the wider increment. Limit this only to cases where 21110fca6ea1SDimitry Andric // both increments directly increment the corresponding PHI nodes and have 21120fca6ea1SDimitry Andric // the same opcode. It is not safe to re-use the flags from the original 21130fca6ea1SDimitry Andric // increment, if it is more complex and SCEV expansion may have yielded a 21140fca6ea1SDimitry Andric // more simplified wider increment. 21150fca6ea1SDimitry Andric if (SCEVExpander::canReuseFlagsFromOriginalIVInc(OrigPhi, WidePhi, 21160fca6ea1SDimitry Andric OrigInc, WideInc) && 21170fca6ea1SDimitry Andric isa<OverflowingBinaryOperator>(OrigInc) && 21180fca6ea1SDimitry Andric isa<OverflowingBinaryOperator>(WideInc)) { 21190fca6ea1SDimitry Andric WideInc->setHasNoUnsignedWrap(WideInc->hasNoUnsignedWrap() || 21200fca6ea1SDimitry Andric OrigInc->hasNoUnsignedWrap()); 21210fca6ea1SDimitry Andric WideInc->setHasNoSignedWrap(WideInc->hasNoSignedWrap() || 21220fca6ea1SDimitry Andric OrigInc->hasNoSignedWrap()); 21230fca6ea1SDimitry Andric } 2124e8d8bef9SDimitry Andric } 21255f757f3fSDimitry Andric } 2126e8d8bef9SDimitry Andric 2127e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n"); 2128e8d8bef9SDimitry Andric ++NumWidened; 2129e8d8bef9SDimitry Andric 2130e8d8bef9SDimitry Andric // Traverse the def-use chain using a worklist starting at the original IV. 2131e8d8bef9SDimitry Andric assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" ); 2132e8d8bef9SDimitry Andric 2133e8d8bef9SDimitry Andric Widened.insert(OrigPhi); 2134e8d8bef9SDimitry Andric pushNarrowIVUsers(OrigPhi, WidePhi); 2135e8d8bef9SDimitry Andric 2136e8d8bef9SDimitry Andric while (!NarrowIVUsers.empty()) { 2137e8d8bef9SDimitry Andric WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val(); 2138e8d8bef9SDimitry Andric 2139e8d8bef9SDimitry Andric // Process a def-use edge. This may replace the use, so don't hold a 2140e8d8bef9SDimitry Andric // use_iterator across it. 21410fca6ea1SDimitry Andric Instruction *WideUse = widenIVUse(DU, Rewriter, OrigPhi, WidePhi); 2142e8d8bef9SDimitry Andric 2143e8d8bef9SDimitry Andric // Follow all def-use edges from the previous narrow use. 2144e8d8bef9SDimitry Andric if (WideUse) 2145e8d8bef9SDimitry Andric pushNarrowIVUsers(DU.NarrowUse, WideUse); 2146e8d8bef9SDimitry Andric 2147e8d8bef9SDimitry Andric // widenIVUse may have removed the def-use edge. 2148e8d8bef9SDimitry Andric if (DU.NarrowDef->use_empty()) 2149e8d8bef9SDimitry Andric DeadInsts.emplace_back(DU.NarrowDef); 2150e8d8bef9SDimitry Andric } 2151e8d8bef9SDimitry Andric 2152e8d8bef9SDimitry Andric // Attach any debug information to the new PHI. 2153e8d8bef9SDimitry Andric replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT); 2154e8d8bef9SDimitry Andric 2155e8d8bef9SDimitry Andric return WidePhi; 2156e8d8bef9SDimitry Andric } 2157e8d8bef9SDimitry Andric 2158e8d8bef9SDimitry Andric /// Calculates control-dependent range for the given def at the given context 2159e8d8bef9SDimitry Andric /// by looking at dominating conditions inside of the loop 2160e8d8bef9SDimitry Andric void WidenIV::calculatePostIncRange(Instruction *NarrowDef, 2161e8d8bef9SDimitry Andric Instruction *NarrowUser) { 2162e8d8bef9SDimitry Andric Value *NarrowDefLHS; 2163e8d8bef9SDimitry Andric const APInt *NarrowDefRHS; 2164e8d8bef9SDimitry Andric if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS), 2165e8d8bef9SDimitry Andric m_APInt(NarrowDefRHS))) || 2166e8d8bef9SDimitry Andric !NarrowDefRHS->isNonNegative()) 2167e8d8bef9SDimitry Andric return; 2168e8d8bef9SDimitry Andric 2169e8d8bef9SDimitry Andric auto UpdateRangeFromCondition = [&] (Value *Condition, 2170e8d8bef9SDimitry Andric bool TrueDest) { 2171e8d8bef9SDimitry Andric CmpInst::Predicate Pred; 2172e8d8bef9SDimitry Andric Value *CmpRHS; 2173e8d8bef9SDimitry Andric if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS), 2174e8d8bef9SDimitry Andric m_Value(CmpRHS)))) 2175e8d8bef9SDimitry Andric return; 2176e8d8bef9SDimitry Andric 2177e8d8bef9SDimitry Andric CmpInst::Predicate P = 2178e8d8bef9SDimitry Andric TrueDest ? Pred : CmpInst::getInversePredicate(Pred); 2179e8d8bef9SDimitry Andric 2180e8d8bef9SDimitry Andric auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS)); 2181e8d8bef9SDimitry Andric auto CmpConstrainedLHSRange = 2182e8d8bef9SDimitry Andric ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange); 2183e8d8bef9SDimitry Andric auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap( 2184e8d8bef9SDimitry Andric *NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap); 2185e8d8bef9SDimitry Andric 2186e8d8bef9SDimitry Andric updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange); 2187e8d8bef9SDimitry Andric }; 2188e8d8bef9SDimitry Andric 2189e8d8bef9SDimitry Andric auto UpdateRangeFromGuards = [&](Instruction *Ctx) { 2190e8d8bef9SDimitry Andric if (!HasGuards) 2191e8d8bef9SDimitry Andric return; 2192e8d8bef9SDimitry Andric 2193e8d8bef9SDimitry Andric for (Instruction &I : make_range(Ctx->getIterator().getReverse(), 2194e8d8bef9SDimitry Andric Ctx->getParent()->rend())) { 2195e8d8bef9SDimitry Andric Value *C = nullptr; 2196e8d8bef9SDimitry Andric if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C)))) 2197e8d8bef9SDimitry Andric UpdateRangeFromCondition(C, /*TrueDest=*/true); 2198e8d8bef9SDimitry Andric } 2199e8d8bef9SDimitry Andric }; 2200e8d8bef9SDimitry Andric 2201e8d8bef9SDimitry Andric UpdateRangeFromGuards(NarrowUser); 2202e8d8bef9SDimitry Andric 2203e8d8bef9SDimitry Andric BasicBlock *NarrowUserBB = NarrowUser->getParent(); 2204e8d8bef9SDimitry Andric // If NarrowUserBB is statically unreachable asking dominator queries may 2205e8d8bef9SDimitry Andric // yield surprising results. (e.g. the block may not have a dom tree node) 2206e8d8bef9SDimitry Andric if (!DT->isReachableFromEntry(NarrowUserBB)) 2207e8d8bef9SDimitry Andric return; 2208e8d8bef9SDimitry Andric 2209e8d8bef9SDimitry Andric for (auto *DTB = (*DT)[NarrowUserBB]->getIDom(); 2210e8d8bef9SDimitry Andric L->contains(DTB->getBlock()); 2211e8d8bef9SDimitry Andric DTB = DTB->getIDom()) { 2212e8d8bef9SDimitry Andric auto *BB = DTB->getBlock(); 2213e8d8bef9SDimitry Andric auto *TI = BB->getTerminator(); 2214e8d8bef9SDimitry Andric UpdateRangeFromGuards(TI); 2215e8d8bef9SDimitry Andric 2216e8d8bef9SDimitry Andric auto *BI = dyn_cast<BranchInst>(TI); 2217e8d8bef9SDimitry Andric if (!BI || !BI->isConditional()) 2218e8d8bef9SDimitry Andric continue; 2219e8d8bef9SDimitry Andric 2220e8d8bef9SDimitry Andric auto *TrueSuccessor = BI->getSuccessor(0); 2221e8d8bef9SDimitry Andric auto *FalseSuccessor = BI->getSuccessor(1); 2222e8d8bef9SDimitry Andric 2223e8d8bef9SDimitry Andric auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) { 2224e8d8bef9SDimitry Andric return BBE.isSingleEdge() && 2225e8d8bef9SDimitry Andric DT->dominates(BBE, NarrowUser->getParent()); 2226e8d8bef9SDimitry Andric }; 2227e8d8bef9SDimitry Andric 2228e8d8bef9SDimitry Andric if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor))) 2229e8d8bef9SDimitry Andric UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true); 2230e8d8bef9SDimitry Andric 2231e8d8bef9SDimitry Andric if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor))) 2232e8d8bef9SDimitry Andric UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false); 2233e8d8bef9SDimitry Andric } 2234e8d8bef9SDimitry Andric } 2235e8d8bef9SDimitry Andric 2236e8d8bef9SDimitry Andric /// Calculates PostIncRangeInfos map for the given IV 2237e8d8bef9SDimitry Andric void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) { 2238e8d8bef9SDimitry Andric SmallPtrSet<Instruction *, 16> Visited; 2239e8d8bef9SDimitry Andric SmallVector<Instruction *, 6> Worklist; 2240e8d8bef9SDimitry Andric Worklist.push_back(OrigPhi); 2241e8d8bef9SDimitry Andric Visited.insert(OrigPhi); 2242e8d8bef9SDimitry Andric 2243e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2244e8d8bef9SDimitry Andric Instruction *NarrowDef = Worklist.pop_back_val(); 2245e8d8bef9SDimitry Andric 2246e8d8bef9SDimitry Andric for (Use &U : NarrowDef->uses()) { 2247e8d8bef9SDimitry Andric auto *NarrowUser = cast<Instruction>(U.getUser()); 2248e8d8bef9SDimitry Andric 2249e8d8bef9SDimitry Andric // Don't go looking outside the current loop. 2250e8d8bef9SDimitry Andric auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()]; 2251e8d8bef9SDimitry Andric if (!NarrowUserLoop || !L->contains(NarrowUserLoop)) 2252e8d8bef9SDimitry Andric continue; 2253e8d8bef9SDimitry Andric 2254e8d8bef9SDimitry Andric if (!Visited.insert(NarrowUser).second) 2255e8d8bef9SDimitry Andric continue; 2256e8d8bef9SDimitry Andric 2257e8d8bef9SDimitry Andric Worklist.push_back(NarrowUser); 2258e8d8bef9SDimitry Andric 2259e8d8bef9SDimitry Andric calculatePostIncRange(NarrowDef, NarrowUser); 2260e8d8bef9SDimitry Andric } 2261e8d8bef9SDimitry Andric } 2262e8d8bef9SDimitry Andric } 2263e8d8bef9SDimitry Andric 2264e8d8bef9SDimitry Andric PHINode *llvm::createWideIV(const WideIVInfo &WI, 2265e8d8bef9SDimitry Andric LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter, 2266e8d8bef9SDimitry Andric DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts, 2267e8d8bef9SDimitry Andric unsigned &NumElimExt, unsigned &NumWidened, 2268e8d8bef9SDimitry Andric bool HasGuards, bool UsePostIncrementRanges) { 2269e8d8bef9SDimitry Andric WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges); 2270e8d8bef9SDimitry Andric PHINode *WidePHI = Widener.createWideIV(Rewriter); 2271e8d8bef9SDimitry Andric NumElimExt = Widener.getNumElimExt(); 2272e8d8bef9SDimitry Andric NumWidened = Widener.getNumWidened(); 2273e8d8bef9SDimitry Andric return WidePHI; 2274e8d8bef9SDimitry Andric } 2275