1 //===- InstCombineShifts.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitShl, visitLShr, and visitAShr functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
20 using namespace PatternMatch;
22 #define DEBUG_TYPE "instcombine"
24 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
25 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
26 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
28 // See if we can fold away this shift.
29 if (SimplifyDemandedInstructionBits(I))
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))
38 if (Constant *CUI = dyn_cast<Constant>(Op1))
39 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
42 // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
43 // iff A and C2 are both positive.
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);
51 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
52 // Because shifts by negative values (which could occur if A were negative)
55 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),
67 /// Return true if we can simplify two logical (either left or right) shifts
68 /// that have constant shift amounts.
69 static bool canEvaluateShiftedShift(unsigned FirstShiftAmt,
70 bool IsFirstShiftLeft,
71 Instruction *SecondShift, InstCombiner &IC,
73 assert(SecondShift->isLogicalShift() && "Unexpected instruction type");
75 // We need constant shifts.
76 auto *SecondShiftConst = dyn_cast<ConstantInt>(SecondShift->getOperand(1));
77 if (!SecondShiftConst)
80 unsigned SecondShiftAmt = SecondShiftConst->getZExtValue();
81 bool IsSecondShiftLeft = SecondShift->getOpcode() == Instruction::Shl;
83 // 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)
88 // 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)
93 unsigned TypeWidth = SecondShift->getType()->getScalarSizeInBits();
95 // If the 2nd shift is bigger than the 1st, we can fold:
96 // lshr(c1) + shl(c2) -> shl(c3) + and(c4) or
97 // shl(c1) + lshr(c2) -> lshr(c3) + and(c4),
98 // but it isn't profitable unless we know the and'd out bits are already zero.
99 // 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) {
102 unsigned MaskShift = IsSecondShiftLeft ? TypeWidth - SecondShiftAmt
103 : SecondShiftAmt - FirstShiftAmt;
104 APInt Mask = APInt::getLowBitsSet(TypeWidth, FirstShiftAmt) << MaskShift;
105 if (IC.MaskedValueIsZero(SecondShift->getOperand(0), Mask, 0, CxtI))
112 /// See if we can compute the specified value, but shifted
113 /// logically to the left or right by some number of bits. This should return
114 /// true if the expression can be computed for the same cost as the current
115 /// expression tree. This is used to eliminate extraneous shifting from things
117 /// %C = shl i128 %A, 64
118 /// %D = shl i128 %B, 96
119 /// %E = or i128 %C, %D
120 /// %F = lshr i128 %E, 64
121 /// where the client will ask if E can be computed shifted right by 64-bits. If
122 /// this succeeds, the GetShiftedValue function will be called to produce the
124 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
125 InstCombiner &IC, Instruction *CxtI) {
126 // We can always evaluate constants shifted.
127 if (isa<Constant>(V))
130 Instruction *I = dyn_cast<Instruction>(V);
131 if (!I) return false;
133 // If this is the opposite shift, we can directly reuse the input of the shift
134 // if the needed bits are already zero in the input. This allows us to reuse
135 // the value which means that we don't care if the shift has multiple uses.
136 // TODO: Handle opposite shift by exact value.
137 ConstantInt *CI = nullptr;
138 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
139 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
140 if (CI->getZExtValue() == NumBits) {
141 // TODO: Check that the input bits are already zero with MaskedValueIsZero
143 // If this is a truncate of a logical shr, we can truncate it to a smaller
144 // lshr iff we know that the bits we would otherwise be shifting in are
146 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
147 uint32_t BitWidth = Ty->getScalarSizeInBits();
148 if (MaskedValueIsZero(I->getOperand(0),
149 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
150 CI->getLimitedValue(BitWidth) < BitWidth) {
151 return CanEvaluateTruncated(I->getOperand(0), Ty);
158 // We can't mutate something that has multiple uses: doing so would
159 // require duplicating the instruction in general, which isn't profitable.
160 if (!I->hasOneUse()) return false;
162 switch (I->getOpcode()) {
163 default: return false;
164 case Instruction::And:
165 case Instruction::Or:
166 case Instruction::Xor:
167 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
168 return CanEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
169 CanEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
171 case Instruction::Shl:
172 case Instruction::LShr:
173 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
175 case Instruction::Select: {
176 SelectInst *SI = cast<SelectInst>(I);
177 Value *TrueVal = SI->getTrueValue();
178 Value *FalseVal = SI->getFalseValue();
179 return CanEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
180 CanEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
182 case Instruction::PHI: {
183 // We can change a phi if we can change all operands. Note that we never
184 // get into trouble with cyclic PHIs here because we only consider
185 // instructions with a single use.
186 PHINode *PN = cast<PHINode>(I);
187 for (Value *IncValue : PN->incoming_values())
188 if (!CanEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
195 /// When CanEvaluateShifted returned true for an expression,
196 /// this value inserts the new computation that produces the shifted value.
197 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
198 InstCombiner &IC, const DataLayout &DL) {
199 // We can always evaluate constants shifted.
200 if (Constant *C = dyn_cast<Constant>(V)) {
202 V = IC.Builder->CreateShl(C, NumBits);
204 V = IC.Builder->CreateLShr(C, NumBits);
205 // If we got a constantexpr back, try to simplify it with TD info.
206 if (auto *C = dyn_cast<Constant>(V))
208 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
213 Instruction *I = cast<Instruction>(V);
216 switch (I->getOpcode()) {
217 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
218 case Instruction::And:
219 case Instruction::Or:
220 case Instruction::Xor:
221 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
223 0, GetShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
225 1, GetShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
228 case Instruction::Shl: {
229 BinaryOperator *BO = cast<BinaryOperator>(I);
230 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
232 // We only accept shifts-by-a-constant in CanEvaluateShifted.
233 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
235 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
237 // If this is oversized composite shift, then unsigned shifts get 0.
238 unsigned NewShAmt = NumBits+CI->getZExtValue();
239 if (NewShAmt >= TypeWidth)
240 return Constant::getNullValue(I->getType());
242 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
243 BO->setHasNoUnsignedWrap(false);
244 BO->setHasNoSignedWrap(false);
248 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
250 if (CI->getValue() == NumBits) {
251 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
252 V = IC.Builder->CreateAnd(BO->getOperand(0),
253 ConstantInt::get(BO->getContext(), Mask));
254 if (Instruction *VI = dyn_cast<Instruction>(V)) {
261 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
262 // the and won't be needed.
263 assert(CI->getZExtValue() > NumBits);
264 BO->setOperand(1, ConstantInt::get(BO->getType(),
265 CI->getZExtValue() - NumBits));
266 BO->setHasNoUnsignedWrap(false);
267 BO->setHasNoSignedWrap(false);
270 // FIXME: This is almost identical to the SHL case. Refactor both cases into
271 // a helper function.
272 case Instruction::LShr: {
273 BinaryOperator *BO = cast<BinaryOperator>(I);
274 unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
275 // We only accept shifts-by-a-constant in CanEvaluateShifted.
276 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
278 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
280 // If this is oversized composite shift, then unsigned shifts get 0.
281 unsigned NewShAmt = NumBits+CI->getZExtValue();
282 if (NewShAmt >= TypeWidth)
283 return Constant::getNullValue(BO->getType());
285 BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
286 BO->setIsExact(false);
290 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
292 if (CI->getValue() == NumBits) {
293 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
294 V = IC.Builder->CreateAnd(I->getOperand(0),
295 ConstantInt::get(BO->getContext(), Mask));
296 if (Instruction *VI = dyn_cast<Instruction>(V)) {
303 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
304 // the and won't be needed.
305 assert(CI->getZExtValue() > NumBits);
306 BO->setOperand(1, ConstantInt::get(BO->getType(),
307 CI->getZExtValue() - NumBits));
308 BO->setIsExact(false);
312 case Instruction::Select:
314 1, GetShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
316 2, GetShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
318 case Instruction::PHI: {
319 // We can change a phi if we can change all operands. Note that we never
320 // get into trouble with cyclic PHIs here because we only consider
321 // instructions with a single use.
322 PHINode *PN = cast<PHINode>(I);
323 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
324 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i), NumBits,
325 isLeftShift, IC, DL));
331 /// Try to fold (X << C1) << C2, where the shifts are some combination of
334 foldShiftByConstOfShiftByConst(BinaryOperator &I, ConstantInt *COp1,
335 InstCombiner::BuilderTy *Builder) {
336 Value *Op0 = I.getOperand(0);
337 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
339 // Find out if this is a shift of a shift by a constant.
340 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
341 if (ShiftOp && !ShiftOp->isShift())
344 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
346 // This is a constant shift of a constant shift. Be careful about hiding
347 // shl instructions behind bit masks. They are used to represent multiplies
348 // by a constant, and it is important that simple arithmetic expressions
349 // are still recognizable by scalar evolution.
351 // The transforms applied to shl are very similar to the transforms applied
352 // to mul by constant. We can be more aggressive about optimizing right
355 // Combinations of right and left shifts will still be optimized in
356 // DAGCombine where scalar evolution no longer applies.
358 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
359 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
360 uint32_t ShiftAmt2 = COp1->getLimitedValue(TypeBits);
361 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
363 return nullptr; // Will be simplified in the future.
364 Value *X = ShiftOp->getOperand(0);
366 IntegerType *Ty = cast<IntegerType>(I.getType());
368 // Check for (X << c1) << c2 and (X >> c1) >> c2
369 if (I.getOpcode() == ShiftOp->getOpcode()) {
370 uint32_t AmtSum = ShiftAmt1 + ShiftAmt2; // Fold into one big shift.
371 // If this is an oversized composite shift, then unsigned shifts become
372 // zero (handled in InstSimplify) and ashr saturates.
373 if (AmtSum >= TypeBits) {
374 if (I.getOpcode() != Instruction::AShr)
376 AmtSum = TypeBits - 1; // Saturate to 31 for i32 ashr.
379 return BinaryOperator::Create(I.getOpcode(), X,
380 ConstantInt::get(Ty, AmtSum));
383 if (ShiftAmt1 == ShiftAmt2) {
384 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
385 if (I.getOpcode() == Instruction::LShr &&
386 ShiftOp->getOpcode() == Instruction::Shl) {
387 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
388 return BinaryOperator::CreateAnd(
389 X, ConstantInt::get(I.getContext(), Mask));
391 } else if (ShiftAmt1 < ShiftAmt2) {
392 uint32_t ShiftDiff = ShiftAmt2 - ShiftAmt1;
394 // (X >>?,exact C1) << C2 --> X << (C2-C1)
395 // The inexact version is deferred to DAGCombine so we don't hide shl
396 // behind a bit mask.
397 if (I.getOpcode() == Instruction::Shl &&
398 ShiftOp->getOpcode() != Instruction::Shl && ShiftOp->isExact()) {
399 assert(ShiftOp->getOpcode() == Instruction::LShr ||
400 ShiftOp->getOpcode() == Instruction::AShr);
401 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
402 BinaryOperator *NewShl =
403 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
404 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
405 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
409 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
410 if (I.getOpcode() == Instruction::LShr &&
411 ShiftOp->getOpcode() == Instruction::Shl) {
412 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
413 // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
414 if (ShiftOp->hasNoUnsignedWrap()) {
415 BinaryOperator *NewLShr =
416 BinaryOperator::Create(Instruction::LShr, X, ShiftDiffCst);
417 NewLShr->setIsExact(I.isExact());
420 Value *Shift = Builder->CreateLShr(X, ShiftDiffCst);
422 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
423 return BinaryOperator::CreateAnd(
424 Shift, ConstantInt::get(I.getContext(), Mask));
427 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
428 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
429 if (I.getOpcode() == Instruction::AShr &&
430 ShiftOp->getOpcode() == Instruction::Shl) {
431 if (ShiftOp->hasNoSignedWrap()) {
432 // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
433 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
434 BinaryOperator *NewAShr =
435 BinaryOperator::Create(Instruction::AShr, X, ShiftDiffCst);
436 NewAShr->setIsExact(I.isExact());
441 assert(ShiftAmt2 < ShiftAmt1);
442 uint32_t ShiftDiff = ShiftAmt1 - ShiftAmt2;
444 // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
445 // The inexact version is deferred to DAGCombine so we don't hide shl
446 // behind a bit mask.
447 if (I.getOpcode() == Instruction::Shl &&
448 ShiftOp->getOpcode() != Instruction::Shl && ShiftOp->isExact()) {
449 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
450 BinaryOperator *NewShr =
451 BinaryOperator::Create(ShiftOp->getOpcode(), X, ShiftDiffCst);
452 NewShr->setIsExact(true);
456 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
457 if (I.getOpcode() == Instruction::LShr &&
458 ShiftOp->getOpcode() == Instruction::Shl) {
459 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
460 if (ShiftOp->hasNoUnsignedWrap()) {
461 // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
462 BinaryOperator *NewShl =
463 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
464 NewShl->setHasNoUnsignedWrap(true);
467 Value *Shift = Builder->CreateShl(X, ShiftDiffCst);
469 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
470 return BinaryOperator::CreateAnd(
471 Shift, ConstantInt::get(I.getContext(), Mask));
474 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. However,
475 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
476 if (I.getOpcode() == Instruction::AShr &&
477 ShiftOp->getOpcode() == Instruction::Shl) {
478 if (ShiftOp->hasNoSignedWrap()) {
479 // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
480 ConstantInt *ShiftDiffCst = ConstantInt::get(Ty, ShiftDiff);
481 BinaryOperator *NewShl =
482 BinaryOperator::Create(Instruction::Shl, X, ShiftDiffCst);
483 NewShl->setHasNoSignedWrap(true);
493 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
495 bool isLeftShift = I.getOpcode() == Instruction::Shl;
497 ConstantInt *COp1 = nullptr;
498 if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(Op1))
499 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
500 else if (ConstantVector *CV = dyn_cast<ConstantVector>(Op1))
501 COp1 = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
503 COp1 = dyn_cast<ConstantInt>(Op1);
508 // See if we can propagate this shift into the input, this covers the trivial
509 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
510 if (I.getOpcode() != Instruction::AShr &&
511 CanEvaluateShifted(Op0, COp1->getZExtValue(), isLeftShift, *this, &I)) {
512 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
513 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
515 return replaceInstUsesWith(
516 I, GetShiftedValue(Op0, COp1->getZExtValue(), isLeftShift, *this, DL));
519 // See if we can simplify any instructions used by the instruction whose sole
520 // purpose is to compute bits we don't care about.
521 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
523 assert(!COp1->uge(TypeBits) &&
524 "Shift over the type width should have been removed already");
526 // ((X*C1) << C2) == (X * (C1 << C2))
527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
528 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
529 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
530 return BinaryOperator::CreateMul(BO->getOperand(0),
531 ConstantExpr::getShl(BOOp, Op1));
533 if (Instruction *FoldedShift = foldOpWithConstantIntoOperand(I))
536 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
537 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
538 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
539 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
540 // place. Don't try to do this transformation in this case. Also, we
541 // require that the input operand is a shift-by-constant so that we have
542 // confidence that the shifts will get folded together. We could do this
543 // xform in more cases, but it is unlikely to be profitable.
544 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
545 isa<ConstantInt>(TrOp->getOperand(1))) {
546 // Okay, we'll do this xform. Make the shift of shift.
547 Constant *ShAmt = ConstantExpr::getZExt(COp1, TrOp->getType());
548 // (shift2 (shift1 & 0x00FF), c2)
549 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
551 // For logical shifts, the truncation has the effect of making the high
552 // part of the register be zeros. Emulate this by inserting an AND to
553 // clear the top bits as needed. This 'and' will usually be zapped by
554 // other xforms later if dead.
555 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
556 unsigned DstSize = TI->getType()->getScalarSizeInBits();
557 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
559 // The mask we constructed says what the trunc would do if occurring
560 // between the shifts. We want to know the effect *after* the second
561 // shift. We know that it is a logical shift by a constant, so adjust the
562 // mask as appropriate.
563 if (I.getOpcode() == Instruction::Shl)
564 MaskV <<= COp1->getZExtValue();
566 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
567 MaskV = MaskV.lshr(COp1->getZExtValue());
571 Value *And = Builder->CreateAnd(NSh,
572 ConstantInt::get(I.getContext(), MaskV),
575 // Return the value truncated to the interesting size.
576 return new TruncInst(And, I.getType());
580 if (Op0->hasOneUse()) {
581 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
582 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
585 switch (Op0BO->getOpcode()) {
587 case Instruction::Add:
588 case Instruction::And:
589 case Instruction::Or:
590 case Instruction::Xor: {
591 // These operators commute.
592 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
593 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
594 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
596 Value *YS = // (Y << C)
597 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
599 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
600 Op0BO->getOperand(1)->getName());
601 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
603 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
604 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
605 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
606 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
607 return BinaryOperator::CreateAnd(X, Mask);
610 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
611 Value *Op0BOOp1 = Op0BO->getOperand(1);
612 if (isLeftShift && Op0BOOp1->hasOneUse() &&
614 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
615 m_ConstantInt(CC)))) {
616 Value *YS = // (Y << C)
617 Builder->CreateShl(Op0BO->getOperand(0), Op1,
620 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
621 V1->getName()+".mask");
622 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
627 case Instruction::Sub: {
628 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
629 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
630 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
632 Value *YS = // (Y << C)
633 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
635 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
636 Op0BO->getOperand(0)->getName());
637 uint32_t Op1Val = COp1->getLimitedValue(TypeBits);
639 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
640 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
641 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
642 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
643 return BinaryOperator::CreateAnd(X, Mask);
646 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
647 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
648 match(Op0BO->getOperand(0),
649 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
650 m_ConstantInt(CC))) && V2 == Op1) {
651 Value *YS = // (Y << C)
652 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
654 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
655 V1->getName()+".mask");
657 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
665 // If the operand is a bitwise operator with a constant RHS, and the
666 // shift is the only use, we can pull it out of the shift.
667 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
668 bool isValid = true; // Valid only for And, Or, Xor
669 bool highBitSet = false; // Transform if high bit of constant set?
671 switch (Op0BO->getOpcode()) {
672 default: isValid = false; break; // Do not perform transform!
673 case Instruction::Add:
674 isValid = isLeftShift;
676 case Instruction::Or:
677 case Instruction::Xor:
680 case Instruction::And:
685 // If this is a signed shift right, and the high bit is modified
686 // by the logical operation, do not perform the transformation.
687 // The highBitSet boolean indicates the value of the high bit of
688 // the constant which would cause it to be modified for this
691 if (isValid && I.getOpcode() == Instruction::AShr)
692 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
695 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
698 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
699 NewShift->takeName(Op0BO);
701 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
708 if (Instruction *Folded = foldShiftByConstOfShiftByConst(I, COp1, Builder))
714 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
715 if (Value *V = SimplifyVectorOp(I))
716 return replaceInstUsesWith(I, V);
719 SimplifyShlInst(I.getOperand(0), I.getOperand(1), I.hasNoSignedWrap(),
720 I.hasNoUnsignedWrap(), DL, &TLI, &DT, &AC))
721 return replaceInstUsesWith(I, V);
723 if (Instruction *V = commonShiftTransforms(I))
726 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
727 unsigned ShAmt = Op1C->getZExtValue();
730 // %zext = zext i32 %V to i64
731 // %res = shl i64 %V, 8
734 // %shl = shl i32 %V, 8
735 // %res = zext i32 %shl to i64
737 // This is only valid if %V would have zeros shifted out.
738 if (auto *ZI = dyn_cast<ZExtInst>(I.getOperand(0))) {
739 unsigned SrcBitWidth = ZI->getSrcTy()->getScalarSizeInBits();
740 if (ShAmt < SrcBitWidth &&
741 MaskedValueIsZero(ZI->getOperand(0),
742 APInt::getHighBitsSet(SrcBitWidth, ShAmt), 0, &I)) {
743 auto *Shl = Builder->CreateShl(ZI->getOperand(0), ShAmt);
744 return new ZExtInst(Shl, I.getType());
748 // If the shifted-out value is known-zero, then this is a NUW shift.
749 if (!I.hasNoUnsignedWrap() &&
750 MaskedValueIsZero(I.getOperand(0),
751 APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt), 0,
753 I.setHasNoUnsignedWrap();
757 // If the shifted out value is all signbits, this is a NSW shift.
758 if (!I.hasNoSignedWrap() &&
759 ComputeNumSignBits(I.getOperand(0), 0, &I) > ShAmt) {
760 I.setHasNoSignedWrap();
765 // (C1 << A) << C2 -> (C1 << C2) << A
768 if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
769 match(I.getOperand(1), m_Constant(C2)))
770 return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
775 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
776 if (Value *V = SimplifyVectorOp(I))
777 return replaceInstUsesWith(I, V);
779 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
781 return replaceInstUsesWith(I, V);
783 if (Instruction *R = commonShiftTransforms(I))
786 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
788 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
789 unsigned ShAmt = Op1C->getZExtValue();
791 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
792 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
793 // ctlz.i32(x)>>5 --> zext(x == 0)
794 // cttz.i32(x)>>5 --> zext(x == 0)
795 // ctpop.i32(x)>>5 --> zext(x == -1)
796 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
797 II->getIntrinsicID() == Intrinsic::cttz ||
798 II->getIntrinsicID() == Intrinsic::ctpop) &&
799 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
800 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
801 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
802 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
803 return new ZExtInst(Cmp, II->getType());
807 // If the shifted-out value is known-zero, then this is an exact shift.
809 MaskedValueIsZero(Op0, APInt::getLowBitsSet(Op1C->getBitWidth(), ShAmt),
819 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
820 if (Value *V = SimplifyVectorOp(I))
821 return replaceInstUsesWith(I, V);
823 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
825 return replaceInstUsesWith(I, V);
827 if (Instruction *R = commonShiftTransforms(I))
830 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
832 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
833 unsigned ShAmt = Op1C->getZExtValue();
835 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
836 // have a sign-extend idiom.
838 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
839 // If the input is an extension from the shifted amount value, e.g.
840 // %x = zext i8 %A to i32
841 // %y = shl i32 %x, 24
843 // then turn this into "z = sext i8 A to i32".
844 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
845 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
846 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
847 if (Op1C->getZExtValue() == DestBits-SrcBits)
848 return new SExtInst(ZI->getOperand(0), ZI->getType());
852 // If the shifted-out value is known-zero, then this is an exact shift.
854 MaskedValueIsZero(Op0, APInt::getLowBitsSet(Op1C->getBitWidth(), ShAmt),
861 // See if we can turn a signed shr into an unsigned shr.
862 if (MaskedValueIsZero(Op0,
863 APInt::getSignBit(I.getType()->getScalarSizeInBits()),
865 return BinaryOperator::CreateLShr(Op0, Op1);