blob: 63216423f7594b6003e0074d3335af5fc98f9cae [file] [log] [blame]
Chris Lattnerdc67e132010-01-05 07:44:46 +00001//===- InstCombineShifts.cpp ----------------------------------------------===//
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 the visitShl, visitLShr, and visitAShr functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eli Friedman911e12f2011-07-20 21:57:23 +000015#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands7f60dc12011-01-14 00:37:45 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc67e132010-01-05 07:44:46 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattnerdc67e132010-01-05 07:44:46 +000024Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
Chris Lattnerdc67e132010-01-05 07:44:46 +000025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patelcf082032017-01-13 18:08:25 +000026 assert(Op0->getType() == Op1->getType());
Chris Lattnerdc67e132010-01-05 07:44:46 +000027
Chris Lattnerdc67e132010-01-05 07:44:46 +000028 // See if we can fold away this shift.
29 if (SimplifyDemandedInstructionBits(I))
30 return &I;
31
32 // Try to fold constant and into select arguments.
33 if (isa<Constant>(Op0))
34 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
35 if (Instruction *R = FoldOpIntoSelect(I, SI))
36 return R;
37
Matt Arsenaultfed3dc82014-04-14 21:50:37 +000038 if (Constant *CUI = dyn_cast<Constant>(Op1))
Chris Lattnerdc67e132010-01-05 07:44:46 +000039 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
40 return Res;
Benjamin Kramerb5afa652010-11-23 18:52:42 +000041
Simon Pilgrim6dd8fab2016-11-01 15:40:30 +000042 // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
43 // iff A and C2 are both positive.
44 Value *A;
45 Constant *C;
46 if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
47 if (isKnownNonNegative(A, DL) && isKnownNonNegative(C, DL))
48 return BinaryOperator::Create(
49 I.getOpcode(), Builder->CreateBinOp(I.getOpcode(), Op0, C), A);
50
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000051 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
Chris Lattner6b657ae2011-02-10 05:36:31 +000052 // Because shifts by negative values (which could occur if A were negative)
53 // are undefined.
Simon Pilgrim6dd8fab2016-11-01 15:40:30 +000054 const APInt *B;
Chris Lattner6b657ae2011-02-10 05:36:31 +000055 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
56 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
57 // demand the sign bit (and many others) here??
58 Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
59 Op1->getName());
60 I.setOperand(1, Rem);
61 return &I;
62 }
Jakub Staszak538e3862012-12-09 15:37:46 +000063
Craig Topperf40110f2014-04-25 05:29:35 +000064 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +000065}
66
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000067/// Return true if we can simplify two logical (either left or right) shifts
68/// that have constant shift amounts.
Sanjay Patelbd8b7792016-04-11 16:11:07 +000069static bool canEvaluateShiftedShift(unsigned FirstShiftAmt,
70 bool IsFirstShiftLeft,
71 Instruction *SecondShift, InstCombiner &IC,
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000072 Instruction *CxtI) {
Sanjay Patel3a48e982016-04-11 17:27:44 +000073 assert(SecondShift->isLogicalShift() && "Unexpected instruction type");
Sanjay Patelb91bcd72016-04-11 17:35:57 +000074
Sanjay Patelbd8b7792016-04-11 16:11:07 +000075 // We need constant shifts.
76 auto *SecondShiftConst = dyn_cast<ConstantInt>(SecondShift->getOperand(1));
77 if (!SecondShiftConst)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000078 return false;
79
Sanjay Patelbd8b7792016-04-11 16:11:07 +000080 unsigned SecondShiftAmt = SecondShiftConst->getZExtValue();
Sanjay Patel37129072016-04-11 17:11:55 +000081 bool IsSecondShiftLeft = SecondShift->getOpcode() == Instruction::Shl;
Sanjay Patelbd8b7792016-04-11 16:11:07 +000082
Sanjay Patel37129072016-04-11 17:11:55 +000083 // We can always fold shl(c1) + shl(c2) -> shl(c1+c2).
84 // We can always fold lshr(c1) + lshr(c2) -> lshr(c1+c2).
85 if (IsFirstShiftLeft == IsSecondShiftLeft)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000086 return true;
87
Sanjay Patel37129072016-04-11 17:11:55 +000088 // We can always fold lshr(c) + shl(c) -> and(c2).
89 // We can always fold shl(c) + lshr(c) -> and(c2).
90 if (FirstShiftAmt == SecondShiftAmt)
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000091 return true;
92
Sanjay Patelbd8b7792016-04-11 16:11:07 +000093 unsigned TypeWidth = SecondShift->getType()->getScalarSizeInBits();
Sanjay Patel6eaff5c2016-04-11 15:43:41 +000094
Sanjay Patelbd8b7792016-04-11 16:11:07 +000095 // If the 2nd shift is bigger than the 1st, we can fold:
Sanjay Patel37129072016-04-11 17:11:55 +000096 // lshr(c1) + shl(c2) -> shl(c3) + and(c4) or
97 // shl(c1) + lshr(c2) -> lshr(c3) + and(c4),
Sanjay Patelbd8b7792016-04-11 16:11:07 +000098 // but it isn't profitable unless we know the and'd out bits are already zero.
Sanjay Patel816ec882016-04-11 16:50:32 +000099 // Also check that the 2nd shift is valid (less than the type width) or we'll
100 // crash trying to produce the bit mask for the 'and'.
101 if (SecondShiftAmt > FirstShiftAmt && SecondShiftAmt < TypeWidth) {
Sanjay Patel37129072016-04-11 17:11:55 +0000102 unsigned MaskShift = IsSecondShiftLeft ? TypeWidth - SecondShiftAmt
103 : SecondShiftAmt - FirstShiftAmt;
Sanjay Patelbd8b7792016-04-11 16:11:07 +0000104 APInt Mask = APInt::getLowBitsSet(TypeWidth, FirstShiftAmt) << MaskShift;
105 if (IC.MaskedValueIsZero(SecondShift->getOperand(0), Mask, 0, CxtI))
Sanjay Patel6eaff5c2016-04-11 15:43:41 +0000106 return true;
107 }
108
109 return false;
110}
111
Sanjay Patel20aaf582017-01-15 17:55:35 +0000112/// See if we can compute the specified value, but shifted logically to the left
113/// or right by some number of bits. This should return true if the expression
114/// can be computed for the same cost as the current expression tree. This is
115/// used to eliminate extraneous shifting from things like:
Chris Lattner18d7fc82010-08-27 22:24:38 +0000116/// %C = shl i128 %A, 64
117/// %D = shl i128 %B, 96
118/// %E = or i128 %C, %D
119/// %F = lshr i128 %E, 64
Sanjay Patel20aaf582017-01-15 17:55:35 +0000120/// where the client will ask if E can be computed shifted right by 64-bits. If
121/// this succeeds, getShiftedValue() will be called to produce the value.
122static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
Hal Finkel60db0582014-09-07 18:57:58 +0000123 InstCombiner &IC, Instruction *CxtI) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000124 // We can always evaluate constants shifted.
125 if (isa<Constant>(V))
126 return true;
Jakub Staszak538e3862012-12-09 15:37:46 +0000127
Chris Lattner18d7fc82010-08-27 22:24:38 +0000128 Instruction *I = dyn_cast<Instruction>(V);
129 if (!I) return false;
Jakub Staszak538e3862012-12-09 15:37:46 +0000130
Chris Lattner18d7fc82010-08-27 22:24:38 +0000131 // If this is the opposite shift, we can directly reuse the input of the shift
132 // if the needed bits are already zero in the input. This allows us to reuse
133 // the value which means that we don't care if the shift has multiple uses.
134 // TODO: Handle opposite shift by exact value.
Craig Topperf40110f2014-04-25 05:29:35 +0000135 ConstantInt *CI = nullptr;
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000136 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
137 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000138 if (CI->getZExtValue() == NumBits) {
139 // TODO: Check that the input bits are already zero with MaskedValueIsZero
140#if 0
141 // If this is a truncate of a logical shr, we can truncate it to a smaller
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000142 // lshr iff we know that the bits we would otherwise be shifting in are
Chris Lattner18d7fc82010-08-27 22:24:38 +0000143 // already zeros.
144 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
145 uint32_t BitWidth = Ty->getScalarSizeInBits();
146 if (MaskedValueIsZero(I->getOperand(0),
147 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
148 CI->getLimitedValue(BitWidth) < BitWidth) {
149 return CanEvaluateTruncated(I->getOperand(0), Ty);
150 }
151#endif
Jakub Staszak538e3862012-12-09 15:37:46 +0000152
Chris Lattner18d7fc82010-08-27 22:24:38 +0000153 }
154 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000155
Chris Lattner18d7fc82010-08-27 22:24:38 +0000156 // We can't mutate something that has multiple uses: doing so would
157 // require duplicating the instruction in general, which isn't profitable.
158 if (!I->hasOneUse()) return false;
Jakub Staszak538e3862012-12-09 15:37:46 +0000159
Chris Lattner18d7fc82010-08-27 22:24:38 +0000160 switch (I->getOpcode()) {
161 default: return false;
162 case Instruction::And:
163 case Instruction::Or:
164 case Instruction::Xor:
165 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
Sanjay Patel20aaf582017-01-15 17:55:35 +0000166 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
167 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
Jakub Staszak538e3862012-12-09 15:37:46 +0000168
Sanjay Patel6eaff5c2016-04-11 15:43:41 +0000169 case Instruction::Shl:
Sanjay Patel37129072016-04-11 17:11:55 +0000170 case Instruction::LShr:
Sanjay Patel4b9c6822016-04-11 17:25:23 +0000171 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000172
Chris Lattner18d7fc82010-08-27 22:24:38 +0000173 case Instruction::Select: {
174 SelectInst *SI = cast<SelectInst>(I);
Sanjay Patel690955f2016-01-31 16:34:11 +0000175 Value *TrueVal = SI->getTrueValue();
176 Value *FalseVal = SI->getFalseValue();
Sanjay Patel20aaf582017-01-15 17:55:35 +0000177 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
178 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000179 }
180 case Instruction::PHI: {
181 // We can change a phi if we can change all operands. Note that we never
182 // get into trouble with cyclic PHIs here because we only consider
183 // instructions with a single use.
184 PHINode *PN = cast<PHINode>(I);
Pete Cooper833f34d2015-05-12 20:05:31 +0000185 for (Value *IncValue : PN->incoming_values())
Sanjay Patel20aaf582017-01-15 17:55:35 +0000186 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
Chris Lattner18d7fc82010-08-27 22:24:38 +0000187 return false;
188 return true;
189 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000190 }
Chris Lattner18d7fc82010-08-27 22:24:38 +0000191}
192
Sanjay Patel20aaf582017-01-15 17:55:35 +0000193/// When canEvaluateShifted() returns true for an expression, this function
194/// inserts the new computation that produces the shifted value.
195static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000196 InstCombiner &IC, const DataLayout &DL) {
Chris Lattner18d7fc82010-08-27 22:24:38 +0000197 // We can always evaluate constants shifted.
198 if (Constant *C = dyn_cast<Constant>(V)) {
199 if (isLeftShift)
200 V = IC.Builder->CreateShl(C, NumBits);
201 else
202 V = IC.Builder->CreateLShr(C, NumBits);
203 // If we got a constantexpr back, try to simplify it with TD info.
David Majnemerd536f232016-07-29 03:27:26 +0000204 if (auto *C = dyn_cast<Constant>(V))
205 if (auto *FoldedC =
Justin Bogner99798402016-08-05 01:06:44 +0000206 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
David Majnemerd536f232016-07-29 03:27:26 +0000207 V = FoldedC;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000208 return V;
209 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000210
Chris Lattner18d7fc82010-08-27 22:24:38 +0000211 Instruction *I = cast<Instruction>(V);
212 IC.Worklist.Add(I);
213
214 switch (I->getOpcode()) {
Craig Toppera2886c22012-02-07 05:05:23 +0000215 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
Chris Lattner18d7fc82010-08-27 22:24:38 +0000216 case Instruction::And:
217 case Instruction::Or:
218 case Instruction::Xor:
219 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000221 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000222 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000223 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000224 return I;
Jakub Staszak538e3862012-12-09 15:37:46 +0000225
Chris Lattner18d7fc82010-08-27 22:24:38 +0000226 case Instruction::Shl: {
Eli Friedman530341d2011-07-29 00:18:19 +0000227 BinaryOperator *BO = cast<BinaryOperator>(I);
228 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
Chris Lattner18d7fc82010-08-27 22:24:38 +0000229
230 // We only accept shifts-by-a-constant in CanEvaluateShifted.
Eli Friedman530341d2011-07-29 00:18:19 +0000231 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
232
Chris Lattner18d7fc82010-08-27 22:24:38 +0000233 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
234 if (isLeftShift) {
235 // If this is oversized composite shift, then unsigned shifts get 0.
236 unsigned NewShAmt = NumBits+CI->getZExtValue();
237 if (NewShAmt >= TypeWidth)
238 return Constant::getNullValue(I->getType());
239
Eli Friedman530341d2011-07-29 00:18:19 +0000240 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
241 BO->setHasNoUnsignedWrap(false);
242 BO->setHasNoSignedWrap(false);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000243 return I;
244 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000245
Chris Lattner18d7fc82010-08-27 22:24:38 +0000246 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
247 // zeros.
Chris Lattner6c1395f2010-08-27 22:53:44 +0000248 if (CI->getValue() == NumBits) {
249 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
Eli Friedman530341d2011-07-29 00:18:19 +0000250 V = IC.Builder->CreateAnd(BO->getOperand(0),
251 ConstantInt::get(BO->getContext(), Mask));
Chris Lattner6c1395f2010-08-27 22:53:44 +0000252 if (Instruction *VI = dyn_cast<Instruction>(V)) {
Eli Friedman530341d2011-07-29 00:18:19 +0000253 VI->moveBefore(BO);
254 VI->takeName(BO);
Chris Lattner6c1395f2010-08-27 22:53:44 +0000255 }
256 return V;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000257 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000258
Chris Lattner6c1395f2010-08-27 22:53:44 +0000259 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
260 // the and won't be needed.
261 assert(CI->getZExtValue() > NumBits);
Eli Friedman530341d2011-07-29 00:18:19 +0000262 BO->setOperand(1, ConstantInt::get(BO->getType(),
263 CI->getZExtValue() - NumBits));
264 BO->setHasNoUnsignedWrap(false);
265 BO->setHasNoSignedWrap(false);
266 return BO;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000267 }
Sanjay Patelb91bcd72016-04-11 17:35:57 +0000268 // FIXME: This is almost identical to the SHL case. Refactor both cases into
269 // a helper function.
Chris Lattner18d7fc82010-08-27 22:24:38 +0000270 case Instruction::LShr: {
Eli Friedman530341d2011-07-29 00:18:19 +0000271 BinaryOperator *BO = cast<BinaryOperator>(I);
272 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
Chris Lattner18d7fc82010-08-27 22:24:38 +0000273 // We only accept shifts-by-a-constant in CanEvaluateShifted.
Eli Friedman530341d2011-07-29 00:18:19 +0000274 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
Jakub Staszak538e3862012-12-09 15:37:46 +0000275
Chris Lattner18d7fc82010-08-27 22:24:38 +0000276 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
277 if (!isLeftShift) {
278 // If this is oversized composite shift, then unsigned shifts get 0.
279 unsigned NewShAmt = NumBits+CI->getZExtValue();
280 if (NewShAmt >= TypeWidth)
Eli Friedman530341d2011-07-29 00:18:19 +0000281 return Constant::getNullValue(BO->getType());
Jakub Staszak538e3862012-12-09 15:37:46 +0000282
Eli Friedman530341d2011-07-29 00:18:19 +0000283 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
284 BO->setIsExact(false);
Chris Lattner18d7fc82010-08-27 22:24:38 +0000285 return I;
286 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000287
Chris Lattner18d7fc82010-08-27 22:24:38 +0000288 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
289 // zeros.
Chris Lattner6c1395f2010-08-27 22:53:44 +0000290 if (CI->getValue() == NumBits) {
291 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
292 V = IC.Builder->CreateAnd(I->getOperand(0),
Eli Friedman530341d2011-07-29 00:18:19 +0000293 ConstantInt::get(BO->getContext(), Mask));
Chris Lattner6c1395f2010-08-27 22:53:44 +0000294 if (Instruction *VI = dyn_cast<Instruction>(V)) {
295 VI->moveBefore(I);
296 VI->takeName(I);
297 }
298 return V;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000299 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000300
Chris Lattner6c1395f2010-08-27 22:53:44 +0000301 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
302 // the and won't be needed.
303 assert(CI->getZExtValue() > NumBits);
Eli Friedman530341d2011-07-29 00:18:19 +0000304 BO->setOperand(1, ConstantInt::get(BO->getType(),
305 CI->getZExtValue() - NumBits));
306 BO->setIsExact(false);
307 return BO;
Chris Lattner18d7fc82010-08-27 22:24:38 +0000308 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000309
Chris Lattner18d7fc82010-08-27 22:24:38 +0000310 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000311 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000312 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000313 I->setOperand(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000314 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000315 return I;
316 case Instruction::PHI: {
317 // We can change a phi if we can change all operands. Note that we never
318 // get into trouble with cyclic PHIs here because we only consider
319 // instructions with a single use.
320 PHINode *PN = cast<PHINode>(I);
321 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
Sanjay Patel20aaf582017-01-15 17:55:35 +0000322 PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000323 isLeftShift, IC, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000324 return PN;
325 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000326 }
Chris Lattner18d7fc82010-08-27 22:24:38 +0000327}
328
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000329/// Try to fold (X << C1) << C2, where the shifts are some combination of
330/// shl/ashr/lshr.
331static Instruction *
332foldShiftByConstOfShiftByConst(BinaryOperator &I, ConstantInt *COp1,
333 InstCombiner::BuilderTy *Builder) {
334 Value *Op0 = I.getOperand(0);
335 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner18d7fc82010-08-27 22:24:38 +0000336
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000337 // Find out if this is a shift of a shift by a constant.
338 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
339 if (ShiftOp && !ShiftOp->isShift())
340 ShiftOp = nullptr;
341
342 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
343
344 // This is a constant shift of a constant shift. Be careful about hiding
345 // shl instructions behind bit masks. They are used to represent multiplies
346 // by a constant, and it is important that simple arithmetic expressions
347 // are still recognizable by scalar evolution.
348 //
349 // The transforms applied to shl are very similar to the transforms applied
350 // to mul by constant. We can be more aggressive about optimizing right
351 // shifts.
352 //
353 // Combinations of right and left shifts will still be optimized in
354 // DAGCombine where scalar evolution no longer applies.
355
356 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
357 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
358 uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
359 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
360 if (ShiftAmt1 == 0)
361 return nullptr; // Will be simplified in the future.
362 Value *X = ShiftOp->getOperand(0);
363
364 IntegerType *Ty = cast<IntegerType>(I.getType());
365
366 // Check for (X << c1) << c2 and (X >> c1) >> c2
367 if (I.getOpcode() == ShiftOp->getOpcode()) {
368 uint32_t AmtSum = ShiftAmt1 + ShiftAmt2; // Fold into one big shift.
369 // If this is an oversized composite shift, then unsigned shifts become
370 // zero (handled in InstSimplify) and ashr saturates.
371 if (AmtSum >= TypeBits) {
372 if (I.getOpcode() != Instruction::AShr)
373 return nullptr;
374 AmtSum = TypeBits - 1; // Saturate to 31 for i32 ashr.
375 }
376
377 return BinaryOperator::Create(I.getOpcode(), X,
378 ConstantInt::get(Ty, AmtSum));
379 }
380
381 if (ShiftAmt1 == ShiftAmt2) {
382 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
383 if (I.getOpcode() == Instruction::LShr &&
384 ShiftOp->getOpcode() == Instruction::Shl) {
385 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
386 return BinaryOperator::CreateAnd(
387 X, ConstantInt::get(I.getContext(), Mask));
388 }
389 } else if (ShiftAmt1 < ShiftAmt2) {
390 uint32_t ShiftDiff = ShiftAmt2 - ShiftAmt1;
391
392 // (X >>?,exact C1) << C2 --> X << (C2-C1)
393 // The inexact version is deferred to DAGCombine so we don't hide shl
394 // behind a bit mask.
395 if (I.getOpcode() == Instruction::Shl &&
396 ShiftOp->getOpcode() != Instruction::Shl && ShiftOp->isExact()) {
397 assert(ShiftOp->getOpcode() == Instruction::LShr ||
398 ShiftOp->getOpcode() == Instruction::AShr);
399 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
400 BinaryOperator *NewShl =
401 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
402 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
403 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
404 return NewShl;
405 }
406
407 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
408 if (I.getOpcode() == Instruction::LShr &&
409 ShiftOp->getOpcode() == Instruction::Shl) {
410 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
411 // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
412 if (ShiftOp->hasNoUnsignedWrap()) {
413 BinaryOperator *NewLShr =
414 BinaryOperator::Create(Instruction::LShr, X, ShiftDiffCst);
415 NewLShr->setIsExact(I.isExact());
416 return NewLShr;
417 }
418 Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
419
420 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
421 return BinaryOperator::CreateAnd(
422 Shift, ConstantInt::get(I.getContext(), Mask));
423 }
424
425 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
426 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
427 if (I.getOpcode() == Instruction::AShr &&
428 ShiftOp->getOpcode() == Instruction::Shl) {
429 if (ShiftOp->hasNoSignedWrap()) {
430 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
431 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
432 BinaryOperator *NewAShr =
433 BinaryOperator::Create(Instruction::AShr, X, ShiftDiffCst);
434 NewAShr->setIsExact(I.isExact());
435 return NewAShr;
436 }
437 }
438 } else {
439 assert(ShiftAmt2 < ShiftAmt1);
440 uint32_t ShiftDiff = ShiftAmt1 - ShiftAmt2;
441
442 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
443 // The inexact version is deferred to DAGCombine so we don't hide shl
444 // behind a bit mask.
445 if (I.getOpcode() == Instruction::Shl &&
446 ShiftOp->getOpcode() != Instruction::Shl && ShiftOp->isExact()) {
447 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
448 BinaryOperator *NewShr =
449 BinaryOperator::Create(ShiftOp->getOpcode(), X, ShiftDiffCst);
450 NewShr->setIsExact(true);
451 return NewShr;
452 }
453
454 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
455 if (I.getOpcode() == Instruction::LShr &&
456 ShiftOp->getOpcode() == Instruction::Shl) {
457 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
458 if (ShiftOp->hasNoUnsignedWrap()) {
459 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
460 BinaryOperator *NewShl =
461 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
462 NewShl->setHasNoUnsignedWrap(true);
463 return NewShl;
464 }
465 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
466
467 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
468 return BinaryOperator::CreateAnd(
469 Shift, ConstantInt::get(I.getContext(), Mask));
470 }
471
472 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
473 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
474 if (I.getOpcode() == Instruction::AShr &&
475 ShiftOp->getOpcode() == Instruction::Shl) {
476 if (ShiftOp->hasNoSignedWrap()) {
477 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
478 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
479 BinaryOperator *NewShl =
480 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
481 NewShl->setHasNoSignedWrap(true);
482 return NewShl;
483 }
484 }
485 }
486 }
487
488 return nullptr;
489}
Chris Lattner18d7fc82010-08-27 22:24:38 +0000490
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000491Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
Chris Lattnerdc67e132010-01-05 07:44:46 +0000492 BinaryOperator &I) {
493 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Jakub Staszak538e3862012-12-09 15:37:46 +0000494
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000495 ConstantInt *COp1 = nullptr;
496 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
497 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
498 else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
499 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
500 else
501 COp1 = dyn_cast<ConstantInt>(Op1);
502
503 if (!COp1)
504 return nullptr;
Jakub Staszak538e3862012-12-09 15:37:46 +0000505
Chris Lattner18d7fc82010-08-27 22:24:38 +0000506 // See if we can propagate this shift into the input, this covers the trivial
507 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
508 if (I.getOpcode() != Instruction::AShr &&
Sanjay Patel20aaf582017-01-15 17:55:35 +0000509 canEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this, &I)) {
Chris Lattnerdd660102010-08-28 01:20:38 +0000510 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
511 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
Jakub Staszak538e3862012-12-09 15:37:46 +0000512
Sanjay Patel4b198802016-02-01 22:23:39 +0000513 return replaceInstUsesWith(
Sanjay Patel20aaf582017-01-15 17:55:35 +0000514 I, getShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this, DL));
Chris Lattner18d7fc82010-08-27 22:24:38 +0000515 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000516
Jakub Staszak538e3862012-12-09 15:37:46 +0000517 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattnerdc67e132010-01-05 07:44:46 +0000518 // purpose is to compute bits we don't care about.
519 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Jakub Staszak538e3862012-12-09 15:37:46 +0000520
Matt Arsenault6b4bed42014-04-23 16:48:40 +0000521 assert(!COp1->uge(TypeBits) &&
522 "Shift over the type width should have been removed already");
Jakub Staszak538e3862012-12-09 15:37:46 +0000523
Chris Lattnerdc67e132010-01-05 07:44:46 +0000524 // ((X*C1) << C2) == (X * (C1 << C2))
525 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
526 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
527 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
528 return BinaryOperator::CreateMul(BO->getOperand(0),
Sanjay Patel690955f2016-01-31 16:34:11 +0000529 ConstantExpr::getShl(BOOp, Op1));
Jakub Staszak538e3862012-12-09 15:37:46 +0000530
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000531 if (Instruction *FoldedShift = foldOpWithConstantIntoOperand(I))
532 return FoldedShift;
Jakub Staszak538e3862012-12-09 15:37:46 +0000533
Chris Lattnerdc67e132010-01-05 07:44:46 +0000534 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
535 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
536 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
537 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
538 // place. Don't try to do this transformation in this case. Also, we
539 // require that the input operand is a shift-by-constant so that we have
540 // confidence that the shifts will get folded together. We could do this
541 // xform in more cases, but it is unlikely to be profitable.
Jakub Staszak538e3862012-12-09 15:37:46 +0000542 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
Chris Lattnerdc67e132010-01-05 07:44:46 +0000543 isa<ConstantInt>(TrOp->getOperand(1))) {
544 // Okay, we'll do this xform. Make the shift of shift.
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000545 Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
Chris Lattnerdc67e132010-01-05 07:44:46 +0000546 // (shift2 (shift1 & 0x00FF), c2)
547 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
548
549 // For logical shifts, the truncation has the effect of making the high
550 // part of the register be zeros. Emulate this by inserting an AND to
551 // clear the top bits as needed. This 'and' will usually be zapped by
552 // other xforms later if dead.
553 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
554 unsigned DstSize = TI->getType()->getScalarSizeInBits();
555 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
Jakub Staszak538e3862012-12-09 15:37:46 +0000556
Chris Lattnerdc67e132010-01-05 07:44:46 +0000557 // The mask we constructed says what the trunc would do if occurring
558 // between the shifts. We want to know the effect *after* the second
559 // shift. We know that it is a logical shift by a constant, so adjust the
560 // mask as appropriate.
561 if (I.getOpcode() == Instruction::Shl)
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000562 MaskV <<= COp1->getZExtValue();
Chris Lattnerdc67e132010-01-05 07:44:46 +0000563 else {
564 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000565 MaskV = MaskV.lshr(COp1->getZExtValue());
Chris Lattnerdc67e132010-01-05 07:44:46 +0000566 }
567
568 // shift1 & 0x00FF
569 Value *And = Builder->CreateAnd(NSh,
570 ConstantInt::get(I.getContext(), MaskV),
571 TI->getName());
572
573 // Return the value truncated to the interesting size.
574 return new TruncInst(And, I.getType());
575 }
576 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000577
Chris Lattnerdc67e132010-01-05 07:44:46 +0000578 if (Op0->hasOneUse()) {
579 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
580 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
581 Value *V1, *V2;
582 ConstantInt *CC;
583 switch (Op0BO->getOpcode()) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000584 default: break;
585 case Instruction::Add:
586 case Instruction::And:
587 case Instruction::Or:
588 case Instruction::Xor: {
589 // These operators commute.
590 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
591 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
592 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
593 m_Specific(Op1)))) {
594 Value *YS = // (Y << C)
595 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
596 // (X + (Y << C))
597 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
598 Op0BO->getOperand(1)->getName());
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000599 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
600
601 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
602 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
603 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
604 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
605 return BinaryOperator::CreateAnd(X, Mask);
Chris Lattnerdc67e132010-01-05 07:44:46 +0000606 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000607
Chris Lattner2b459fe2010-01-10 06:59:55 +0000608 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
609 Value *Op0BOOp1 = Op0BO->getOperand(1);
610 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Jakub Staszak538e3862012-12-09 15:37:46 +0000611 match(Op0BOOp1,
Jakub Staszak84321852012-12-09 16:06:44 +0000612 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
613 m_ConstantInt(CC)))) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000614 Value *YS = // (Y << C)
615 Builder->CreateShl(Op0BO->getOperand(0), Op1,
616 Op0BO->getName());
617 // X & (CC << C)
618 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
619 V1->getName()+".mask");
620 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattnerdc67e132010-01-05 07:44:46 +0000621 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000622 LLVM_FALLTHROUGH;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000623 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000624
Chris Lattner2b459fe2010-01-10 06:59:55 +0000625 case Instruction::Sub: {
626 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
627 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
628 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
629 m_Specific(Op1)))) {
630 Value *YS = // (Y << C)
631 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
632 // (X + (Y << C))
633 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
634 Op0BO->getOperand(0)->getName());
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000635 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
636
637 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
638 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
639 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
640 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
641 return BinaryOperator::CreateAnd(X, Mask);
Chris Lattner2b459fe2010-01-10 06:59:55 +0000642 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000643
Chris Lattner2b459fe2010-01-10 06:59:55 +0000644 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
645 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
646 match(Op0BO->getOperand(0),
Jakub Staszak84321852012-12-09 16:06:44 +0000647 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
648 m_ConstantInt(CC))) && V2 == Op1) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000649 Value *YS = // (Y << C)
650 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
651 // X & (CC << C)
652 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
653 V1->getName()+".mask");
Jakub Staszak538e3862012-12-09 15:37:46 +0000654
Chris Lattner2b459fe2010-01-10 06:59:55 +0000655 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
656 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000657
Chris Lattner2b459fe2010-01-10 06:59:55 +0000658 break;
659 }
660 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000661
662
Sanjay Patelfc3d8f02014-07-22 04:57:06 +0000663 // If the operand is a bitwise operator with a constant RHS, and the
Chris Lattnerdc67e132010-01-05 07:44:46 +0000664 // shift is the only use, we can pull it out of the shift.
665 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
666 bool isValid = true; // Valid only for And, Or, Xor
667 bool highBitSet = false; // Transform if high bit of constant set?
Jakub Staszak538e3862012-12-09 15:37:46 +0000668
Chris Lattnerdc67e132010-01-05 07:44:46 +0000669 switch (Op0BO->getOpcode()) {
Chris Lattner2b459fe2010-01-10 06:59:55 +0000670 default: isValid = false; break; // Do not perform transform!
671 case Instruction::Add:
672 isValid = isLeftShift;
673 break;
674 case Instruction::Or:
675 case Instruction::Xor:
676 highBitSet = false;
677 break;
678 case Instruction::And:
679 highBitSet = true;
680 break;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000681 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000682
Chris Lattnerdc67e132010-01-05 07:44:46 +0000683 // If this is a signed shift right, and the high bit is modified
684 // by the logical operation, do not perform the transformation.
685 // The highBitSet boolean indicates the value of the high bit of
686 // the constant which would cause it to be modified for this
687 // operation.
688 //
689 if (isValid && I.getOpcode() == Instruction::AShr)
690 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Jakub Staszak538e3862012-12-09 15:37:46 +0000691
Chris Lattnerdc67e132010-01-05 07:44:46 +0000692 if (isValid) {
693 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Jakub Staszak538e3862012-12-09 15:37:46 +0000694
Chris Lattnerdc67e132010-01-05 07:44:46 +0000695 Value *NewShift =
696 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
697 NewShift->takeName(Op0BO);
Jakub Staszak538e3862012-12-09 15:37:46 +0000698
Chris Lattnerdc67e132010-01-05 07:44:46 +0000699 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
700 NewRHS);
701 }
702 }
703 }
704 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000705
Sanjay Patel4c48bbe2016-12-10 22:16:29 +0000706 if (Instruction *Folded = foldShiftByConstOfShiftByConst(I, COp1, Builder))
707 return Folded;
Jakub Staszak538e3862012-12-09 15:37:46 +0000708
Craig Topperf40110f2014-04-25 05:29:35 +0000709 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000710}
711
712Instruction *InstCombiner::visitShl(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000713 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000714 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000715
Sanjay Patelcf082032017-01-13 18:08:25 +0000716 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
717 if (Value *V = SimplifyShlInst(Op0, Op1, I.hasNoSignedWrap(),
718 I.hasNoUnsignedWrap(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000719 return replaceInstUsesWith(I, V);
Jakub Staszak538e3862012-12-09 15:37:46 +0000720
Chris Lattner6b657ae2011-02-10 05:36:31 +0000721 if (Instruction *V = commonShiftTransforms(I))
722 return V;
Jakub Staszak538e3862012-12-09 15:37:46 +0000723
Sanjay Patelb22f6c52017-01-13 18:39:09 +0000724 const APInt *ShAmtAPInt;
725 if (match(Op1, m_APInt(ShAmtAPInt))) {
726 unsigned ShAmt = ShAmtAPInt->getZExtValue();
Jakub Staszak538e3862012-12-09 15:37:46 +0000727
Sanjay Patelacd24c72017-01-13 18:52:10 +0000728 // shl (zext X), ShAmt --> zext (shl X, ShAmt)
729 // This is only valid if X would have zeros shifted out.
730 Value *X;
731 if (match(Op0, m_ZExt(m_Value(X)))) {
732 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
733 if (ShAmt < SrcWidth &&
734 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
735 return new ZExtInst(Builder->CreateShl(X, ShAmt), I.getType());
David Majnemercb892e92017-01-04 02:21:34 +0000736 }
737
Chris Lattner6b657ae2011-02-10 05:36:31 +0000738 // If the shifted-out value is known-zero, then this is a NUW shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000739 if (!I.hasNoUnsignedWrap() &&
Sanjay Patelcf082032017-01-13 18:08:25 +0000740 MaskedValueIsZero(
Sanjay Patelb22f6c52017-01-13 18:39:09 +0000741 Op0, APInt::getHighBitsSet(ShAmtAPInt->getBitWidth(), ShAmt), 0,
742 &I)) {
Sanjay Patel690955f2016-01-31 16:34:11 +0000743 I.setHasNoUnsignedWrap();
744 return &I;
745 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000746
Sanjay Patelcf082032017-01-13 18:08:25 +0000747 // If the shifted-out value is all signbits, then this is a NSW shift.
748 if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000749 I.setHasNoSignedWrap();
750 return &I;
751 }
752 }
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000753
Benjamin Kramerf0e3f042011-04-29 08:41:23 +0000754 // (C1 << A) << C2 -> (C1 << C2) << A
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000755 Constant *C1, *C2;
756 Value *A;
Sanjay Patelcf082032017-01-13 18:08:25 +0000757 if (match(Op0, m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
758 match(Op1, m_Constant(C2)))
Benjamin Kramer16f18ed2011-04-29 08:15:41 +0000759 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
760
Craig Topperf40110f2014-04-25 05:29:35 +0000761 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000762}
763
764Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000765 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000766 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000767
Sanjay Patelcf082032017-01-13 18:08:25 +0000768 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
769 if (Value *V = SimplifyLShrInst(Op0, Op1, I.isExact(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000770 return replaceInstUsesWith(I, V);
Duncan Sands7f60dc12011-01-14 00:37:45 +0000771
Chris Lattner249da5c2010-01-23 18:49:30 +0000772 if (Instruction *R = commonShiftTransforms(I))
773 return R;
Jakub Staszak538e3862012-12-09 15:37:46 +0000774
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000775 const APInt *ShAmtAPInt;
776 if (match(Op1, m_APInt(ShAmtAPInt))) {
777 unsigned ShAmt = ShAmtAPInt->getZExtValue();
778 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
779 auto *II = dyn_cast<IntrinsicInst>(Op0);
780 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
781 (II->getIntrinsicID() == Intrinsic::ctlz ||
782 II->getIntrinsicID() == Intrinsic::cttz ||
783 II->getIntrinsicID() == Intrinsic::ctpop)) {
Chris Lattner249da5c2010-01-23 18:49:30 +0000784 // ctlz.i32(x)>>5 --> zext(x == 0)
785 // cttz.i32(x)>>5 --> zext(x == 0)
786 // ctpop.i32(x)>>5 --> zext(x == -1)
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000787 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
788 Constant *RHS = ConstantInt::getSigned(Op0->getType(), IsPop ? -1 : 0);
789 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
790 return new ZExtInst(Cmp, II->getType());
Chris Lattner249da5c2010-01-23 18:49:30 +0000791 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000792
Chris Lattner6b657ae2011-02-10 05:36:31 +0000793 // If the shifted-out value is known-zero, then this is an exact shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000794 if (!I.isExact() &&
Sanjay Patel2d4b4562017-01-13 23:04:10 +0000795 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000796 I.setIsExact();
797 return &I;
Jakub Staszak538e3862012-12-09 15:37:46 +0000798 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000799 }
Craig Topperf40110f2014-04-25 05:29:35 +0000800 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000801}
802
803Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000804 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000805 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000806
Sanjay Patelcf082032017-01-13 18:08:25 +0000807 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
808 if (Value *V = SimplifyAShrInst(Op0, Op1, I.isExact(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000809 return replaceInstUsesWith(I, V);
Duncan Sands7f60dc12011-01-14 00:37:45 +0000810
Chris Lattnerdc67e132010-01-05 07:44:46 +0000811 if (Instruction *R = commonShiftTransforms(I))
812 return R;
Jakub Staszak538e3862012-12-09 15:37:46 +0000813
Sanjay Patelca3124f2017-01-14 23:13:50 +0000814 unsigned BitWidth = I.getType()->getScalarSizeInBits();
Sanjay Patel5f8451a2017-01-15 16:38:19 +0000815 const APInt *ShAmtAPInt;
816 if (match(Op1, m_APInt(ShAmtAPInt))) {
817 unsigned ShAmt = ShAmtAPInt->getZExtValue();
Jakub Staszak538e3862012-12-09 15:37:46 +0000818
Sanjay Patelca3124f2017-01-14 23:13:50 +0000819 // If the shift amount equals the difference in width of the destination
Sanjay Patel5f8451a2017-01-15 16:38:19 +0000820 // and source scalar types:
Sanjay Patelca3124f2017-01-14 23:13:50 +0000821 // ashr (shl (zext X), C), C --> sext X
Chris Lattnera1e223e2010-01-08 19:04:21 +0000822 Value *X;
Sanjay Patelca3124f2017-01-14 23:13:50 +0000823 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
824 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
825 return new SExtInst(X, I.getType());
Chris Lattner6b657ae2011-02-10 05:36:31 +0000826
827 // If the shifted-out value is known-zero, then this is an exact shift.
Jakub Staszak538e3862012-12-09 15:37:46 +0000828 if (!I.isExact() &&
Sanjay Patelca3124f2017-01-14 23:13:50 +0000829 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000830 I.setIsExact();
831 return &I;
832 }
Jakub Staszak538e3862012-12-09 15:37:46 +0000833 }
834
Chris Lattnerdc67e132010-01-05 07:44:46 +0000835 // See if we can turn a signed shr into an unsigned shr.
Sanjay Patelca3124f2017-01-14 23:13:50 +0000836 if (MaskedValueIsZero(Op0, APInt::getSignBit(BitWidth), 0, &I))
Chris Lattnera1e223e2010-01-08 19:04:21 +0000837 return BinaryOperator::CreateLShr(Op0, Op1);
Jakub Staszak538e3862012-12-09 15:37:46 +0000838
Craig Topperf40110f2014-04-25 05:29:35 +0000839 return nullptr;
Chris Lattnerdc67e132010-01-05 07:44:46 +0000840}