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