Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 1 | //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements induction variable simplification. It does |
| 11 | // not define any actual pass or policy, but provides a single function to |
| 12 | // simplify a loop's induction variables based on ScalarEvolution. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 16 | #include "llvm/Transforms/Utils/SimplifyIndVar.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SmallVector.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/LoopInfo.h" |
| 21 | #include "llvm/Analysis/LoopPass.h" |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 23 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 24 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 25 | #include "llvm/IR/IRBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Instructions.h" |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 27 | #include "llvm/IR/IntrinsicInst.h" |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 28 | #include "llvm/IR/PatternMatch.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 29 | #include "llvm/Support/Debug.h" |
| 30 | #include "llvm/Support/raw_ostream.h" |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 31 | |
| 32 | using namespace llvm; |
| 33 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 34 | #define DEBUG_TYPE "indvars" |
| 35 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 36 | STATISTIC(NumElimIdentity, "Number of IV identities eliminated"); |
| 37 | STATISTIC(NumElimOperand, "Number of IV operands folded into a use"); |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 38 | STATISTIC(NumFoldedUser, "Number of IV users folded into a constant"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 39 | STATISTIC(NumElimRem , "Number of IV remainder operations eliminated"); |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 40 | STATISTIC( |
| 41 | NumSimplifiedSDiv, |
| 42 | "Number of IV signed division operations converted to unsigned division"); |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 43 | STATISTIC( |
| 44 | NumSimplifiedSRem, |
| 45 | "Number of IV signed remainder operations converted to unsigned remainder"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 46 | STATISTIC(NumElimCmp , "Number of IV comparisons eliminated"); |
| 47 | |
| 48 | namespace { |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 49 | /// This is a utility for simplifying induction variables |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 50 | /// based on ScalarEvolution. It is the primary instrument of the |
| 51 | /// IndvarSimplify pass, but it may also be directly invoked to cleanup after |
| 52 | /// other loop passes that preserve SCEV. |
| 53 | class SimplifyIndvar { |
| 54 | Loop *L; |
| 55 | LoopInfo *LI; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 56 | ScalarEvolution *SE; |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 57 | DominatorTree *DT; |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 58 | SCEVExpander &Rewriter; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 59 | SmallVectorImpl<WeakTrackingVH> &DeadInsts; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 60 | |
| 61 | bool Changed; |
| 62 | |
| 63 | public: |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 64 | SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT, |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 65 | LoopInfo *LI, SCEVExpander &Rewriter, |
| 66 | SmallVectorImpl<WeakTrackingVH> &Dead) |
| 67 | : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead), |
| 68 | Changed(false) { |
Andrew Trick | e629d00 | 2011-08-10 04:22:26 +0000 | [diff] [blame] | 69 | assert(LI && "IV simplification requires LoopInfo"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 70 | } |
| 71 | |
| 72 | bool hasChanged() const { return Changed; } |
| 73 | |
| 74 | /// Iteratively perform simplification on a worklist of users of the |
| 75 | /// specified induction variable. This is the top-level driver that applies |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 76 | /// all simplifications to users of an IV. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 77 | void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 78 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 79 | Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 80 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 81 | bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand); |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 82 | bool replaceIVUserWithLoopInvariant(Instruction *UseInst); |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 83 | |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 84 | bool eliminateOverflowIntrinsic(CallInst *CI); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 85 | bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand); |
| 86 | void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand); |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 87 | void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, |
| 88 | bool IsSigned); |
| 89 | void replaceRemWithNumerator(BinaryOperator *Rem); |
| 90 | void replaceRemWithNumeratorOrZero(BinaryOperator *Rem); |
| 91 | void replaceSRemWithURem(BinaryOperator *Rem); |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 92 | bool eliminateSDiv(BinaryOperator *SDiv); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 93 | bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand); |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 94 | bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand); |
Philip Reames | 357cd32 | 2017-10-31 22:56:16 +0000 | [diff] [blame] | 95 | |
| 96 | |
| 97 | private: |
| 98 | // Wrapped around ScalarEvolution::isLoopInvariantPredicate which returns |
| 99 | // true only when a free expansion is available. |
| 100 | bool isCheapLoopInvariantPredicate(ICmpInst::Predicate Pred, |
| 101 | const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 102 | const SmallDenseMap<const SCEV*, Value*> &FreeExpansions, |
| 103 | ICmpInst::Predicate &InvariantPred, |
| 104 | Value *&LHSV, Value *& RHSV); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 105 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 106 | } |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 107 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 108 | /// Fold an IV operand into its use. This removes increments of an |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 109 | /// aligned IV when used by a instruction that ignores the low bits. |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 110 | /// |
Andrew Trick | 7251e41 | 2011-09-19 17:54:39 +0000 | [diff] [blame] | 111 | /// IVOperand is guaranteed SCEVable, but UseInst may not be. |
| 112 | /// |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 113 | /// Return the operand of IVOperand for this induction variable if IVOperand can |
Andrew Trick | 6dbb060 | 2011-08-10 18:07:05 +0000 | [diff] [blame] | 114 | /// be folded (in case more folding opportunities have been exposed). |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 115 | /// Otherwise return null. |
| 116 | Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 117 | Value *IVSrc = nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 118 | unsigned OperIdx = 0; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 119 | const SCEV *FoldedExpr = nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 120 | switch (UseInst->getOpcode()) { |
| 121 | default: |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 122 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 123 | case Instruction::UDiv: |
| 124 | case Instruction::LShr: |
| 125 | // We're only interested in the case where we know something about |
| 126 | // the numerator and have a constant denominator. |
| 127 | if (IVOperand != UseInst->getOperand(OperIdx) || |
| 128 | !isa<ConstantInt>(UseInst->getOperand(1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 129 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 130 | |
| 131 | // Attempt to fold a binary operator with constant operand. |
| 132 | // e.g. ((I + 1) >> 2) => I >> 2 |
Andrew Trick | 9490458 | 2011-11-17 23:36:35 +0000 | [diff] [blame] | 133 | if (!isa<BinaryOperator>(IVOperand) |
| 134 | || !isa<ConstantInt>(IVOperand->getOperand(1))) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 135 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 136 | |
| 137 | IVSrc = IVOperand->getOperand(0); |
| 138 | // IVSrc must be the (SCEVable) IV, since the other operand is const. |
| 139 | assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand"); |
| 140 | |
| 141 | ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1)); |
| 142 | if (UseInst->getOpcode() == Instruction::LShr) { |
| 143 | // Get a constant for the divisor. See createSCEV. |
| 144 | uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth(); |
| 145 | if (D->getValue().uge(BitWidth)) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 146 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 147 | |
| 148 | D = ConstantInt::get(UseInst->getContext(), |
Benjamin Kramer | fc3ea6f | 2013-07-11 16:05:50 +0000 | [diff] [blame] | 149 | APInt::getOneBitSet(BitWidth, D->getZExtValue())); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 150 | } |
| 151 | FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D)); |
| 152 | } |
| 153 | // We have something that might fold it's operand. Compare SCEVs. |
| 154 | if (!SE->isSCEVable(UseInst->getType())) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 155 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 156 | |
| 157 | // Bypass the operand if SCEV can prove it has no effect. |
| 158 | if (SE->getSCEV(UseInst) != FoldedExpr) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 159 | return nullptr; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 160 | |
| 161 | DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand |
| 162 | << " -> " << *UseInst << '\n'); |
| 163 | |
| 164 | UseInst->setOperand(OperIdx, IVSrc); |
| 165 | assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper"); |
| 166 | |
| 167 | ++NumElimOperand; |
| 168 | Changed = true; |
| 169 | if (IVOperand->use_empty()) |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 170 | DeadInsts.emplace_back(IVOperand); |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 171 | return IVSrc; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 172 | } |
| 173 | |
Philip Reames | dc417a9 | 2017-10-31 18:04:57 +0000 | [diff] [blame] | 174 | bool SimplifyIndvar::isCheapLoopInvariantPredicate(ICmpInst::Predicate Pred, |
| 175 | const SCEV *LHS, const SCEV *RHS, const Loop *L, |
| 176 | const SmallDenseMap<const SCEV*, Value*> &FreeExpansions, |
| 177 | ICmpInst::Predicate &InvariantPred, |
| 178 | Value *&LHSV, Value *& RHSV) { |
| 179 | |
| 180 | const SCEV *InvariantLHS, *InvariantRHS; |
| 181 | if (!SE->isLoopInvariantPredicate(Pred, LHS, RHS, L, InvariantPred, |
| 182 | InvariantLHS, InvariantRHS)) |
| 183 | return false; |
| 184 | |
| 185 | // Rewrite the comparison to a loop invariant comparison if it can be done |
| 186 | // cheaply, where cheaply means "we don't need to emit any new |
| 187 | // instructions". |
| 188 | LHSV = FreeExpansions.lookup(InvariantLHS); |
| 189 | RHSV = FreeExpansions.lookup(InvariantRHS); |
| 190 | |
| 191 | return (LHSV && RHSV); |
| 192 | } |
| 193 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 194 | /// SimplifyIVUsers helper for eliminating useless |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 195 | /// comparisons against an induction variable. |
| 196 | void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) { |
| 197 | unsigned IVOperIdx = 0; |
| 198 | ICmpInst::Predicate Pred = ICmp->getPredicate(); |
Max Kazantsev | b9edcbc | 2017-07-08 17:17:30 +0000 | [diff] [blame] | 199 | ICmpInst::Predicate OriginalPred = Pred; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 200 | if (IVOperand != ICmp->getOperand(0)) { |
| 201 | // Swapped |
| 202 | assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand"); |
| 203 | IVOperIdx = 1; |
| 204 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 205 | } |
| 206 | |
Philip Reames | 29dd40b | 2017-10-26 22:02:16 +0000 | [diff] [blame] | 207 | // Get the SCEVs for the ICmp operands (in the specific context of the |
| 208 | // current loop) |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 209 | const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent()); |
Philip Reames | 29dd40b | 2017-10-26 22:02:16 +0000 | [diff] [blame] | 210 | const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop); |
| 211 | const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 212 | |
Philip Reames | 357cd32 | 2017-10-31 22:56:16 +0000 | [diff] [blame] | 213 | SmallDenseMap<const SCEV*, Value*> CheapExpansions; |
| 214 | CheapExpansions[S] = ICmp->getOperand(IVOperIdx); |
| 215 | CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx); |
| 216 | |
| 217 | // TODO: Support multiple entry loops? (We currently bail out of these in |
| 218 | // the IndVarSimplify pass) |
| 219 | auto *PN = dyn_cast<PHINode>(IVOperand); |
| 220 | if (PN) |
| 221 | if (auto *BB = L->getLoopPredecessor()) { |
| 222 | Value *Incoming = PN->getIncomingValueForBlock(BB); |
| 223 | const SCEV *IncomingS = SE->getSCEV(Incoming); |
| 224 | CheapExpansions[IncomingS] = Incoming; |
| 225 | } |
| 226 | |
| 227 | ICmpInst::Predicate NewPred; |
| 228 | Value *NewLHS = nullptr, *NewRHS = nullptr; |
| 229 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 230 | // If the condition is always true or always false, replace it with |
| 231 | // a constant value. |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 232 | if (SE->isKnownPredicate(Pred, S, X)) { |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 233 | ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext())); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 234 | DeadInsts.emplace_back(ICmp); |
Sanjoy Das | c18115d | 2015-08-06 20:43:28 +0000 | [diff] [blame] | 235 | DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 236 | } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) { |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 237 | ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext())); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 238 | DeadInsts.emplace_back(ICmp); |
Sanjoy Das | c18115d | 2015-08-06 20:43:28 +0000 | [diff] [blame] | 239 | DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n'); |
Philip Reames | 357cd32 | 2017-10-31 22:56:16 +0000 | [diff] [blame] | 240 | } else if (PN && |
| 241 | isCheapLoopInvariantPredicate(Pred, S, X, L, CheapExpansions, |
| 242 | NewPred, NewLHS, NewRHS)) { |
| 243 | DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n'); |
| 244 | ICmp->setPredicate(NewPred); |
| 245 | assert(NewLHS && NewRHS); |
| 246 | ICmp->setOperand(0, NewLHS); |
| 247 | ICmp->setOperand(1, NewRHS); |
Max Kazantsev | b9edcbc | 2017-07-08 17:17:30 +0000 | [diff] [blame] | 248 | } else if (ICmpInst::isSigned(OriginalPred) && |
| 249 | SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) { |
| 250 | // If we were unable to make anything above, all we can is to canonicalize |
| 251 | // the comparison hoping that it will open the doors for other |
| 252 | // optimizations. If we find out that we compare two non-negative values, |
| 253 | // we turn the instruction's predicate to its unsigned version. Note that |
| 254 | // we cannot rely on Pred here unless we check if we have swapped it. |
| 255 | assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?"); |
| 256 | DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n'); |
| 257 | ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred)); |
Sanjoy Das | 5dab205 | 2015-07-27 21:42:49 +0000 | [diff] [blame] | 258 | } else |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 259 | return; |
| 260 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 261 | ++NumElimCmp; |
| 262 | Changed = true; |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 263 | } |
| 264 | |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 265 | bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) { |
| 266 | // Get the SCEVs for the ICmp operands. |
| 267 | auto *N = SE->getSCEV(SDiv->getOperand(0)); |
| 268 | auto *D = SE->getSCEV(SDiv->getOperand(1)); |
| 269 | |
| 270 | // Simplify unnecessary loops away. |
| 271 | const Loop *L = LI->getLoopFor(SDiv->getParent()); |
| 272 | N = SE->getSCEVAtScope(N, L); |
| 273 | D = SE->getSCEVAtScope(D, L); |
| 274 | |
| 275 | // Replace sdiv by udiv if both of the operands are non-negative |
| 276 | if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) { |
| 277 | auto *UDiv = BinaryOperator::Create( |
| 278 | BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1), |
| 279 | SDiv->getName() + ".udiv", SDiv); |
| 280 | UDiv->setIsExact(SDiv->isExact()); |
| 281 | SDiv->replaceAllUsesWith(UDiv); |
| 282 | DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n'); |
| 283 | ++NumSimplifiedSDiv; |
| 284 | Changed = true; |
| 285 | DeadInsts.push_back(SDiv); |
| 286 | return true; |
| 287 | } |
| 288 | |
| 289 | return false; |
| 290 | } |
| 291 | |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 292 | // i %s n -> i %u n if i >= 0 and n >= 0 |
| 293 | void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) { |
| 294 | auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); |
| 295 | auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D, |
| 296 | Rem->getName() + ".urem", Rem); |
| 297 | Rem->replaceAllUsesWith(URem); |
| 298 | DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n'); |
| 299 | ++NumSimplifiedSRem; |
Hongbin Zheng | bbe448a | 2017-09-25 18:10:36 +0000 | [diff] [blame] | 300 | Changed = true; |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 301 | DeadInsts.emplace_back(Rem); |
| 302 | } |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 303 | |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 304 | // i % n --> i if i is in [0,n). |
| 305 | void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) { |
| 306 | Rem->replaceAllUsesWith(Rem->getOperand(0)); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 307 | DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); |
| 308 | ++NumElimRem; |
| 309 | Changed = true; |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 310 | DeadInsts.emplace_back(Rem); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 311 | } |
| 312 | |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 313 | // (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n). |
| 314 | void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) { |
| 315 | auto *T = Rem->getType(); |
| 316 | auto *N = Rem->getOperand(0), *D = Rem->getOperand(1); |
| 317 | ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D); |
| 318 | SelectInst *Sel = |
| 319 | SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem); |
| 320 | Rem->replaceAllUsesWith(Sel); |
| 321 | DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n'); |
| 322 | ++NumElimRem; |
| 323 | Changed = true; |
| 324 | DeadInsts.emplace_back(Rem); |
| 325 | } |
| 326 | |
| 327 | /// SimplifyIVUsers helper for eliminating useless remainder operations |
| 328 | /// operating on an induction variable or replacing srem by urem. |
| 329 | void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand, |
| 330 | bool IsSigned) { |
| 331 | auto *NValue = Rem->getOperand(0); |
| 332 | auto *DValue = Rem->getOperand(1); |
| 333 | // We're only interested in the case where we know something about |
| 334 | // the numerator, unless it is a srem, because we want to replace srem by urem |
| 335 | // in general. |
| 336 | bool UsedAsNumerator = IVOperand == NValue; |
| 337 | if (!UsedAsNumerator && !IsSigned) |
| 338 | return; |
| 339 | |
| 340 | const SCEV *N = SE->getSCEV(NValue); |
| 341 | |
| 342 | // Simplify unnecessary loops away. |
| 343 | const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent()); |
| 344 | N = SE->getSCEVAtScope(N, ICmpLoop); |
| 345 | |
| 346 | bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N); |
| 347 | |
| 348 | // Do not proceed if the Numerator may be negative |
| 349 | if (!IsNumeratorNonNegative) |
| 350 | return; |
| 351 | |
| 352 | const SCEV *D = SE->getSCEV(DValue); |
| 353 | D = SE->getSCEVAtScope(D, ICmpLoop); |
| 354 | |
| 355 | if (UsedAsNumerator) { |
| 356 | auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; |
| 357 | if (SE->isKnownPredicate(LT, N, D)) { |
| 358 | replaceRemWithNumerator(Rem); |
| 359 | return; |
| 360 | } |
| 361 | |
| 362 | auto *T = Rem->getType(); |
| 363 | const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T)); |
| 364 | if (SE->isKnownPredicate(LT, NLessOne, D)) { |
| 365 | replaceRemWithNumeratorOrZero(Rem); |
| 366 | return; |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | // Try to replace SRem with URem, if both N and D are known non-negative. |
| 371 | // Since we had already check N, we only need to check D now |
| 372 | if (!IsSigned || !SE->isKnownNonNegative(D)) |
| 373 | return; |
| 374 | |
| 375 | replaceSRemWithURem(Rem); |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 376 | } |
| 377 | |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 378 | bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) { |
| 379 | auto *F = CI->getCalledFunction(); |
| 380 | if (!F) |
| 381 | return false; |
| 382 | |
| 383 | typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)( |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 384 | const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 385 | typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)( |
Max Kazantsev | 8d0322e | 2017-06-30 05:04:09 +0000 | [diff] [blame] | 386 | const SCEV *, Type *, unsigned); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 387 | |
| 388 | OperationFunctionTy Operation; |
| 389 | ExtensionFunctionTy Extension; |
| 390 | |
| 391 | Instruction::BinaryOps RawOp; |
| 392 | |
| 393 | // We always have exactly one of nsw or nuw. If NoSignedOverflow is false, we |
| 394 | // have nuw. |
| 395 | bool NoSignedOverflow; |
| 396 | |
| 397 | switch (F->getIntrinsicID()) { |
| 398 | default: |
| 399 | return false; |
| 400 | |
| 401 | case Intrinsic::sadd_with_overflow: |
| 402 | Operation = &ScalarEvolution::getAddExpr; |
| 403 | Extension = &ScalarEvolution::getSignExtendExpr; |
| 404 | RawOp = Instruction::Add; |
| 405 | NoSignedOverflow = true; |
| 406 | break; |
| 407 | |
| 408 | case Intrinsic::uadd_with_overflow: |
| 409 | Operation = &ScalarEvolution::getAddExpr; |
| 410 | Extension = &ScalarEvolution::getZeroExtendExpr; |
| 411 | RawOp = Instruction::Add; |
| 412 | NoSignedOverflow = false; |
| 413 | break; |
| 414 | |
| 415 | case Intrinsic::ssub_with_overflow: |
| 416 | Operation = &ScalarEvolution::getMinusSCEV; |
| 417 | Extension = &ScalarEvolution::getSignExtendExpr; |
| 418 | RawOp = Instruction::Sub; |
| 419 | NoSignedOverflow = true; |
| 420 | break; |
| 421 | |
| 422 | case Intrinsic::usub_with_overflow: |
| 423 | Operation = &ScalarEvolution::getMinusSCEV; |
| 424 | Extension = &ScalarEvolution::getZeroExtendExpr; |
| 425 | RawOp = Instruction::Sub; |
| 426 | NoSignedOverflow = false; |
| 427 | break; |
| 428 | } |
| 429 | |
| 430 | const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0)); |
| 431 | const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1)); |
| 432 | |
| 433 | auto *NarrowTy = cast<IntegerType>(LHS->getType()); |
| 434 | auto *WideTy = |
| 435 | IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); |
| 436 | |
| 437 | const SCEV *A = |
Max Kazantsev | 8d0322e | 2017-06-30 05:04:09 +0000 | [diff] [blame] | 438 | (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), |
| 439 | WideTy, 0); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 440 | const SCEV *B = |
Max Kazantsev | 8d0322e | 2017-06-30 05:04:09 +0000 | [diff] [blame] | 441 | (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0), |
| 442 | (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0); |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 443 | |
| 444 | if (A != B) |
| 445 | return false; |
| 446 | |
| 447 | // Proved no overflow, nuke the overflow check and, if possible, the overflow |
| 448 | // intrinsic as well. |
| 449 | |
| 450 | BinaryOperator *NewResult = BinaryOperator::Create( |
| 451 | RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI); |
| 452 | |
| 453 | if (NoSignedOverflow) |
| 454 | NewResult->setHasNoSignedWrap(true); |
| 455 | else |
| 456 | NewResult->setHasNoUnsignedWrap(true); |
| 457 | |
| 458 | SmallVector<ExtractValueInst *, 4> ToDelete; |
| 459 | |
| 460 | for (auto *U : CI->users()) { |
| 461 | if (auto *EVI = dyn_cast<ExtractValueInst>(U)) { |
| 462 | if (EVI->getIndices()[0] == 1) |
| 463 | EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext())); |
| 464 | else { |
| 465 | assert(EVI->getIndices()[0] == 0 && "Only two possibilities!"); |
| 466 | EVI->replaceAllUsesWith(NewResult); |
| 467 | } |
| 468 | ToDelete.push_back(EVI); |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | for (auto *EVI : ToDelete) |
| 473 | EVI->eraseFromParent(); |
| 474 | |
| 475 | if (CI->use_empty()) |
| 476 | CI->eraseFromParent(); |
| 477 | |
| 478 | return true; |
| 479 | } |
| 480 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 481 | /// Eliminate an operation that consumes a simple IV and has no observable |
| 482 | /// side-effect given the range of IV values. IVOperand is guaranteed SCEVable, |
| 483 | /// but UseInst may not be. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 484 | bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst, |
| 485 | Instruction *IVOperand) { |
| 486 | if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) { |
| 487 | eliminateIVComparison(ICmp, IVOperand); |
| 488 | return true; |
| 489 | } |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 490 | if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) { |
| 491 | bool IsSRem = Bin->getOpcode() == Instruction::SRem; |
| 492 | if (IsSRem || Bin->getOpcode() == Instruction::URem) { |
Hongbin Zheng | f0093e4 | 2017-09-25 17:39:40 +0000 | [diff] [blame] | 493 | simplifyIVRemainder(Bin, IVOperand, IsSRem); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 494 | return true; |
| 495 | } |
Hongbin Zheng | bfd7c38 | 2017-03-30 21:56:56 +0000 | [diff] [blame] | 496 | |
| 497 | if (Bin->getOpcode() == Instruction::SDiv) |
| 498 | return eliminateSDiv(Bin); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 499 | } |
| 500 | |
Sanjoy Das | ae09b3c | 2016-05-29 00:36:25 +0000 | [diff] [blame] | 501 | if (auto *CI = dyn_cast<CallInst>(UseInst)) |
| 502 | if (eliminateOverflowIntrinsic(CI)) |
| 503 | return true; |
| 504 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 505 | if (eliminateIdentitySCEV(UseInst, IVOperand)) |
| 506 | return true; |
| 507 | |
| 508 | return false; |
| 509 | } |
| 510 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 511 | static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) { |
| 512 | if (auto *BB = L->getLoopPreheader()) |
| 513 | return BB->getTerminator(); |
| 514 | |
| 515 | return Hint; |
| 516 | } |
| 517 | |
| 518 | /// Replace the UseInst with a constant if possible. |
| 519 | bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) { |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 520 | if (!SE->isSCEVable(I->getType())) |
| 521 | return false; |
| 522 | |
| 523 | // Get the symbolic expression for this instruction. |
| 524 | const SCEV *S = SE->getSCEV(I); |
| 525 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 526 | if (!SE->isLoopInvariant(S, L)) |
Hongbin Zheng | c8abdf5 | 2017-09-29 16:32:12 +0000 | [diff] [blame] | 527 | return false; |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 528 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 529 | // Do not generate something ridiculous even if S is loop invariant. |
| 530 | if (Rewriter.isHighCostExpansion(S, L, I)) |
Hongbin Zheng | c8abdf5 | 2017-09-29 16:32:12 +0000 | [diff] [blame] | 531 | return false; |
| 532 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 533 | auto *IP = GetLoopInvariantInsertPosition(L, I); |
| 534 | auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP); |
| 535 | |
| 536 | I->replaceAllUsesWith(Invariant); |
| 537 | DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I |
| 538 | << " with loop invariant: " << *S << '\n'); |
Hongbin Zheng | c8abdf5 | 2017-09-29 16:32:12 +0000 | [diff] [blame] | 539 | ++NumFoldedUser; |
| 540 | Changed = true; |
| 541 | DeadInsts.emplace_back(I); |
| 542 | return true; |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 543 | } |
| 544 | |
Sanjoy Das | 088bb0e | 2015-10-06 21:44:39 +0000 | [diff] [blame] | 545 | /// Eliminate any operation that SCEV can prove is an identity function. |
| 546 | bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst, |
| 547 | Instruction *IVOperand) { |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 548 | if (!SE->isSCEVable(UseInst->getType()) || |
| 549 | (UseInst->getType() != IVOperand->getType()) || |
| 550 | (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand))) |
| 551 | return false; |
| 552 | |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 553 | // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the |
| 554 | // dominator tree, even if X is an operand to Y. For instance, in |
| 555 | // |
| 556 | // %iv = phi i32 {0,+,1} |
| 557 | // br %cond, label %left, label %merge |
| 558 | // |
| 559 | // left: |
| 560 | // %X = add i32 %iv, 0 |
| 561 | // br label %merge |
| 562 | // |
| 563 | // merge: |
| 564 | // %M = phi (%X, %iv) |
| 565 | // |
| 566 | // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and |
| 567 | // %M.replaceAllUsesWith(%X) would be incorrect. |
| 568 | |
| 569 | if (isa<PHINode>(UseInst)) |
| 570 | // If UseInst is not a PHI node then we know that IVOperand dominates |
| 571 | // UseInst directly from the legality of SSA. |
| 572 | if (!DT || !DT->dominates(IVOperand, UseInst)) |
| 573 | return false; |
| 574 | |
Sanjoy Das | 0015e5a | 2015-10-07 17:38:31 +0000 | [diff] [blame] | 575 | if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand)) |
| 576 | return false; |
| 577 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 578 | DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n'); |
| 579 | |
| 580 | UseInst->replaceAllUsesWith(IVOperand); |
| 581 | ++NumElimIdentity; |
| 582 | Changed = true; |
Benjamin Kramer | f5e2fc4 | 2015-05-29 19:43:39 +0000 | [diff] [blame] | 583 | DeadInsts.emplace_back(UseInst); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 584 | return true; |
| 585 | } |
| 586 | |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 587 | /// Annotate BO with nsw / nuw if it provably does not signed-overflow / |
| 588 | /// unsigned-overflow. Returns true if anything changed, false otherwise. |
| 589 | bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO, |
| 590 | Value *IVOperand) { |
| 591 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 592 | // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`. |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 593 | if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap()) |
| 594 | return false; |
| 595 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 596 | const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *, |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 597 | SCEV::NoWrapFlags, unsigned); |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 598 | switch (BO->getOpcode()) { |
| 599 | default: |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 600 | return false; |
| 601 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 602 | case Instruction::Add: |
| 603 | GetExprForBO = &ScalarEvolution::getAddExpr; |
| 604 | break; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 605 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 606 | case Instruction::Sub: |
| 607 | GetExprForBO = &ScalarEvolution::getMinusSCEV; |
| 608 | break; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 609 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 610 | case Instruction::Mul: |
| 611 | GetExprForBO = &ScalarEvolution::getMulExpr; |
| 612 | break; |
| 613 | } |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 614 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 615 | unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth(); |
| 616 | Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2); |
| 617 | const SCEV *LHS = SE->getSCEV(BO->getOperand(0)); |
| 618 | const SCEV *RHS = SE->getSCEV(BO->getOperand(1)); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 619 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 620 | bool Changed = false; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 621 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 622 | if (!BO->hasNoUnsignedWrap()) { |
| 623 | const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy); |
| 624 | const SCEV *OpAfterExtend = (SE->*GetExprForBO)( |
| 625 | SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy), |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 626 | SCEV::FlagAnyWrap, 0u); |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 627 | if (ExtendAfterOp == OpAfterExtend) { |
| 628 | BO->setHasNoUnsignedWrap(); |
| 629 | SE->forgetValue(BO); |
| 630 | Changed = true; |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 631 | } |
| 632 | } |
| 633 | |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 634 | if (!BO->hasNoSignedWrap()) { |
| 635 | const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy); |
| 636 | const SCEV *OpAfterExtend = (SE->*GetExprForBO)( |
| 637 | SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy), |
Max Kazantsev | dc80366 | 2017-06-15 11:48:21 +0000 | [diff] [blame] | 638 | SCEV::FlagAnyWrap, 0u); |
Sanjoy Das | a5397c0 | 2015-03-04 22:24:23 +0000 | [diff] [blame] | 639 | if (ExtendAfterOp == OpAfterExtend) { |
| 640 | BO->setHasNoSignedWrap(); |
| 641 | SE->forgetValue(BO); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 642 | Changed = true; |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | return Changed; |
| 647 | } |
| 648 | |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 649 | /// Annotate the Shr in (X << IVOperand) >> C as exact using the |
| 650 | /// information from the IV's range. Returns true if anything changed, false |
| 651 | /// otherwise. |
| 652 | bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO, |
| 653 | Value *IVOperand) { |
| 654 | using namespace llvm::PatternMatch; |
| 655 | |
| 656 | if (BO->getOpcode() == Instruction::Shl) { |
| 657 | bool Changed = false; |
| 658 | ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand)); |
| 659 | for (auto *U : BO->users()) { |
| 660 | const APInt *C; |
| 661 | if (match(U, |
| 662 | m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) || |
| 663 | match(U, |
| 664 | m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) { |
| 665 | BinaryOperator *Shr = cast<BinaryOperator>(U); |
| 666 | if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) { |
| 667 | Shr->setIsExact(true); |
| 668 | Changed = true; |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | return Changed; |
| 673 | } |
| 674 | |
| 675 | return false; |
| 676 | } |
| 677 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 678 | /// Add all uses of Def to the current IV's worklist. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 679 | static void pushIVUsers( |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 680 | Instruction *Def, Loop *L, |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 681 | SmallPtrSet<Instruction*,16> &Simplified, |
| 682 | SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) { |
| 683 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 684 | for (User *U : Def->users()) { |
| 685 | Instruction *UI = cast<Instruction>(U); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 686 | |
| 687 | // Avoid infinite or exponential worklist processing. |
| 688 | // Also ensure unique worklist users. |
| 689 | // If Def is a LoopPhi, it may not be in the Simplified set, so check for |
| 690 | // self edges first. |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 691 | if (UI == Def) |
| 692 | continue; |
| 693 | |
| 694 | // Only change the current Loop, do not change the other parts (e.g. other |
| 695 | // Loops). |
| 696 | if (!L->contains(UI)) |
| 697 | continue; |
| 698 | |
| 699 | // Do not push the same instruction more than once. |
| 700 | if (!Simplified.insert(UI).second) |
| 701 | continue; |
| 702 | |
| 703 | SimpleIVUsers.push_back(std::make_pair(UI, Def)); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 704 | } |
| 705 | } |
| 706 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 707 | /// Return true if this instruction generates a simple SCEV |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 708 | /// expression in terms of that IV. |
| 709 | /// |
Andrew Trick | 6dbb060 | 2011-08-10 18:07:05 +0000 | [diff] [blame] | 710 | /// This is similar to IVUsers' isInteresting() but processes each instruction |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 711 | /// non-recursively when the operand is already known to be a simpleIVUser. |
| 712 | /// |
| 713 | static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) { |
| 714 | if (!SE->isSCEVable(I->getType())) |
| 715 | return false; |
| 716 | |
| 717 | // Get the symbolic expression for this instruction. |
| 718 | const SCEV *S = SE->getSCEV(I); |
| 719 | |
| 720 | // Only consider affine recurrences. |
| 721 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); |
| 722 | if (AR && AR->getLoop() == L) |
| 723 | return true; |
| 724 | |
| 725 | return false; |
| 726 | } |
| 727 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 728 | /// Iteratively perform simplification on a worklist of users |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 729 | /// of the specified induction variable. Each successive simplification may push |
| 730 | /// more users which may themselves be candidates for simplification. |
| 731 | /// |
| 732 | /// This algorithm does not require IVUsers analysis. Instead, it simplifies |
| 733 | /// instructions in-place during analysis. Rather than rewriting induction |
| 734 | /// variables bottom-up from their users, it transforms a chain of IVUsers |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 735 | /// top-down, updating the IR only when it encounters a clear optimization |
| 736 | /// opportunity. |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 737 | /// |
| 738 | /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers. |
| 739 | /// |
| 740 | void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) { |
Andrew Trick | 7251e41 | 2011-09-19 17:54:39 +0000 | [diff] [blame] | 741 | if (!SE->isSCEVable(CurrIV->getType())) |
| 742 | return; |
| 743 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 744 | // Instructions processed by SimplifyIndvar for CurrIV. |
| 745 | SmallPtrSet<Instruction*,16> Simplified; |
| 746 | |
| 747 | // Use-def pairs if IV users waiting to be processed for CurrIV. |
| 748 | SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers; |
| 749 | |
| 750 | // Push users of the current LoopPhi. In rare cases, pushIVUsers may be |
| 751 | // called multiple times for the same LoopPhi. This is the proper thing to |
| 752 | // do for loop header phis that use each other. |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 753 | pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 754 | |
| 755 | while (!SimpleIVUsers.empty()) { |
| 756 | std::pair<Instruction*, Instruction*> UseOper = |
| 757 | SimpleIVUsers.pop_back_val(); |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 758 | Instruction *UseInst = UseOper.first; |
| 759 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 760 | // Bypass back edges to avoid extra work. |
Andrew Trick | 0ba77a0 | 2013-12-23 23:31:49 +0000 | [diff] [blame] | 761 | if (UseInst == CurrIV) continue; |
| 762 | |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 763 | // Try to replace UseInst with a loop invariant before any other |
| 764 | // simplifications. |
| 765 | if (replaceIVUserWithLoopInvariant(UseInst)) |
Hongbin Zheng | d1b7b2e | 2017-09-27 03:11:46 +0000 | [diff] [blame] | 766 | continue; |
| 767 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 768 | Instruction *IVOperand = UseOper.second; |
| 769 | for (unsigned N = 0; IVOperand; ++N) { |
| 770 | assert(N <= Simplified.size() && "runaway iteration"); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 771 | |
Andrew Trick | 74664d5 | 2011-08-10 04:01:31 +0000 | [diff] [blame] | 772 | Value *NewOper = foldIVUser(UseOper.first, IVOperand); |
| 773 | if (!NewOper) |
| 774 | break; // done folding |
| 775 | IVOperand = dyn_cast<Instruction>(NewOper); |
| 776 | } |
| 777 | if (!IVOperand) |
| 778 | continue; |
| 779 | |
| 780 | if (eliminateIVUser(UseOper.first, IVOperand)) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 781 | pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 782 | continue; |
| 783 | } |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 784 | |
| 785 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) { |
David Green | b26a0a4 | 2017-07-05 13:25:58 +0000 | [diff] [blame] | 786 | if ((isa<OverflowingBinaryOperator>(BO) && |
| 787 | strengthenOverflowingOperation(BO, IVOperand)) || |
| 788 | (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) { |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 789 | // re-queue uses of the now modified binary operator and fall |
| 790 | // through to the checks that remain. |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 791 | pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers); |
Sanjoy Das | 7c0ce26 | 2015-01-06 19:02:56 +0000 | [diff] [blame] | 792 | } |
| 793 | } |
| 794 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 795 | CastInst *Cast = dyn_cast<CastInst>(UseOper.first); |
| 796 | if (V && Cast) { |
| 797 | V->visitCast(Cast); |
| 798 | continue; |
| 799 | } |
| 800 | if (isSimpleIVUser(UseOper.first, L, SE)) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 801 | pushIVUsers(UseOper.first, L, Simplified, SimpleIVUsers); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 802 | } |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | namespace llvm { |
| 807 | |
David Blaikie | a379b181 | 2011-12-20 02:50:00 +0000 | [diff] [blame] | 808 | void IVVisitor::anchor() { } |
| 809 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 810 | /// Simplify instructions that use this induction variable |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 811 | /// by using ScalarEvolution to analyze the IV's recurrence. |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 812 | bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 813 | LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead, |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 814 | SCEVExpander &Rewriter, IVVisitor *V) { |
| 815 | SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Rewriter, |
| 816 | Dead); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 817 | SIV.simplifyUsers(CurrIV, V); |
| 818 | return SIV.hasChanged(); |
| 819 | } |
| 820 | |
Sanjay Patel | 7777b50 | 2014-11-12 18:07:42 +0000 | [diff] [blame] | 821 | /// Simplify users of induction variables within this |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 822 | /// loop. This does not actually change or add IVs. |
Sanjoy Das | 5c8bead | 2015-10-06 21:44:49 +0000 | [diff] [blame] | 823 | bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 824 | LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 825 | SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars"); |
| 826 | #ifndef NDEBUG |
| 827 | Rewriter.setDebugType(DEBUG_TYPE); |
| 828 | #endif |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 829 | bool Changed = false; |
| 830 | for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { |
Hongbin Zheng | d36f2030 | 2017-10-12 02:54:11 +0000 | [diff] [blame] | 831 | Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead, Rewriter); |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 832 | } |
| 833 | return Changed; |
| 834 | } |
| 835 | |
Andrew Trick | 3ec331e | 2011-08-10 03:46:27 +0000 | [diff] [blame] | 836 | } // namespace llvm |