InstCombineShifts.cpp revision a85732fa3bf17dd48b897f76533142ac0f2ec140
1//===- 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
14#include "InstCombine.h"
15#include "llvm/Support/PatternMatch.h"
16using namespace llvm;
17using namespace PatternMatch;
18
19Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
20  assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
21  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
22
23  // shl X, 0 == X and shr X, 0 == X
24  // shl 0, X == 0 and shr 0, X == 0
25  if (Op1 == Constant::getNullValue(Op1->getType()) ||
26      Op0 == Constant::getNullValue(Op0->getType()))
27    return ReplaceInstUsesWith(I, Op0);
28
29  if (isa<UndefValue>(Op0)) {
30    if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
31      return ReplaceInstUsesWith(I, Op0);
32    else                                    // undef << X -> 0, undef >>u X -> 0
33      return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
34  }
35  if (isa<UndefValue>(Op1)) {
36    if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
37      return ReplaceInstUsesWith(I, Op0);
38    else                                     // X << undef, X >>u undef -> 0
39      return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
40  }
41
42  // See if we can fold away this shift.
43  if (SimplifyDemandedInstructionBits(I))
44    return &I;
45
46  // Try to fold constant and into select arguments.
47  if (isa<Constant>(Op0))
48    if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
49      if (Instruction *R = FoldOpIntoSelect(I, SI))
50        return R;
51
52  if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
53    if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
54      return Res;
55  return 0;
56}
57
58Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
59                                               BinaryOperator &I) {
60  bool isLeftShift = I.getOpcode() == Instruction::Shl;
61
62  // See if we can simplify any instructions used by the instruction whose sole
63  // purpose is to compute bits we don't care about.
64  uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
65
66  // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
67  // a signed shift.
68  //
69  if (Op1->uge(TypeBits)) {
70    if (I.getOpcode() != Instruction::AShr)
71      return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
72    else {
73      I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
74      return &I;
75    }
76  }
77
78  // ((X*C1) << C2) == (X * (C1 << C2))
79  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
80    if (BO->getOpcode() == Instruction::Mul && isLeftShift)
81      if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
82        return BinaryOperator::CreateMul(BO->getOperand(0),
83                                        ConstantExpr::getShl(BOOp, Op1));
84
85  // Try to fold constant and into select arguments.
86  if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
87    if (Instruction *R = FoldOpIntoSelect(I, SI))
88      return R;
89  if (isa<PHINode>(Op0))
90    if (Instruction *NV = FoldOpIntoPhi(I))
91      return NV;
92
93  // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
94  if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
95    Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
96    // If 'shift2' is an ashr, we would have to get the sign bit into a funny
97    // place.  Don't try to do this transformation in this case.  Also, we
98    // require that the input operand is a shift-by-constant so that we have
99    // confidence that the shifts will get folded together.  We could do this
100    // xform in more cases, but it is unlikely to be profitable.
101    if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
102        isa<ConstantInt>(TrOp->getOperand(1))) {
103      // Okay, we'll do this xform.  Make the shift of shift.
104      Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
105      // (shift2 (shift1 & 0x00FF), c2)
106      Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
107
108      // For logical shifts, the truncation has the effect of making the high
109      // part of the register be zeros.  Emulate this by inserting an AND to
110      // clear the top bits as needed.  This 'and' will usually be zapped by
111      // other xforms later if dead.
112      unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
113      unsigned DstSize = TI->getType()->getScalarSizeInBits();
114      APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
115
116      // The mask we constructed says what the trunc would do if occurring
117      // between the shifts.  We want to know the effect *after* the second
118      // shift.  We know that it is a logical shift by a constant, so adjust the
119      // mask as appropriate.
120      if (I.getOpcode() == Instruction::Shl)
121        MaskV <<= Op1->getZExtValue();
122      else {
123        assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
124        MaskV = MaskV.lshr(Op1->getZExtValue());
125      }
126
127      // shift1 & 0x00FF
128      Value *And = Builder->CreateAnd(NSh,
129                                      ConstantInt::get(I.getContext(), MaskV),
130                                      TI->getName());
131
132      // Return the value truncated to the interesting size.
133      return new TruncInst(And, I.getType());
134    }
135  }
136
137  if (Op0->hasOneUse()) {
138    if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
139      // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
140      Value *V1, *V2;
141      ConstantInt *CC;
142      switch (Op0BO->getOpcode()) {
143        default: break;
144        case Instruction::Add:
145        case Instruction::And:
146        case Instruction::Or:
147        case Instruction::Xor: {
148          // These operators commute.
149          // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
150          if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
151              match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
152                    m_Specific(Op1)))) {
153            Value *YS =         // (Y << C)
154              Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
155            // (X + (Y << C))
156            Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
157                                            Op0BO->getOperand(1)->getName());
158            uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
159            return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
160                       APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
161          }
162
163          // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
164          Value *Op0BOOp1 = Op0BO->getOperand(1);
165          if (isLeftShift && Op0BOOp1->hasOneUse() &&
166              match(Op0BOOp1,
167                    m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
168                          m_ConstantInt(CC))) &&
169              cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
170            Value *YS =   // (Y << C)
171              Builder->CreateShl(Op0BO->getOperand(0), Op1,
172                                           Op0BO->getName());
173            // X & (CC << C)
174            Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
175                                           V1->getName()+".mask");
176            return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
177          }
178        }
179
180        // FALL THROUGH.
181        case Instruction::Sub: {
182          // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
183          if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
184              match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
185                    m_Specific(Op1)))) {
186            Value *YS =  // (Y << C)
187              Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
188            // (X + (Y << C))
189            Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
190                                            Op0BO->getOperand(0)->getName());
191            uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
192            return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
193                       APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
194          }
195
196          // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
197          if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
198              match(Op0BO->getOperand(0),
199                    m_And(m_Shr(m_Value(V1), m_Value(V2)),
200                          m_ConstantInt(CC))) && V2 == Op1 &&
201              cast<BinaryOperator>(Op0BO->getOperand(0))
202                  ->getOperand(0)->hasOneUse()) {
203            Value *YS = // (Y << C)
204              Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
205            // X & (CC << C)
206            Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
207                                           V1->getName()+".mask");
208
209            return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
210          }
211
212          break;
213        }
214      }
215
216
217      // If the operand is an bitwise operator with a constant RHS, and the
218      // shift is the only use, we can pull it out of the shift.
219      if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
220        bool isValid = true;     // Valid only for And, Or, Xor
221        bool highBitSet = false; // Transform if high bit of constant set?
222
223        switch (Op0BO->getOpcode()) {
224          default: isValid = false; break;   // Do not perform transform!
225          case Instruction::Add:
226            isValid = isLeftShift;
227            break;
228          case Instruction::Or:
229          case Instruction::Xor:
230            highBitSet = false;
231            break;
232          case Instruction::And:
233            highBitSet = true;
234            break;
235        }
236
237        // If this is a signed shift right, and the high bit is modified
238        // by the logical operation, do not perform the transformation.
239        // The highBitSet boolean indicates the value of the high bit of
240        // the constant which would cause it to be modified for this
241        // operation.
242        //
243        if (isValid && I.getOpcode() == Instruction::AShr)
244          isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
245
246        if (isValid) {
247          Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
248
249          Value *NewShift =
250            Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
251          NewShift->takeName(Op0BO);
252
253          return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
254                                        NewRHS);
255        }
256      }
257    }
258  }
259
260  // Find out if this is a shift of a shift by a constant.
261  BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
262  if (ShiftOp && !ShiftOp->isShift())
263    ShiftOp = 0;
264
265  if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
266    ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
267    uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
268    uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
269    assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
270    if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
271    Value *X = ShiftOp->getOperand(0);
272
273    uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
274
275    const IntegerType *Ty = cast<IntegerType>(I.getType());
276
277    // Check for (X << c1) << c2  and  (X >> c1) >> c2
278    if (I.getOpcode() == ShiftOp->getOpcode()) {
279      // If this is oversized composite shift, then unsigned shifts get 0, ashr
280      // saturates.
281      if (AmtSum >= TypeBits) {
282        if (I.getOpcode() != Instruction::AShr)
283          return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
284        AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
285      }
286
287      return BinaryOperator::Create(I.getOpcode(), X,
288                                    ConstantInt::get(Ty, AmtSum));
289    }
290
291    if (ShiftOp->getOpcode() == Instruction::LShr &&
292        I.getOpcode() == Instruction::AShr) {
293      if (AmtSum >= TypeBits)
294        return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
295
296      // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
297      return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
298    }
299
300    if (ShiftOp->getOpcode() == Instruction::AShr &&
301        I.getOpcode() == Instruction::LShr) {
302      // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
303      if (AmtSum >= TypeBits)
304        AmtSum = TypeBits-1;
305
306      Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
307
308      APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
309      return BinaryOperator::CreateAnd(Shift,
310                                       ConstantInt::get(I.getContext(), Mask));
311    }
312
313    // Okay, if we get here, one shift must be left, and the other shift must be
314    // right.  See if the amounts are equal.
315    if (ShiftAmt1 == ShiftAmt2) {
316      // If we have ((X >>? C) << C), turn this into X & (-1 << C).
317      if (I.getOpcode() == Instruction::Shl) {
318        APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
319        return BinaryOperator::CreateAnd(X,
320                                         ConstantInt::get(I.getContext(),Mask));
321      }
322      // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
323      if (I.getOpcode() == Instruction::LShr) {
324        APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
325        return BinaryOperator::CreateAnd(X,
326                                        ConstantInt::get(I.getContext(), Mask));
327      }
328      // We can simplify ((X << C) >>s C) into a trunc + sext.
329      // NOTE: we could do this for any C, but that would make 'unusual' integer
330      // types.  For now, just stick to ones well-supported by the code
331      // generators.
332      const Type *SExtType = 0;
333      switch (Ty->getBitWidth() - ShiftAmt1) {
334      case 1  :
335      case 8  :
336      case 16 :
337      case 32 :
338      case 64 :
339      case 128:
340        SExtType = IntegerType::get(I.getContext(),
341                                    Ty->getBitWidth() - ShiftAmt1);
342        break;
343      default: break;
344      }
345      if (SExtType)
346        return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
347      // Otherwise, we can't handle it yet.
348    } else if (ShiftAmt1 < ShiftAmt2) {
349      uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
350
351      // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
352      if (I.getOpcode() == Instruction::Shl) {
353        assert(ShiftOp->getOpcode() == Instruction::LShr ||
354               ShiftOp->getOpcode() == Instruction::AShr);
355        Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
356
357        APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
358        return BinaryOperator::CreateAnd(Shift,
359                                         ConstantInt::get(I.getContext(),Mask));
360      }
361
362      // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
363      if (I.getOpcode() == Instruction::LShr) {
364        assert(ShiftOp->getOpcode() == Instruction::Shl);
365        Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
366
367        APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
368        return BinaryOperator::CreateAnd(Shift,
369                                         ConstantInt::get(I.getContext(),Mask));
370      }
371
372      // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
373    } else {
374      assert(ShiftAmt2 < ShiftAmt1);
375      uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
376
377      // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
378      if (I.getOpcode() == Instruction::Shl) {
379        assert(ShiftOp->getOpcode() == Instruction::LShr ||
380               ShiftOp->getOpcode() == Instruction::AShr);
381        Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
382                                            ConstantInt::get(Ty, ShiftDiff));
383
384        APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
385        return BinaryOperator::CreateAnd(Shift,
386                                         ConstantInt::get(I.getContext(),Mask));
387      }
388
389      // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
390      if (I.getOpcode() == Instruction::LShr) {
391        assert(ShiftOp->getOpcode() == Instruction::Shl);
392        Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
393
394        APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
395        return BinaryOperator::CreateAnd(Shift,
396                                         ConstantInt::get(I.getContext(),Mask));
397      }
398
399      // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
400    }
401  }
402  return 0;
403}
404
405Instruction *InstCombiner::visitShl(BinaryOperator &I) {
406  return commonShiftTransforms(I);
407}
408
409Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
410  return commonShiftTransforms(I);
411}
412
413Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
414  if (Instruction *R = commonShiftTransforms(I))
415    return R;
416
417  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
418
419  if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0)) {
420    // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
421    if (CSI->isAllOnesValue())
422      return ReplaceInstUsesWith(I, CSI);
423  }
424
425  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
426    // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
427    // have a sign-extend idiom.  If the input value is known to already be sign
428    // extended enough, delete the extension.
429    Value *X;
430    if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
431        ComputeNumSignBits(X) > Op1C->getZExtValue())
432      return ReplaceInstUsesWith(I, X);
433  }
434
435  // See if we can turn a signed shr into an unsigned shr.
436  if (MaskedValueIsZero(Op0,
437                        APInt::getSignBit(I.getType()->getScalarSizeInBits())))
438    return BinaryOperator::CreateLShr(Op0, Op1);
439
440  // Arithmetic shifting an all-sign-bit value is a no-op.
441  unsigned NumSignBits = ComputeNumSignBits(Op0);
442  if (NumSignBits == Op0->getType()->getScalarSizeInBits())
443    return ReplaceInstUsesWith(I, Op0);
444
445  return 0;
446}
447
448