InstCombineShifts.cpp revision 226633
1202375Srdivacky//===- InstCombineShifts.cpp ----------------------------------------------===//
2202375Srdivacky//
3202375Srdivacky//                     The LLVM Compiler Infrastructure
4202375Srdivacky//
5202375Srdivacky// This file is distributed under the University of Illinois Open Source
6202375Srdivacky// License. See LICENSE.TXT for details.
7202375Srdivacky//
8202375Srdivacky//===----------------------------------------------------------------------===//
9202375Srdivacky//
10202375Srdivacky// This file implements the visitShl, visitLShr, and visitAShr functions.
11202375Srdivacky//
12202375Srdivacky//===----------------------------------------------------------------------===//
13202375Srdivacky
14202375Srdivacky#include "InstCombine.h"
15203954Srdivacky#include "llvm/IntrinsicInst.h"
16226633Sdim#include "llvm/Analysis/ConstantFolding.h"
17218893Sdim#include "llvm/Analysis/InstructionSimplify.h"
18202375Srdivacky#include "llvm/Support/PatternMatch.h"
19202375Srdivackyusing namespace llvm;
20202375Srdivackyusing namespace PatternMatch;
21202375Srdivacky
22202375SrdivackyInstruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
23202375Srdivacky  assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
24202375Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
25202375Srdivacky
26202375Srdivacky  // See if we can fold away this shift.
27202375Srdivacky  if (SimplifyDemandedInstructionBits(I))
28202375Srdivacky    return &I;
29202375Srdivacky
30202375Srdivacky  // Try to fold constant and into select arguments.
31202375Srdivacky  if (isa<Constant>(Op0))
32202375Srdivacky    if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
33202375Srdivacky      if (Instruction *R = FoldOpIntoSelect(I, SI))
34202375Srdivacky        return R;
35202375Srdivacky
36202375Srdivacky  if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
37202375Srdivacky    if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
38202375Srdivacky      return Res;
39218893Sdim
40218893Sdim  // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
41218893Sdim  // Because shifts by negative values (which could occur if A were negative)
42218893Sdim  // are undefined.
43218893Sdim  Value *A; const APInt *B;
44218893Sdim  if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
45218893Sdim    // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
46218893Sdim    // demand the sign bit (and many others) here??
47218893Sdim    Value *Rem = Builder->CreateAnd(A, ConstantInt::get(I.getType(), *B-1),
48218893Sdim                                    Op1->getName());
49218893Sdim    I.setOperand(1, Rem);
50218893Sdim    return &I;
51218893Sdim  }
52218893Sdim
53202375Srdivacky  return 0;
54202375Srdivacky}
55202375Srdivacky
56212904Sdim/// CanEvaluateShifted - See if we can compute the specified value, but shifted
57212904Sdim/// logically to the left or right by some number of bits.  This should return
58212904Sdim/// true if the expression can be computed for the same cost as the current
59212904Sdim/// expression tree.  This is used to eliminate extraneous shifting from things
60212904Sdim/// like:
61212904Sdim///      %C = shl i128 %A, 64
62212904Sdim///      %D = shl i128 %B, 96
63212904Sdim///      %E = or i128 %C, %D
64212904Sdim///      %F = lshr i128 %E, 64
65212904Sdim/// where the client will ask if E can be computed shifted right by 64-bits.  If
66212904Sdim/// this succeeds, the GetShiftedValue function will be called to produce the
67212904Sdim/// value.
68212904Sdimstatic bool CanEvaluateShifted(Value *V, unsigned NumBits, bool isLeftShift,
69212904Sdim                               InstCombiner &IC) {
70212904Sdim  // We can always evaluate constants shifted.
71212904Sdim  if (isa<Constant>(V))
72212904Sdim    return true;
73212904Sdim
74212904Sdim  Instruction *I = dyn_cast<Instruction>(V);
75212904Sdim  if (!I) return false;
76212904Sdim
77212904Sdim  // If this is the opposite shift, we can directly reuse the input of the shift
78212904Sdim  // if the needed bits are already zero in the input.  This allows us to reuse
79212904Sdim  // the value which means that we don't care if the shift has multiple uses.
80212904Sdim  //  TODO:  Handle opposite shift by exact value.
81218893Sdim  ConstantInt *CI = 0;
82212904Sdim  if ((isLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
83212904Sdim      (!isLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
84212904Sdim    if (CI->getZExtValue() == NumBits) {
85212904Sdim      // TODO: Check that the input bits are already zero with MaskedValueIsZero
86212904Sdim#if 0
87212904Sdim      // If this is a truncate of a logical shr, we can truncate it to a smaller
88212904Sdim      // lshr iff we know that the bits we would otherwise be shifting in are
89212904Sdim      // already zeros.
90212904Sdim      uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
91212904Sdim      uint32_t BitWidth = Ty->getScalarSizeInBits();
92212904Sdim      if (MaskedValueIsZero(I->getOperand(0),
93212904Sdim            APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
94212904Sdim          CI->getLimitedValue(BitWidth) < BitWidth) {
95212904Sdim        return CanEvaluateTruncated(I->getOperand(0), Ty);
96212904Sdim      }
97212904Sdim#endif
98212904Sdim
99212904Sdim    }
100212904Sdim  }
101212904Sdim
102212904Sdim  // We can't mutate something that has multiple uses: doing so would
103212904Sdim  // require duplicating the instruction in general, which isn't profitable.
104212904Sdim  if (!I->hasOneUse()) return false;
105212904Sdim
106212904Sdim  switch (I->getOpcode()) {
107212904Sdim  default: return false;
108212904Sdim  case Instruction::And:
109212904Sdim  case Instruction::Or:
110212904Sdim  case Instruction::Xor:
111212904Sdim    // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
112212904Sdim    return CanEvaluateShifted(I->getOperand(0), NumBits, isLeftShift, IC) &&
113212904Sdim           CanEvaluateShifted(I->getOperand(1), NumBits, isLeftShift, IC);
114212904Sdim
115212904Sdim  case Instruction::Shl: {
116212904Sdim    // We can often fold the shift into shifts-by-a-constant.
117212904Sdim    CI = dyn_cast<ConstantInt>(I->getOperand(1));
118212904Sdim    if (CI == 0) return false;
119212904Sdim
120212904Sdim    // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
121212904Sdim    if (isLeftShift) return true;
122212904Sdim
123212904Sdim    // We can always turn shl(c)+shr(c) -> and(c2).
124212904Sdim    if (CI->getValue() == NumBits) return true;
125212904Sdim
126212904Sdim    unsigned TypeWidth = I->getType()->getScalarSizeInBits();
127212904Sdim
128212904Sdim    // We can turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but it isn't
129212904Sdim    // profitable unless we know the and'd out bits are already zero.
130212904Sdim    if (CI->getZExtValue() > NumBits) {
131218893Sdim      unsigned LowBits = TypeWidth - CI->getZExtValue();
132212904Sdim      if (MaskedValueIsZero(I->getOperand(0),
133218893Sdim                       APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
134212904Sdim        return true;
135212904Sdim    }
136212904Sdim
137212904Sdim    return false;
138212904Sdim  }
139212904Sdim  case Instruction::LShr: {
140212904Sdim    // We can often fold the shift into shifts-by-a-constant.
141212904Sdim    CI = dyn_cast<ConstantInt>(I->getOperand(1));
142212904Sdim    if (CI == 0) return false;
143212904Sdim
144212904Sdim    // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
145212904Sdim    if (!isLeftShift) return true;
146212904Sdim
147212904Sdim    // We can always turn lshr(c)+shl(c) -> and(c2).
148212904Sdim    if (CI->getValue() == NumBits) return true;
149212904Sdim
150212904Sdim    unsigned TypeWidth = I->getType()->getScalarSizeInBits();
151212904Sdim
152212904Sdim    // We can always turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but it isn't
153212904Sdim    // profitable unless we know the and'd out bits are already zero.
154212904Sdim    if (CI->getZExtValue() > NumBits) {
155212904Sdim      unsigned LowBits = CI->getZExtValue() - NumBits;
156212904Sdim      if (MaskedValueIsZero(I->getOperand(0),
157218893Sdim                          APInt::getLowBitsSet(TypeWidth, NumBits) << LowBits))
158212904Sdim        return true;
159212904Sdim    }
160212904Sdim
161212904Sdim    return false;
162212904Sdim  }
163212904Sdim  case Instruction::Select: {
164212904Sdim    SelectInst *SI = cast<SelectInst>(I);
165212904Sdim    return CanEvaluateShifted(SI->getTrueValue(), NumBits, isLeftShift, IC) &&
166212904Sdim           CanEvaluateShifted(SI->getFalseValue(), NumBits, isLeftShift, IC);
167212904Sdim  }
168212904Sdim  case Instruction::PHI: {
169212904Sdim    // We can change a phi if we can change all operands.  Note that we never
170212904Sdim    // get into trouble with cyclic PHIs here because we only consider
171212904Sdim    // instructions with a single use.
172212904Sdim    PHINode *PN = cast<PHINode>(I);
173212904Sdim    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
174212904Sdim      if (!CanEvaluateShifted(PN->getIncomingValue(i), NumBits, isLeftShift,IC))
175212904Sdim        return false;
176212904Sdim    return true;
177212904Sdim  }
178212904Sdim  }
179212904Sdim}
180212904Sdim
181212904Sdim/// GetShiftedValue - When CanEvaluateShifted returned true for an expression,
182212904Sdim/// this value inserts the new computation that produces the shifted value.
183212904Sdimstatic Value *GetShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
184212904Sdim                              InstCombiner &IC) {
185212904Sdim  // We can always evaluate constants shifted.
186212904Sdim  if (Constant *C = dyn_cast<Constant>(V)) {
187212904Sdim    if (isLeftShift)
188212904Sdim      V = IC.Builder->CreateShl(C, NumBits);
189212904Sdim    else
190212904Sdim      V = IC.Builder->CreateLShr(C, NumBits);
191212904Sdim    // If we got a constantexpr back, try to simplify it with TD info.
192212904Sdim    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
193212904Sdim      V = ConstantFoldConstantExpression(CE, IC.getTargetData());
194212904Sdim    return V;
195212904Sdim  }
196212904Sdim
197212904Sdim  Instruction *I = cast<Instruction>(V);
198212904Sdim  IC.Worklist.Add(I);
199212904Sdim
200212904Sdim  switch (I->getOpcode()) {
201212904Sdim  default: assert(0 && "Inconsistency with CanEvaluateShifted");
202212904Sdim  case Instruction::And:
203212904Sdim  case Instruction::Or:
204212904Sdim  case Instruction::Xor:
205212904Sdim    // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
206212904Sdim    I->setOperand(0, GetShiftedValue(I->getOperand(0), NumBits,isLeftShift,IC));
207212904Sdim    I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
208212904Sdim    return I;
209212904Sdim
210212904Sdim  case Instruction::Shl: {
211226633Sdim    BinaryOperator *BO = cast<BinaryOperator>(I);
212226633Sdim    unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
213212904Sdim
214212904Sdim    // We only accept shifts-by-a-constant in CanEvaluateShifted.
215226633Sdim    ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
216226633Sdim
217212904Sdim    // We can always fold shl(c1)+shl(c2) -> shl(c1+c2).
218212904Sdim    if (isLeftShift) {
219212904Sdim      // If this is oversized composite shift, then unsigned shifts get 0.
220212904Sdim      unsigned NewShAmt = NumBits+CI->getZExtValue();
221212904Sdim      if (NewShAmt >= TypeWidth)
222212904Sdim        return Constant::getNullValue(I->getType());
223212904Sdim
224226633Sdim      BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
225226633Sdim      BO->setHasNoUnsignedWrap(false);
226226633Sdim      BO->setHasNoSignedWrap(false);
227212904Sdim      return I;
228212904Sdim    }
229212904Sdim
230212904Sdim    // We turn shl(c)+lshr(c) -> and(c2) if the input doesn't already have
231212904Sdim    // zeros.
232212904Sdim    if (CI->getValue() == NumBits) {
233212904Sdim      APInt Mask(APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits));
234226633Sdim      V = IC.Builder->CreateAnd(BO->getOperand(0),
235226633Sdim                                ConstantInt::get(BO->getContext(), Mask));
236212904Sdim      if (Instruction *VI = dyn_cast<Instruction>(V)) {
237226633Sdim        VI->moveBefore(BO);
238226633Sdim        VI->takeName(BO);
239212904Sdim      }
240212904Sdim      return V;
241212904Sdim    }
242212904Sdim
243212904Sdim    // We turn shl(c1)+shr(c2) -> shl(c3)+and(c4), but only when we know that
244212904Sdim    // the and won't be needed.
245212904Sdim    assert(CI->getZExtValue() > NumBits);
246226633Sdim    BO->setOperand(1, ConstantInt::get(BO->getType(),
247226633Sdim                                       CI->getZExtValue() - NumBits));
248226633Sdim    BO->setHasNoUnsignedWrap(false);
249226633Sdim    BO->setHasNoSignedWrap(false);
250226633Sdim    return BO;
251212904Sdim  }
252212904Sdim  case Instruction::LShr: {
253226633Sdim    BinaryOperator *BO = cast<BinaryOperator>(I);
254226633Sdim    unsigned TypeWidth = BO->getType()->getScalarSizeInBits();
255212904Sdim    // We only accept shifts-by-a-constant in CanEvaluateShifted.
256226633Sdim    ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
257212904Sdim
258212904Sdim    // We can always fold lshr(c1)+lshr(c2) -> lshr(c1+c2).
259212904Sdim    if (!isLeftShift) {
260212904Sdim      // If this is oversized composite shift, then unsigned shifts get 0.
261212904Sdim      unsigned NewShAmt = NumBits+CI->getZExtValue();
262212904Sdim      if (NewShAmt >= TypeWidth)
263226633Sdim        return Constant::getNullValue(BO->getType());
264212904Sdim
265226633Sdim      BO->setOperand(1, ConstantInt::get(BO->getType(), NewShAmt));
266226633Sdim      BO->setIsExact(false);
267212904Sdim      return I;
268212904Sdim    }
269212904Sdim
270212904Sdim    // We turn lshr(c)+shl(c) -> and(c2) if the input doesn't already have
271212904Sdim    // zeros.
272212904Sdim    if (CI->getValue() == NumBits) {
273212904Sdim      APInt Mask(APInt::getHighBitsSet(TypeWidth, TypeWidth - NumBits));
274212904Sdim      V = IC.Builder->CreateAnd(I->getOperand(0),
275226633Sdim                                ConstantInt::get(BO->getContext(), Mask));
276212904Sdim      if (Instruction *VI = dyn_cast<Instruction>(V)) {
277212904Sdim        VI->moveBefore(I);
278212904Sdim        VI->takeName(I);
279212904Sdim      }
280212904Sdim      return V;
281212904Sdim    }
282212904Sdim
283212904Sdim    // We turn lshr(c1)+shl(c2) -> lshr(c3)+and(c4), but only when we know that
284212904Sdim    // the and won't be needed.
285212904Sdim    assert(CI->getZExtValue() > NumBits);
286226633Sdim    BO->setOperand(1, ConstantInt::get(BO->getType(),
287226633Sdim                                       CI->getZExtValue() - NumBits));
288226633Sdim    BO->setIsExact(false);
289226633Sdim    return BO;
290212904Sdim  }
291212904Sdim
292212904Sdim  case Instruction::Select:
293212904Sdim    I->setOperand(1, GetShiftedValue(I->getOperand(1), NumBits,isLeftShift,IC));
294212904Sdim    I->setOperand(2, GetShiftedValue(I->getOperand(2), NumBits,isLeftShift,IC));
295212904Sdim    return I;
296212904Sdim  case Instruction::PHI: {
297212904Sdim    // We can change a phi if we can change all operands.  Note that we never
298212904Sdim    // get into trouble with cyclic PHIs here because we only consider
299212904Sdim    // instructions with a single use.
300212904Sdim    PHINode *PN = cast<PHINode>(I);
301212904Sdim    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
302212904Sdim      PN->setIncomingValue(i, GetShiftedValue(PN->getIncomingValue(i),
303212904Sdim                                              NumBits, isLeftShift, IC));
304212904Sdim    return PN;
305212904Sdim  }
306212904Sdim  }
307212904Sdim}
308212904Sdim
309212904Sdim
310212904Sdim
311202375SrdivackyInstruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
312202375Srdivacky                                               BinaryOperator &I) {
313202375Srdivacky  bool isLeftShift = I.getOpcode() == Instruction::Shl;
314212904Sdim
315212904Sdim
316212904Sdim  // See if we can propagate this shift into the input, this covers the trivial
317212904Sdim  // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
318212904Sdim  if (I.getOpcode() != Instruction::AShr &&
319212904Sdim      CanEvaluateShifted(Op0, Op1->getZExtValue(), isLeftShift, *this)) {
320212904Sdim    DEBUG(dbgs() << "ICE: GetShiftedValue propagating shift through expression"
321212904Sdim              " to eliminate shift:\n  IN: " << *Op0 << "\n  SH: " << I <<"\n");
322212904Sdim
323212904Sdim    return ReplaceInstUsesWith(I,
324212904Sdim                 GetShiftedValue(Op0, Op1->getZExtValue(), isLeftShift, *this));
325212904Sdim  }
326212904Sdim
327212904Sdim
328202375Srdivacky  // See if we can simplify any instructions used by the instruction whose sole
329202375Srdivacky  // purpose is to compute bits we don't care about.
330202375Srdivacky  uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
331202375Srdivacky
332202375Srdivacky  // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
333202375Srdivacky  // a signed shift.
334202375Srdivacky  //
335202375Srdivacky  if (Op1->uge(TypeBits)) {
336202375Srdivacky    if (I.getOpcode() != Instruction::AShr)
337202375Srdivacky      return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
338203954Srdivacky    // ashr i32 X, 32 --> ashr i32 X, 31
339203954Srdivacky    I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
340203954Srdivacky    return &I;
341202375Srdivacky  }
342202375Srdivacky
343202375Srdivacky  // ((X*C1) << C2) == (X * (C1 << C2))
344202375Srdivacky  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
345202375Srdivacky    if (BO->getOpcode() == Instruction::Mul && isLeftShift)
346202375Srdivacky      if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
347202375Srdivacky        return BinaryOperator::CreateMul(BO->getOperand(0),
348202375Srdivacky                                        ConstantExpr::getShl(BOOp, Op1));
349202375Srdivacky
350202375Srdivacky  // Try to fold constant and into select arguments.
351202375Srdivacky  if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
352202375Srdivacky    if (Instruction *R = FoldOpIntoSelect(I, SI))
353202375Srdivacky      return R;
354202375Srdivacky  if (isa<PHINode>(Op0))
355202375Srdivacky    if (Instruction *NV = FoldOpIntoPhi(I))
356202375Srdivacky      return NV;
357202375Srdivacky
358202375Srdivacky  // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
359202375Srdivacky  if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
360202375Srdivacky    Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
361202375Srdivacky    // If 'shift2' is an ashr, we would have to get the sign bit into a funny
362202375Srdivacky    // place.  Don't try to do this transformation in this case.  Also, we
363202375Srdivacky    // require that the input operand is a shift-by-constant so that we have
364202375Srdivacky    // confidence that the shifts will get folded together.  We could do this
365202375Srdivacky    // xform in more cases, but it is unlikely to be profitable.
366202375Srdivacky    if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
367202375Srdivacky        isa<ConstantInt>(TrOp->getOperand(1))) {
368202375Srdivacky      // Okay, we'll do this xform.  Make the shift of shift.
369202375Srdivacky      Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
370202375Srdivacky      // (shift2 (shift1 & 0x00FF), c2)
371202375Srdivacky      Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
372202375Srdivacky
373202375Srdivacky      // For logical shifts, the truncation has the effect of making the high
374202375Srdivacky      // part of the register be zeros.  Emulate this by inserting an AND to
375202375Srdivacky      // clear the top bits as needed.  This 'and' will usually be zapped by
376202375Srdivacky      // other xforms later if dead.
377202375Srdivacky      unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
378202375Srdivacky      unsigned DstSize = TI->getType()->getScalarSizeInBits();
379202375Srdivacky      APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
380202375Srdivacky
381202375Srdivacky      // The mask we constructed says what the trunc would do if occurring
382202375Srdivacky      // between the shifts.  We want to know the effect *after* the second
383202375Srdivacky      // shift.  We know that it is a logical shift by a constant, so adjust the
384202375Srdivacky      // mask as appropriate.
385202375Srdivacky      if (I.getOpcode() == Instruction::Shl)
386202375Srdivacky        MaskV <<= Op1->getZExtValue();
387202375Srdivacky      else {
388202375Srdivacky        assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
389202375Srdivacky        MaskV = MaskV.lshr(Op1->getZExtValue());
390202375Srdivacky      }
391202375Srdivacky
392202375Srdivacky      // shift1 & 0x00FF
393202375Srdivacky      Value *And = Builder->CreateAnd(NSh,
394202375Srdivacky                                      ConstantInt::get(I.getContext(), MaskV),
395202375Srdivacky                                      TI->getName());
396202375Srdivacky
397202375Srdivacky      // Return the value truncated to the interesting size.
398202375Srdivacky      return new TruncInst(And, I.getType());
399202375Srdivacky    }
400202375Srdivacky  }
401202375Srdivacky
402202375Srdivacky  if (Op0->hasOneUse()) {
403202375Srdivacky    if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
404202375Srdivacky      // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
405202375Srdivacky      Value *V1, *V2;
406202375Srdivacky      ConstantInt *CC;
407202375Srdivacky      switch (Op0BO->getOpcode()) {
408202375Srdivacky      default: break;
409202375Srdivacky      case Instruction::Add:
410202375Srdivacky      case Instruction::And:
411202375Srdivacky      case Instruction::Or:
412202375Srdivacky      case Instruction::Xor: {
413202375Srdivacky        // These operators commute.
414202375Srdivacky        // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
415202375Srdivacky        if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
416202375Srdivacky            match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
417202375Srdivacky                  m_Specific(Op1)))) {
418202375Srdivacky          Value *YS =         // (Y << C)
419202375Srdivacky            Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
420202375Srdivacky          // (X + (Y << C))
421202375Srdivacky          Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
422202375Srdivacky                                          Op0BO->getOperand(1)->getName());
423202375Srdivacky          uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
424202375Srdivacky          return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
425202375Srdivacky                     APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
426202375Srdivacky        }
427202375Srdivacky
428202375Srdivacky        // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
429202375Srdivacky        Value *Op0BOOp1 = Op0BO->getOperand(1);
430202375Srdivacky        if (isLeftShift && Op0BOOp1->hasOneUse() &&
431202375Srdivacky            match(Op0BOOp1,
432202375Srdivacky                  m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
433202375Srdivacky                        m_ConstantInt(CC))) &&
434202375Srdivacky            cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
435202375Srdivacky          Value *YS =   // (Y << C)
436202375Srdivacky            Builder->CreateShl(Op0BO->getOperand(0), Op1,
437202375Srdivacky                                         Op0BO->getName());
438202375Srdivacky          // X & (CC << C)
439202375Srdivacky          Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
440202375Srdivacky                                         V1->getName()+".mask");
441202375Srdivacky          return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
442202375Srdivacky        }
443202375Srdivacky      }
444202375Srdivacky
445202375Srdivacky      // FALL THROUGH.
446202375Srdivacky      case Instruction::Sub: {
447202375Srdivacky        // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
448202375Srdivacky        if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
449202375Srdivacky            match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
450202375Srdivacky                  m_Specific(Op1)))) {
451202375Srdivacky          Value *YS =  // (Y << C)
452202375Srdivacky            Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
453202375Srdivacky          // (X + (Y << C))
454202375Srdivacky          Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
455202375Srdivacky                                          Op0BO->getOperand(0)->getName());
456202375Srdivacky          uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
457202375Srdivacky          return BinaryOperator::CreateAnd(X, ConstantInt::get(I.getContext(),
458202375Srdivacky                     APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
459202375Srdivacky        }
460202375Srdivacky
461202375Srdivacky        // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
462202375Srdivacky        if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
463202375Srdivacky            match(Op0BO->getOperand(0),
464202375Srdivacky                  m_And(m_Shr(m_Value(V1), m_Value(V2)),
465202375Srdivacky                        m_ConstantInt(CC))) && V2 == Op1 &&
466202375Srdivacky            cast<BinaryOperator>(Op0BO->getOperand(0))
467202375Srdivacky                ->getOperand(0)->hasOneUse()) {
468202375Srdivacky          Value *YS = // (Y << C)
469202375Srdivacky            Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
470202375Srdivacky          // X & (CC << C)
471202375Srdivacky          Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
472202375Srdivacky                                         V1->getName()+".mask");
473202375Srdivacky
474202375Srdivacky          return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
475202375Srdivacky        }
476202375Srdivacky
477202375Srdivacky        break;
478202375Srdivacky      }
479202375Srdivacky      }
480202375Srdivacky
481202375Srdivacky
482202375Srdivacky      // If the operand is an bitwise operator with a constant RHS, and the
483202375Srdivacky      // shift is the only use, we can pull it out of the shift.
484202375Srdivacky      if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
485202375Srdivacky        bool isValid = true;     // Valid only for And, Or, Xor
486202375Srdivacky        bool highBitSet = false; // Transform if high bit of constant set?
487202375Srdivacky
488202375Srdivacky        switch (Op0BO->getOpcode()) {
489202375Srdivacky        default: isValid = false; break;   // Do not perform transform!
490202375Srdivacky        case Instruction::Add:
491202375Srdivacky          isValid = isLeftShift;
492202375Srdivacky          break;
493202375Srdivacky        case Instruction::Or:
494202375Srdivacky        case Instruction::Xor:
495202375Srdivacky          highBitSet = false;
496202375Srdivacky          break;
497202375Srdivacky        case Instruction::And:
498202375Srdivacky          highBitSet = true;
499202375Srdivacky          break;
500202375Srdivacky        }
501202375Srdivacky
502202375Srdivacky        // If this is a signed shift right, and the high bit is modified
503202375Srdivacky        // by the logical operation, do not perform the transformation.
504202375Srdivacky        // The highBitSet boolean indicates the value of the high bit of
505202375Srdivacky        // the constant which would cause it to be modified for this
506202375Srdivacky        // operation.
507202375Srdivacky        //
508202375Srdivacky        if (isValid && I.getOpcode() == Instruction::AShr)
509202375Srdivacky          isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
510202375Srdivacky
511202375Srdivacky        if (isValid) {
512202375Srdivacky          Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
513202375Srdivacky
514202375Srdivacky          Value *NewShift =
515202375Srdivacky            Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
516202375Srdivacky          NewShift->takeName(Op0BO);
517202375Srdivacky
518202375Srdivacky          return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
519202375Srdivacky                                        NewRHS);
520202375Srdivacky        }
521202375Srdivacky      }
522202375Srdivacky    }
523202375Srdivacky  }
524202375Srdivacky
525202375Srdivacky  // Find out if this is a shift of a shift by a constant.
526202375Srdivacky  BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
527202375Srdivacky  if (ShiftOp && !ShiftOp->isShift())
528202375Srdivacky    ShiftOp = 0;
529202375Srdivacky
530202375Srdivacky  if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
531202375Srdivacky    ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
532202375Srdivacky    uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
533202375Srdivacky    uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
534202375Srdivacky    assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
535202375Srdivacky    if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
536202375Srdivacky    Value *X = ShiftOp->getOperand(0);
537202375Srdivacky
538202375Srdivacky    uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
539202375Srdivacky
540226633Sdim    IntegerType *Ty = cast<IntegerType>(I.getType());
541202375Srdivacky
542202375Srdivacky    // Check for (X << c1) << c2  and  (X >> c1) >> c2
543202375Srdivacky    if (I.getOpcode() == ShiftOp->getOpcode()) {
544202375Srdivacky      // If this is oversized composite shift, then unsigned shifts get 0, ashr
545202375Srdivacky      // saturates.
546202375Srdivacky      if (AmtSum >= TypeBits) {
547202375Srdivacky        if (I.getOpcode() != Instruction::AShr)
548202375Srdivacky          return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
549202375Srdivacky        AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
550202375Srdivacky      }
551202375Srdivacky
552202375Srdivacky      return BinaryOperator::Create(I.getOpcode(), X,
553202375Srdivacky                                    ConstantInt::get(Ty, AmtSum));
554202375Srdivacky    }
555202375Srdivacky
556202375Srdivacky    if (ShiftAmt1 == ShiftAmt2) {
557202375Srdivacky      // If we have ((X >>? C) << C), turn this into X & (-1 << C).
558212904Sdim      if (I.getOpcode() == Instruction::Shl &&
559212904Sdim          ShiftOp->getOpcode() != Instruction::Shl) {
560202375Srdivacky        APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
561202375Srdivacky        return BinaryOperator::CreateAnd(X,
562202375Srdivacky                                         ConstantInt::get(I.getContext(),Mask));
563202375Srdivacky      }
564202375Srdivacky      // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
565212904Sdim      if (I.getOpcode() == Instruction::LShr &&
566212904Sdim          ShiftOp->getOpcode() == Instruction::Shl) {
567202375Srdivacky        APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
568202375Srdivacky        return BinaryOperator::CreateAnd(X,
569202375Srdivacky                                        ConstantInt::get(I.getContext(), Mask));
570202375Srdivacky      }
571202375Srdivacky    } else if (ShiftAmt1 < ShiftAmt2) {
572202375Srdivacky      uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
573202375Srdivacky
574202375Srdivacky      // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
575212904Sdim      if (I.getOpcode() == Instruction::Shl &&
576212904Sdim          ShiftOp->getOpcode() != Instruction::Shl) {
577202375Srdivacky        assert(ShiftOp->getOpcode() == Instruction::LShr ||
578202375Srdivacky               ShiftOp->getOpcode() == Instruction::AShr);
579202375Srdivacky        Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
580202375Srdivacky
581202375Srdivacky        APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
582202375Srdivacky        return BinaryOperator::CreateAnd(Shift,
583202375Srdivacky                                         ConstantInt::get(I.getContext(),Mask));
584202375Srdivacky      }
585202375Srdivacky
586202375Srdivacky      // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
587212904Sdim      if (I.getOpcode() == Instruction::LShr &&
588212904Sdim          ShiftOp->getOpcode() == Instruction::Shl) {
589202375Srdivacky        assert(ShiftOp->getOpcode() == Instruction::Shl);
590202375Srdivacky        Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
591202375Srdivacky
592202375Srdivacky        APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
593202375Srdivacky        return BinaryOperator::CreateAnd(Shift,
594202375Srdivacky                                         ConstantInt::get(I.getContext(),Mask));
595202375Srdivacky      }
596202375Srdivacky
597202375Srdivacky      // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
598202375Srdivacky    } else {
599202375Srdivacky      assert(ShiftAmt2 < ShiftAmt1);
600202375Srdivacky      uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
601202375Srdivacky
602202375Srdivacky      // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
603212904Sdim      if (I.getOpcode() == Instruction::Shl &&
604212904Sdim          ShiftOp->getOpcode() != Instruction::Shl) {
605202375Srdivacky        Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
606202375Srdivacky                                            ConstantInt::get(Ty, ShiftDiff));
607202375Srdivacky
608202375Srdivacky        APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
609202375Srdivacky        return BinaryOperator::CreateAnd(Shift,
610202375Srdivacky                                         ConstantInt::get(I.getContext(),Mask));
611202375Srdivacky      }
612202375Srdivacky
613202375Srdivacky      // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
614212904Sdim      if (I.getOpcode() == Instruction::LShr &&
615212904Sdim          ShiftOp->getOpcode() == Instruction::Shl) {
616202375Srdivacky        Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
617202375Srdivacky
618202375Srdivacky        APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
619202375Srdivacky        return BinaryOperator::CreateAnd(Shift,
620202375Srdivacky                                         ConstantInt::get(I.getContext(),Mask));
621202375Srdivacky      }
622202375Srdivacky
623202375Srdivacky      // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
624202375Srdivacky    }
625202375Srdivacky  }
626202375Srdivacky  return 0;
627202375Srdivacky}
628202375Srdivacky
629202375SrdivackyInstruction *InstCombiner::visitShl(BinaryOperator &I) {
630218893Sdim  if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
631218893Sdim                                 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
632218893Sdim                                 TD))
633218893Sdim    return ReplaceInstUsesWith(I, V);
634218893Sdim
635218893Sdim  if (Instruction *V = commonShiftTransforms(I))
636218893Sdim    return V;
637218893Sdim
638218893Sdim  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(I.getOperand(1))) {
639218893Sdim    unsigned ShAmt = Op1C->getZExtValue();
640218893Sdim
641218893Sdim    // If the shifted-out value is known-zero, then this is a NUW shift.
642218893Sdim    if (!I.hasNoUnsignedWrap() &&
643218893Sdim        MaskedValueIsZero(I.getOperand(0),
644218893Sdim                          APInt::getHighBitsSet(Op1C->getBitWidth(), ShAmt))) {
645218893Sdim          I.setHasNoUnsignedWrap();
646218893Sdim          return &I;
647218893Sdim        }
648218893Sdim
649218893Sdim    // If the shifted out value is all signbits, this is a NSW shift.
650218893Sdim    if (!I.hasNoSignedWrap() &&
651218893Sdim        ComputeNumSignBits(I.getOperand(0)) > ShAmt) {
652218893Sdim      I.setHasNoSignedWrap();
653218893Sdim      return &I;
654218893Sdim    }
655218893Sdim  }
656221345Sdim
657221345Sdim  // (C1 << A) << C2 -> (C1 << C2) << A
658221345Sdim  Constant *C1, *C2;
659221345Sdim  Value *A;
660221345Sdim  if (match(I.getOperand(0), m_OneUse(m_Shl(m_Constant(C1), m_Value(A)))) &&
661221345Sdim      match(I.getOperand(1), m_Constant(C2)))
662221345Sdim    return BinaryOperator::CreateShl(ConstantExpr::getShl(C1, C2), A);
663221345Sdim
664218893Sdim  return 0;
665202375Srdivacky}
666202375Srdivacky
667202375SrdivackyInstruction *InstCombiner::visitLShr(BinaryOperator &I) {
668218893Sdim  if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1),
669218893Sdim                                  I.isExact(), TD))
670218893Sdim    return ReplaceInstUsesWith(I, V);
671218893Sdim
672203954Srdivacky  if (Instruction *R = commonShiftTransforms(I))
673203954Srdivacky    return R;
674203954Srdivacky
675203954Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
676203954Srdivacky
677218893Sdim  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
678218893Sdim    unsigned ShAmt = Op1C->getZExtValue();
679218893Sdim
680203954Srdivacky    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
681203954Srdivacky      unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
682203954Srdivacky      // ctlz.i32(x)>>5  --> zext(x == 0)
683203954Srdivacky      // cttz.i32(x)>>5  --> zext(x == 0)
684203954Srdivacky      // ctpop.i32(x)>>5 --> zext(x == -1)
685203954Srdivacky      if ((II->getIntrinsicID() == Intrinsic::ctlz ||
686203954Srdivacky           II->getIntrinsicID() == Intrinsic::cttz ||
687203954Srdivacky           II->getIntrinsicID() == Intrinsic::ctpop) &&
688218893Sdim          isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt) {
689203954Srdivacky        bool isCtPop = II->getIntrinsicID() == Intrinsic::ctpop;
690203954Srdivacky        Constant *RHS = ConstantInt::getSigned(Op0->getType(), isCtPop ? -1:0);
691210299Sed        Value *Cmp = Builder->CreateICmpEQ(II->getArgOperand(0), RHS);
692203954Srdivacky        return new ZExtInst(Cmp, II->getType());
693203954Srdivacky      }
694203954Srdivacky    }
695203954Srdivacky
696218893Sdim    // If the shifted-out value is known-zero, then this is an exact shift.
697218893Sdim    if (!I.isExact() &&
698218893Sdim        MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
699218893Sdim      I.setIsExact();
700218893Sdim      return &I;
701218893Sdim    }
702218893Sdim  }
703218893Sdim
704203954Srdivacky  return 0;
705202375Srdivacky}
706202375Srdivacky
707202375SrdivackyInstruction *InstCombiner::visitAShr(BinaryOperator &I) {
708218893Sdim  if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1),
709218893Sdim                                  I.isExact(), TD))
710218893Sdim    return ReplaceInstUsesWith(I, V);
711218893Sdim
712202375Srdivacky  if (Instruction *R = commonShiftTransforms(I))
713202375Srdivacky    return R;
714202375Srdivacky
715202375Srdivacky  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
716218893Sdim
717202375Srdivacky  if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
718218893Sdim    unsigned ShAmt = Op1C->getZExtValue();
719218893Sdim
720202375Srdivacky    // If the input is a SHL by the same constant (ashr (shl X, C), C), then we
721202878Srdivacky    // have a sign-extend idiom.
722202375Srdivacky    Value *X;
723202878Srdivacky    if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1)))) {
724218893Sdim      // If the left shift is just shifting out partial signbits, delete the
725218893Sdim      // extension.
726218893Sdim      if (cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
727202878Srdivacky        return ReplaceInstUsesWith(I, X);
728202878Srdivacky
729202878Srdivacky      // If the input is an extension from the shifted amount value, e.g.
730202878Srdivacky      //   %x = zext i8 %A to i32
731202878Srdivacky      //   %y = shl i32 %x, 24
732202878Srdivacky      //   %z = ashr %y, 24
733202878Srdivacky      // then turn this into "z = sext i8 A to i32".
734202878Srdivacky      if (ZExtInst *ZI = dyn_cast<ZExtInst>(X)) {
735202878Srdivacky        uint32_t SrcBits = ZI->getOperand(0)->getType()->getScalarSizeInBits();
736202878Srdivacky        uint32_t DestBits = ZI->getType()->getScalarSizeInBits();
737202878Srdivacky        if (Op1C->getZExtValue() == DestBits-SrcBits)
738202878Srdivacky          return new SExtInst(ZI->getOperand(0), ZI->getType());
739202878Srdivacky      }
740202878Srdivacky    }
741218893Sdim
742218893Sdim    // If the shifted-out value is known-zero, then this is an exact shift.
743218893Sdim    if (!I.isExact() &&
744218893Sdim        MaskedValueIsZero(Op0,APInt::getLowBitsSet(Op1C->getBitWidth(),ShAmt))){
745218893Sdim      I.setIsExact();
746218893Sdim      return &I;
747218893Sdim    }
748202375Srdivacky  }
749202375Srdivacky
750202375Srdivacky  // See if we can turn a signed shr into an unsigned shr.
751202375Srdivacky  if (MaskedValueIsZero(Op0,
752202375Srdivacky                        APInt::getSignBit(I.getType()->getScalarSizeInBits())))
753202375Srdivacky    return BinaryOperator::CreateLShr(Op0, Op1);
754202375Srdivacky
755202375Srdivacky  // Arithmetic shifting an all-sign-bit value is a no-op.
756202375Srdivacky  unsigned NumSignBits = ComputeNumSignBits(Op0);
757202375Srdivacky  if (NumSignBits == Op0->getType()->getScalarSizeInBits())
758202375Srdivacky    return ReplaceInstUsesWith(I, Op0);
759202375Srdivacky
760202375Srdivacky  return 0;
761202375Srdivacky}
762202375Srdivacky
763