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 "InstCombine.h"
15 #include "llvm/IntrinsicInst.h"
16 #include "llvm/Support/PatternMatch.h"
18 using namespace PatternMatch;
20 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
21 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
22 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
24 // shl X, 0 == X and shr X, 0 == X
25 // shl 0, X == 0 and shr 0, X == 0
26 if (Op1 == Constant::getNullValue(Op1->getType()) ||
27 Op0 == Constant::getNullValue(Op0->getType()))
28 return ReplaceInstUsesWith(I, Op0);
30 if (isa<UndefValue>(Op0)) {
31 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
32 return ReplaceInstUsesWith(I, Op0);
33 else // undef << X -> 0, undef >>u X -> 0
34 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
36 if (isa<UndefValue>(Op1)) {
37 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
38 return ReplaceInstUsesWith(I, Op0);
39 else // X << undef, X >>u undef -> 0
40 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
43 // See if we can fold away this shift.
44 if (SimplifyDemandedInstructionBits(I))
47 // Try to fold constant and into select arguments.
48 if (isa<Constant>(Op0))
49 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
50 if (Instruction *R = FoldOpIntoSelect(I, SI))
53 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
54 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
57 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
58 // Because shifts by negative values are undefined.
59 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op1))
60 if (BO->hasOneUse() && BO->getOpcode() == Instruction::SRem)
61 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
62 if (CI->getValue().isPowerOf2()) {
63 Constant *C = ConstantInt::get(BO->getType(), CI->getValue()-1);
64 Value *Rem = Builder->CreateAnd(BO->getOperand(0), C, BO->getName());
72 /// CanEvaluateShifted - See if we can compute the specified value, but shifted
73 /// logically to the left or right by some number of bits. This should return
74 /// true if the expression can be computed for the same cost as the current
75 /// expression tree. This is used to eliminate extraneous shifting from things
77 /// %C = shl i128 %A, 64
78 /// %D = shl i128 %B, 96
79 /// %E = or i128 %C, %D
80 /// %F = lshr i128 %E, 64
81 /// where the client will ask if E can be computed shifted right by 64-bits. If
82 /// this succeeds, the GetShiftedValue function will be called to produce the
84 static bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
86 // We can always evaluate constants shifted.
90 Instruction *I = dyn_cast<Instruction>(V);
93 // If this is the opposite shift, we can directly reuse the input of the shift
94 // if the needed bits are already zero in the input. This allows us to reuse
95 // the value which means that we don't care if the shift has multiple uses.
96 // TODO: Handle opposite shift by exact value.
98 if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
99 (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
100 if (CI->getZExtValue() == NumBits) {
101 // TODO: Check that the input bits are already zero with MaskedValueIsZero
103 // If this is a truncate of a logical shr, we can truncate it to a smaller
104 // lshr iff we know that the bits we would otherwise be shifting in are
106 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
107 uint32_t BitWidth = Ty->getScalarSizeInBits();
108 if (MaskedValueIsZero(I->getOperand(0),
109 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
110 CI->getLimitedValue(BitWidth) < BitWidth) {
111 return CanEvaluateTruncated(I->getOperand(0), Ty);
118 // We can't mutate something that has multiple uses: doing so would
119 // require duplicating the instruction in general, which isn't profitable.
120 if (!I->hasOneUse()) return false;
122 switch (I->getOpcode()) {
123 default: return false;
124 case Instruction::And:
125 case Instruction::Or:
126 case Instruction::Xor:
127 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
128 return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
129 CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
131 case Instruction::Shl: {
132 // We can often fold the shift into shifts-by-a-constant.
133 CI = dyn_cast<ConstantInt>(I->getOperand(1));
134 if (CI == 0) return false;
136 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
137 if (isLeftShift) return true;
139 // We can always turn shl(c)+shr(c) -> and(c2).
140 if (CI->getValue() == NumBits) return true;
142 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
144 // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
145 // profitable unless we know the and'd out bits are already zero.
146 if (CI->getZExtValue() > NumBits) {
147 unsigned LowBits = TypeWidth - CI->getZExtValue();
148 if (MaskedValueIsZero(I->getOperand(0),
149 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
155 case Instruction::LShr: {
156 // We can often fold the shift into shifts-by-a-constant.
157 CI = dyn_cast<ConstantInt>(I->getOperand(1));
158 if (CI == 0) return false;
160 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
161 if (!isLeftShift) return true;
163 // We can always turn lshr(c)+shl(c) -> and(c2).
164 if (CI->getValue() == NumBits) return true;
166 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
168 // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
169 // profitable unless we know the and'd out bits are already zero.
170 if (CI->getZExtValue() > NumBits) {
171 unsigned LowBits = CI->getZExtValue() - NumBits;
172 if (MaskedValueIsZero(I->getOperand(0),
173 APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
179 case Instruction::Select: {
180 SelectInst *SI = cast<SelectInst>(I);
181 return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
182 CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
184 case Instruction::PHI: {
185 // We can change a phi if we can change all operands. Note that we never
186 // get into trouble with cyclic PHIs here because we only consider
187 // instructions with a single use.
188 PHINode *PN = cast<PHINode>(I);
189 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
190 if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
197 /// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
198 /// this value inserts the new computation that produces the shifted value.
199 static Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
201 // We can always evaluate constants shifted.
202 if (Constant *C = dyn_cast<Constant>(V)) {
204 V = IC.Builder->CreateShl(C, NumBits);
206 V = IC.Builder->CreateLShr(C, NumBits);
207 // If we got a constantexpr back, try to simplify it with TD info.
208 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
209 V = ConstantFoldConstantExpression(CE, IC.getTargetData());
213 Instruction *I = cast<Instruction>(V);
216 switch (I->getOpcode()) {
217 default: assert(0 && "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.
222 I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
223 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
226 case Instruction::Shl: {
227 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
229 // We only accept shifts-by-a-constant in CanEvaluateShifted.
230 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
232 // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
234 // If this is oversized composite shift, then unsigned shifts get 0.
235 unsigned NewShAmt = NumBits+CI->getZExtValue();
236 if (NewShAmt >= TypeWidth)
237 return Constant::getNullValue(I->getType());
239 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
243 // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
245 if (CI->getValue() == NumBits) {
246 APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
247 V = IC.Builder->CreateAnd(I->getOperand(0),
248 ConstantInt::get(I->getContext(), Mask));
249 if (Instruction *VI = dyn_cast<Instruction>(V)) {
256 // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
257 // the and won't be needed.
258 assert(CI->getZExtValue() > NumBits);
259 I->setOperand(1, ConstantInt::get(I->getType(),
260 CI->getZExtValue() - NumBits));
263 case Instruction::LShr: {
264 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
265 // We only accept shifts-by-a-constant in CanEvaluateShifted.
266 ConstantInt *CI = cast<ConstantInt>(I->getOperand(1));
268 // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
270 // If this is oversized composite shift, then unsigned shifts get 0.
271 unsigned NewShAmt = NumBits+CI->getZExtValue();
272 if (NewShAmt >= TypeWidth)
273 return Constant::getNullValue(I->getType());
275 I->setOperand(1, ConstantInt::get(I->getType(), NewShAmt));
279 // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
281 if (CI->getValue() == NumBits) {
282 APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
283 V = IC.Builder->CreateAnd(I->getOperand(0),
284 ConstantInt::get(I->getContext(), Mask));
285 if (Instruction *VI = dyn_cast<Instruction>(V)) {
292 // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
293 // the and won't be needed.
294 assert(CI->getZExtValue() > NumBits);
295 I->setOperand(1, ConstantInt::get(I->getType(),
296 CI->getZExtValue() - NumBits));
300 case Instruction::Select:
301 I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
302 I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
304 case Instruction::PHI: {
305 // We can change a phi if we can change all operands. Note that we never
306 // get into trouble with cyclic PHIs here because we only consider
307 // instructions with a single use.
308 PHINode *PN = cast<PHINode>(I);
309 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
310 PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
311 NumBits, isLeftShift, IC));
319 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
321 bool isLeftShift = I.getOpcode() == Instruction::Shl;
324 // See if we can propagate this shift into the input, this covers the trivial
325 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
326 if (I.getOpcode() != Instruction::AShr &&
327 CanEvaluateShifted(Op0, Op1->getZExtValue(), isLeftShift, *this)) {
328 DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
329 " to eliminate shift:\n IN: " << *Op0 << "\n SH: " << I <<"\n");
331 return ReplaceInstUsesWith(I,
332 GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
336 // See if we can simplify any instructions used by the instruction whose sole
337 // purpose is to compute bits we don't care about.
338 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
340 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
343 if (Op1->uge(TypeBits)) {
344 if (I.getOpcode() != Instruction::AShr)
345 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
346 // ashr i32 X, 32 --> ashr i32 X, 31
347 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
351 // ((X*C1) << C2) == (X * (C1 << C2))
352 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
353 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
354 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
355 return BinaryOperator::CreateMul(BO->getOperand(0),
356 ConstantExpr::getShl(BOOp, Op1));
358 // Try to fold constant and into select arguments.
359 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
360 if (Instruction *R = FoldOpIntoSelect(I, SI))
362 if (isa<PHINode>(Op0))
363 if (Instruction *NV = FoldOpIntoPhi(I))
366 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
367 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
368 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
369 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
370 // place. Don't try to do this transformation in this case. Also, we
371 // require that the input operand is a shift-by-constant so that we have
372 // confidence that the shifts will get folded together. We could do this
373 // xform in more cases, but it is unlikely to be profitable.
374 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
375 isa<ConstantInt>(TrOp->getOperand(1))) {
376 // Okay, we'll do this xform. Make the shift of shift.
377 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
378 // (shift2 (shift1 & 0x00FF), c2)
379 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
381 // For logical shifts, the truncation has the effect of making the high
382 // part of the register be zeros. Emulate this by inserting an AND to
383 // clear the top bits as needed. This 'and' will usually be zapped by
384 // other xforms later if dead.
385 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
386 unsigned DstSize = TI->getType()->getScalarSizeInBits();
387 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
389 // The mask we constructed says what the trunc would do if occurring
390 // between the shifts. We want to know the effect *after* the second
391 // shift. We know that it is a logical shift by a constant, so adjust the
392 // mask as appropriate.
393 if (I.getOpcode() == Instruction::Shl)
394 MaskV <<= Op1->getZExtValue();
396 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
397 MaskV = MaskV.lshr(Op1->getZExtValue());
401 Value *And = Builder->CreateAnd(NSh,
402 ConstantInt::get(I.getContext(), MaskV),
405 // Return the value truncated to the interesting size.
406 return new TruncInst(And, I.getType());
410 if (Op0->hasOneUse()) {
411 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
412 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
415 switch (Op0BO->getOpcode()) {
417 case Instruction::Add:
418 case Instruction::And:
419 case Instruction::Or:
420 case Instruction::Xor: {
421 // These operators commute.
422 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
423 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
424 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
426 Value *YS = // (Y << C)
427 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
429 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
430 Op0BO->getOperand(1)->getName());
431 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
432 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
433 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
436 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
437 Value *Op0BOOp1 = Op0BO->getOperand(1);
438 if (isLeftShift && Op0BOOp1->hasOneUse() &&
440 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
441 m_ConstantInt(CC))) &&
442 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
443 Value *YS = // (Y << C)
444 Builder->CreateShl(Op0BO->getOperand(0), Op1,
447 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
448 V1->getName()+".mask");
449 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
454 case Instruction::Sub: {
455 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
456 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
457 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
459 Value *YS = // (Y << C)
460 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
462 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
463 Op0BO->getOperand(0)->getName());
464 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
465 return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
466 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
469 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
470 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
471 match(Op0BO->getOperand(0),
472 m_And(m_Shr(m_Value(V1), m_Value(V2)),
473 m_ConstantInt(CC))) && V2 == Op1 &&
474 cast<BinaryOperator>(Op0BO->getOperand(0))
475 ->getOperand(0)->hasOneUse()) {
476 Value *YS = // (Y << C)
477 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
479 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
480 V1->getName()+".mask");
482 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
490 // If the operand is an bitwise operator with a constant RHS, and the
491 // shift is the only use, we can pull it out of the shift.
492 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
493 bool isValid = true; // Valid only for And, Or, Xor
494 bool highBitSet = false; // Transform if high bit of constant set?
496 switch (Op0BO->getOpcode()) {
497 default: isValid = false; break; // Do not perform transform!
498 case Instruction::Add:
499 isValid = isLeftShift;
501 case Instruction::Or:
502 case Instruction::Xor:
505 case Instruction::And:
510 // If this is a signed shift right, and the high bit is modified
511 // by the logical operation, do not perform the transformation.
512 // The highBitSet boolean indicates the value of the high bit of
513 // the constant which would cause it to be modified for this
516 if (isValid && I.getOpcode() == Instruction::AShr)
517 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
520 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
523 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
524 NewShift->takeName(Op0BO);
526 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
533 // Find out if this is a shift of a shift by a constant.
534 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
535 if (ShiftOp && !ShiftOp->isShift())
538 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
539 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
540 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
541 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
542 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
543 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
544 Value *X = ShiftOp->getOperand(0);
546 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
548 const IntegerType *Ty = cast<IntegerType>(I.getType());
550 // Check for (X << c1) << c2 and (X >> c1) >> c2
551 if (I.getOpcode() == ShiftOp->getOpcode()) {
552 // If this is oversized composite shift, then unsigned shifts get 0, ashr
554 if (AmtSum >= TypeBits) {
555 if (I.getOpcode() != Instruction::AShr)
556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
557 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
560 return BinaryOperator::Create(I.getOpcode(), X,
561 ConstantInt::get(Ty, AmtSum));
564 if (ShiftAmt1 == ShiftAmt2) {
565 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
566 if (I.getOpcode() == Instruction::Shl &&
567 ShiftOp->getOpcode() != Instruction::Shl) {
568 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
569 return BinaryOperator::CreateAnd(X,
570 ConstantInt::get(I.getContext(),Mask));
572 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
573 if (I.getOpcode() == Instruction::LShr &&
574 ShiftOp->getOpcode() == Instruction::Shl) {
575 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
576 return BinaryOperator::CreateAnd(X,
577 ConstantInt::get(I.getContext(), Mask));
579 } else if (ShiftAmt1 < ShiftAmt2) {
580 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
582 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
583 if (I.getOpcode() == Instruction::Shl &&
584 ShiftOp->getOpcode() != Instruction::Shl) {
585 assert(ShiftOp->getOpcode() == Instruction::LShr ||
586 ShiftOp->getOpcode() == Instruction::AShr);
587 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
589 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
590 return BinaryOperator::CreateAnd(Shift,
591 ConstantInt::get(I.getContext(),Mask));
594 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
595 if (I.getOpcode() == Instruction::LShr &&
596 ShiftOp->getOpcode() == Instruction::Shl) {
597 assert(ShiftOp->getOpcode() == Instruction::Shl);
598 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
600 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
601 return BinaryOperator::CreateAnd(Shift,
602 ConstantInt::get(I.getContext(),Mask));
605 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
607 assert(ShiftAmt2 < ShiftAmt1);
608 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
610 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
611 if (I.getOpcode() == Instruction::Shl &&
612 ShiftOp->getOpcode() != Instruction::Shl) {
613 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
614 ConstantInt::get(Ty, ShiftDiff));
616 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
617 return BinaryOperator::CreateAnd(Shift,
618 ConstantInt::get(I.getContext(),Mask));
621 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
622 if (I.getOpcode() == Instruction::LShr &&
623 ShiftOp->getOpcode() == Instruction::Shl) {
624 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
626 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
627 return BinaryOperator::CreateAnd(Shift,
628 ConstantInt::get(I.getContext(),Mask));
631 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
637 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
638 return commonShiftTransforms(I);
641 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
642 if (Instruction *R = commonShiftTransforms(I))
645 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
647 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1))
648 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
649 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
650 // ctlz.i32(x)>>5 --> zext(x == 0)
651 // cttz.i32(x)>>5 --> zext(x == 0)
652 // ctpop.i32(x)>>5 --> zext(x == -1)
653 if ((II->getIntrinsicID() == Intrinsic::ctlz ||
654 II->getIntrinsicID() == Intrinsic::cttz ||
655 II->getIntrinsicID() == Intrinsic::ctpop) &&
656 isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == Op1C->getZExtValue()){
657 bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
658 Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
659 Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
660 return new ZExtInst(Cmp, II->getType());
667 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
668 if (Instruction *R = commonShiftTransforms(I))
671 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
673 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) {
674 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
675 if (CSI->isAllOnesValue())
676 return ReplaceInstUsesWith(I, CSI);
679 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
680 // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
681 // have a sign-extend idiom.
683 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
684 // If the input value is known to already be sign extended enough, delete
686 if (ComputeNumSignBits(X) > Op1C->getZExtValue())
687 return ReplaceInstUsesWith(I, X);
689 // If the input is an extension from the shifted amount value, e.g.
690 // %x = zext i8 %A to i32
691 // %y = shl i32 %x, 24
693 // then turn this into "z = sext i8 A to i32".
694 if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
695 uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
696 uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
697 if (Op1C->getZExtValue() == DestBits-SrcBits)
698 return new SExtInst(ZI->getOperand(0), ZI->getType());
703 // See if we can turn a signed shr into an unsigned shr.
704 if (MaskedValueIsZero(Op0,
705 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
706 return BinaryOperator::CreateLShr(Op0, Op1);
708 // Arithmetic shifting an all-sign-bit value is a no-op.
709 unsigned NumSignBits = ComputeNumSignBits(Op0);
710 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
711 return ReplaceInstUsesWith(I, Op0);