LLVM  10.0.0svn
InstCombineShifts.cpp
Go to the documentation of this file.
1 //===- InstCombineShifts.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitShl, visitLShr, and visitAShr functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20 
21 #define DEBUG_TYPE "instcombine"
22 
23 // Given pattern:
24 // (x shiftopcode Q) shiftopcode K
25 // we should rewrite it as
26 // x shiftopcode (Q+K) iff (Q+K) u< bitwidth(x)
27 // This is valid for any shift, but they must be identical.
28 static Instruction *
30  const SimplifyQuery &SQ,
31  InstCombiner::BuilderTy &Builder) {
32  // Look for a shift of some instruction, ignore zext of shift amount if any.
33  Instruction *Sh0Op0;
34  Value *ShAmt0;
35  if (!match(Sh0,
36  m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0)))))
37  return nullptr;
38 
39  // If there is a truncation between the two shifts, we must make note of it
40  // and look through it. The truncation imposes additional constraints on the
41  // transform.
42  Instruction *Sh1;
43  Value *Trunc = nullptr;
44  match(Sh0Op0,
46  m_Instruction(Sh1)));
47 
48  // Inner shift: (x shiftopcode ShAmt1)
49  // Like with other shift, ignore zext of shift amount if any.
50  Value *X, *ShAmt1;
51  if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1)))))
52  return nullptr;
53 
54  // We have two shift amounts from two different shifts. The types of those
55  // shift amounts may not match. If that's the case let's bailout now..
56  if (ShAmt0->getType() != ShAmt1->getType())
57  return nullptr;
58 
59  // The shift opcodes must be identical.
60  Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
61  if (ShiftOpcode != Sh1->getOpcode())
62  return nullptr;
63 
64  // Did we match a pattern with truncation ?
65  if (Trunc) {
66  // For right-shifts we can't do any such simplifications. Leave as-is.
67  if (ShiftOpcode != Instruction::BinaryOps::Shl)
68  return nullptr; // FIXME: still could perform constant-folding.
69  // If we saw truncation, we'll need to produce extra instruction,
70  // and for that one of the operands of the shift must be one-use.
71  if (!match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
72  return nullptr;
73  }
74 
75  // Can we fold (ShAmt0+ShAmt1) ?
76  auto *NewShAmt = dyn_cast_or_null<Constant>(
77  SimplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
78  SQ.getWithInstruction(Sh0)));
79  if (!NewShAmt)
80  return nullptr; // Did not simplify.
81  // Is the new shift amount smaller than the bit width of inner shift?
82  if (!match(NewShAmt, m_SpecificInt_ICMP(
83  ICmpInst::Predicate::ICMP_ULT,
84  APInt(NewShAmt->getType()->getScalarSizeInBits(),
85  X->getType()->getScalarSizeInBits()))))
86  return nullptr; // FIXME: could perform constant-folding.
87 
88  // All good, we can do this fold.
89  NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
90 
91  BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
92 
93  // The flags can only be propagated if there wasn't a trunc.
94  if (!Trunc) {
95  // If the pattern did not involve trunc, and both of the original shifts
96  // had the same flag set, preserve the flag.
97  if (ShiftOpcode == Instruction::BinaryOps::Shl) {
98  NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
99  Sh1->hasNoUnsignedWrap());
100  NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
101  Sh1->hasNoSignedWrap());
102  } else {
103  NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
104  }
105  }
106 
107  Instruction *Ret = NewShift;
108  if (Trunc) {
109  Builder.Insert(NewShift);
110  Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
111  }
112 
113  return Ret;
114 }
115 
116 // If we have some pattern that leaves only some low bits set, and then performs
117 // left-shift of those bits, if none of the bits that are left after the final
118 // shift are modified by the mask, we can omit the mask.
119 //
120 // There are many variants to this pattern:
121 // a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
122 // b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt
123 // c) (x & (-1 >> MaskShAmt)) << ShiftShAmt
124 // d) (x & ((-1 << MaskShAmt) >> MaskShAmt)) << ShiftShAmt
125 // e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
126 // f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
127 // All these patterns can be simplified to just:
128 // x << ShiftShAmt
129 // iff:
130 // a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
131 // c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
132 static Instruction *
134  const SimplifyQuery &SQ) {
135  assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
136  "The input must be 'shl'!");
137 
138  Value *Masked = OuterShift->getOperand(0);
139  Value *ShiftShAmt = OuterShift->getOperand(1);
140 
141  Value *MaskShAmt;
142 
143  // ((1 << MaskShAmt) - 1)
144  auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
145  // (~(-1 << maskNbits))
146  auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
147  // (-1 >> MaskShAmt)
148  auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt));
149  // ((-1 << MaskShAmt) >> MaskShAmt)
150  auto MaskD =
151  m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
152 
153  Value *X;
154  if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
155  // Can we simplify (MaskShAmt+ShiftShAmt) ?
156  Value *SumOfShAmts =
157  SimplifyAddInst(MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
158  SQ.getWithInstruction(OuterShift));
159  if (!SumOfShAmts)
160  return nullptr; // Did not simplify.
161  // Is the total shift amount *not* smaller than the bit width?
162  // FIXME: could also rely on ConstantRange.
163  unsigned BitWidth = X->getType()->getScalarSizeInBits();
164  if (!match(SumOfShAmts, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_UGE,
165  APInt(BitWidth, BitWidth))))
166  return nullptr;
167  // All good, we can do this fold.
168  } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
169  match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
170  m_Deferred(MaskShAmt)))) {
171  // Can we simplify (ShiftShAmt-MaskShAmt) ?
172  Value *ShAmtsDiff =
173  SimplifySubInst(ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
174  SQ.getWithInstruction(OuterShift));
175  if (!ShAmtsDiff)
176  return nullptr; // Did not simplify.
177  // Is the difference non-negative? (is ShiftShAmt u>= MaskShAmt ?)
178  // FIXME: could also rely on ConstantRange.
179  if (!match(ShAmtsDiff, m_NonNegative()))
180  return nullptr;
181  // All good, we can do this fold.
182  } else
183  return nullptr; // Don't know anything about this pattern.
184 
185  // No 'NUW'/'NSW'!
186  // We no longer know that we won't shift-out non-0 bits.
187  return BinaryOperator::Create(OuterShift->getOpcode(), X, ShiftShAmt);
188 }
189 
191  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
192  assert(Op0->getType() == Op1->getType());
193 
194  // See if we can fold away this shift.
195  if (SimplifyDemandedInstructionBits(I))
196  return &I;
197 
198  // Try to fold constant and into select arguments.
199  if (isa<Constant>(Op0))
200  if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
201  if (Instruction *R = FoldOpIntoSelect(I, SI))
202  return R;
203 
204  if (Constant *CUI = dyn_cast<Constant>(Op1))
205  if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
206  return Res;
207 
208  if (Instruction *NewShift =
210  return NewShift;
211 
212  // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
213  // iff A and C2 are both positive.
214  Value *A;
215  Constant *C;
216  if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
217  if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) &&
218  isKnownNonNegative(C, DL, 0, &AC, &I, &DT))
219  return BinaryOperator::Create(
220  I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A);
221 
222  // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
223  // Because shifts by negative values (which could occur if A were negative)
224  // are undefined.
225  const APInt *B;
226  if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
227  // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
228  // demand the sign bit (and many others) here??
229  Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1),
230  Op1->getName());
231  I.setOperand(1, Rem);
232  return &I;
233  }
234 
235  return nullptr;
236 }
237 
238 /// Return true if we can simplify two logical (either left or right) shifts
239 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
240 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
241  Instruction *InnerShift, InstCombiner &IC,
242  Instruction *CxtI) {
243  assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
244 
245  // We need constant scalar or constant splat shifts.
246  const APInt *InnerShiftConst;
247  if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
248  return false;
249 
250  // Two logical shifts in the same direction:
251  // shl (shl X, C1), C2 --> shl X, C1 + C2
252  // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
253  bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
254  if (IsInnerShl == IsOuterShl)
255  return true;
256 
257  // Equal shift amounts in opposite directions become bitwise 'and':
258  // lshr (shl X, C), C --> and X, C'
259  // shl (lshr X, C), C --> and X, C'
260  if (*InnerShiftConst == OuterShAmt)
261  return true;
262 
263  // If the 2nd shift is bigger than the 1st, we can fold:
264  // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
265  // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
266  // but it isn't profitable unless we know the and'd out bits are already zero.
267  // Also, check that the inner shift is valid (less than the type width) or
268  // we'll crash trying to produce the bit mask for the 'and'.
269  unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
270  if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
271  unsigned InnerShAmt = InnerShiftConst->getZExtValue();
272  unsigned MaskShift =
273  IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
274  APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
275  if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
276  return true;
277  }
278 
279  return false;
280 }
281 
282 /// See if we can compute the specified value, but shifted logically to the left
283 /// or right by some number of bits. This should return true if the expression
284 /// can be computed for the same cost as the current expression tree. This is
285 /// used to eliminate extraneous shifting from things like:
286 /// %C = shl i128 %A, 64
287 /// %D = shl i128 %B, 96
288 /// %E = or i128 %C, %D
289 /// %F = lshr i128 %E, 64
290 /// where the client will ask if E can be computed shifted right by 64-bits. If
291 /// this succeeds, getShiftedValue() will be called to produce the value.
292 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
293  InstCombiner &IC, Instruction *CxtI) {
294  // We can always evaluate constants shifted.
295  if (isa<Constant>(V))
296  return true;
297 
299  if (!I) return false;
300 
301  // If this is the opposite shift, we can directly reuse the input of the shift
302  // if the needed bits are already zero in the input. This allows us to reuse
303  // the value which means that we don't care if the shift has multiple uses.
304  // TODO: Handle opposite shift by exact value.
305  ConstantInt *CI = nullptr;
306  if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
307  (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
308  if (CI->getValue() == NumBits) {
309  // TODO: Check that the input bits are already zero with MaskedValueIsZero
310 #if 0
311  // If this is a truncate of a logical shr, we can truncate it to a smaller
312  // lshr iff we know that the bits we would otherwise be shifting in are
313  // already zeros.
314  uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
315  uint32_t BitWidth = Ty->getScalarSizeInBits();
316  if (MaskedValueIsZero(I->getOperand(0),
317  APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
318  CI->getLimitedValue(BitWidth) < BitWidth) {
319  return CanEvaluateTruncated(I->getOperand(0), Ty);
320  }
321 #endif
322 
323  }
324  }
325 
326  // We can't mutate something that has multiple uses: doing so would
327  // require duplicating the instruction in general, which isn't profitable.
328  if (!I->hasOneUse()) return false;
329 
330  switch (I->getOpcode()) {
331  default: return false;
332  case Instruction::And:
333  case Instruction::Or:
334  case Instruction::Xor:
335  // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
336  return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
337  canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
338 
339  case Instruction::Shl:
340  case Instruction::LShr:
341  return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
342 
343  case Instruction::Select: {
344  SelectInst *SI = cast<SelectInst>(I);
345  Value *TrueVal = SI->getTrueValue();
346  Value *FalseVal = SI->getFalseValue();
347  return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
348  canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
349  }
350  case Instruction::PHI: {
351  // We can change a phi if we can change all operands. Note that we never
352  // get into trouble with cyclic PHIs here because we only consider
353  // instructions with a single use.
354  PHINode *PN = cast<PHINode>(I);
355  for (Value *IncValue : PN->incoming_values())
356  if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
357  return false;
358  return true;
359  }
360  }
361 }
362 
363 /// Fold OuterShift (InnerShift X, C1), C2.
364 /// See canEvaluateShiftedShift() for the constraints on these instructions.
365 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
366  bool IsOuterShl,
367  InstCombiner::BuilderTy &Builder) {
368  bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
369  Type *ShType = InnerShift->getType();
370  unsigned TypeWidth = ShType->getScalarSizeInBits();
371 
372  // We only accept shifts-by-a-constant in canEvaluateShifted().
373  const APInt *C1;
374  match(InnerShift->getOperand(1), m_APInt(C1));
375  unsigned InnerShAmt = C1->getZExtValue();
376 
377  // Change the shift amount and clear the appropriate IR flags.
378  auto NewInnerShift = [&](unsigned ShAmt) {
379  InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
380  if (IsInnerShl) {
381  InnerShift->setHasNoUnsignedWrap(false);
382  InnerShift->setHasNoSignedWrap(false);
383  } else {
384  InnerShift->setIsExact(false);
385  }
386  return InnerShift;
387  };
388 
389  // Two logical shifts in the same direction:
390  // shl (shl X, C1), C2 --> shl X, C1 + C2
391  // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
392  if (IsInnerShl == IsOuterShl) {
393  // If this is an oversized composite shift, then unsigned shifts get 0.
394  if (InnerShAmt + OuterShAmt >= TypeWidth)
395  return Constant::getNullValue(ShType);
396 
397  return NewInnerShift(InnerShAmt + OuterShAmt);
398  }
399 
400  // Equal shift amounts in opposite directions become bitwise 'and':
401  // lshr (shl X, C), C --> and X, C'
402  // shl (lshr X, C), C --> and X, C'
403  if (InnerShAmt == OuterShAmt) {
404  APInt Mask = IsInnerShl
405  ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
406  : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
407  Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
408  ConstantInt::get(ShType, Mask));
409  if (auto *AndI = dyn_cast<Instruction>(And)) {
410  AndI->moveBefore(InnerShift);
411  AndI->takeName(InnerShift);
412  }
413  return And;
414  }
415 
416  assert(InnerShAmt > OuterShAmt &&
417  "Unexpected opposite direction logical shift pair");
418 
419  // In general, we would need an 'and' for this transform, but
420  // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
421  // lshr (shl X, C1), C2 --> shl X, C1 - C2
422  // shl (lshr X, C1), C2 --> lshr X, C1 - C2
423  return NewInnerShift(InnerShAmt - OuterShAmt);
424 }
425 
426 /// When canEvaluateShifted() returns true for an expression, this function
427 /// inserts the new computation that produces the shifted value.
428 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
429  InstCombiner &IC, const DataLayout &DL) {
430  // We can always evaluate constants shifted.
431  if (Constant *C = dyn_cast<Constant>(V)) {
432  if (isLeftShift)
433  V = IC.Builder.CreateShl(C, NumBits);
434  else
435  V = IC.Builder.CreateLShr(C, NumBits);
436  // If we got a constantexpr back, try to simplify it with TD info.
437  if (auto *C = dyn_cast<Constant>(V))
438  if (auto *FoldedC =
440  V = FoldedC;
441  return V;
442  }
443 
444  Instruction *I = cast<Instruction>(V);
445  IC.Worklist.Add(I);
446 
447  switch (I->getOpcode()) {
448  default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
449  case Instruction::And:
450  case Instruction::Or:
451  case Instruction::Xor:
452  // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
453  I->setOperand(
454  0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
455  I->setOperand(
456  1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
457  return I;
458 
459  case Instruction::Shl:
460  case Instruction::LShr:
461  return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
462  IC.Builder);
463 
464  case Instruction::Select:
465  I->setOperand(
466  1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
467  I->setOperand(
468  2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
469  return I;
470  case Instruction::PHI: {
471  // We can change a phi if we can change all operands. Note that we never
472  // get into trouble with cyclic PHIs here because we only consider
473  // instructions with a single use.
474  PHINode *PN = cast<PHINode>(I);
475  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
476  PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
477  isLeftShift, IC, DL));
478  return PN;
479  }
480  }
481 }
482 
483 // If this is a bitwise operator or add with a constant RHS we might be able
484 // to pull it through a shift.
486  BinaryOperator *BO) {
487  switch (BO->getOpcode()) {
488  default:
489  return false; // Do not perform transform!
490  case Instruction::Add:
491  return Shift.getOpcode() == Instruction::Shl;
492  case Instruction::Or:
493  case Instruction::Xor:
494  case Instruction::And:
495  return true;
496  }
497 }
498 
500  BinaryOperator &I) {
501  bool isLeftShift = I.getOpcode() == Instruction::Shl;
502 
503  const APInt *Op1C;
504  if (!match(Op1, m_APInt(Op1C)))
505  return nullptr;
506 
507  // See if we can propagate this shift into the input, this covers the trivial
508  // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
509  if (I.getOpcode() != Instruction::AShr &&
510  canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
511  LLVM_DEBUG(
512  dbgs() << "ICE: GetShiftedValue propagating shift through expression"
513  " to eliminate shift:\n IN: "
514  << *Op0 << "\n SH: " << I << "\n");
515 
516  return replaceInstUsesWith(
517  I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
518  }
519 
520  // See if we can simplify any instructions used by the instruction whose sole
521  // purpose is to compute bits we don't care about.
522  unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
523 
524  assert(!Op1C->uge(TypeBits) &&
525  "Shift over the type width should have been removed already");
526 
527  if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
528  return FoldedShift;
529 
530  // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
531  if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
532  Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
533  // If 'shift2' is an ashr, we would have to get the sign bit into a funny
534  // place. Don't try to do this transformation in this case. Also, we
535  // require that the input operand is a shift-by-constant so that we have
536  // confidence that the shifts will get folded together. We could do this
537  // xform in more cases, but it is unlikely to be profitable.
538  if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
539  isa<ConstantInt>(TrOp->getOperand(1))) {
540  // Okay, we'll do this xform. Make the shift of shift.
541  Constant *ShAmt =
542  ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
543  // (shift2 (shift1 & 0x00FF), c2)
544  Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName());
545 
546  // For logical shifts, the truncation has the effect of making the high
547  // part of the register be zeros. Emulate this by inserting an AND to
548  // clear the top bits as needed. This 'and' will usually be zapped by
549  // other xforms later if dead.
550  unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
551  unsigned DstSize = TI->getType()->getScalarSizeInBits();
552  APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
553 
554  // The mask we constructed says what the trunc would do if occurring
555  // between the shifts. We want to know the effect *after* the second
556  // shift. We know that it is a logical shift by a constant, so adjust the
557  // mask as appropriate.
558  if (I.getOpcode() == Instruction::Shl)
559  MaskV <<= Op1C->getZExtValue();
560  else {
561  assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
562  MaskV.lshrInPlace(Op1C->getZExtValue());
563  }
564 
565  // shift1 & 0x00FF
566  Value *And = Builder.CreateAnd(NSh,
567  ConstantInt::get(I.getContext(), MaskV),
568  TI->getName());
569 
570  // Return the value truncated to the interesting size.
571  return new TruncInst(And, I.getType());
572  }
573  }
574 
575  if (Op0->hasOneUse()) {
576  if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
577  // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
578  Value *V1, *V2;
579  ConstantInt *CC;
580  switch (Op0BO->getOpcode()) {
581  default: break;
582  case Instruction::Add:
583  case Instruction::And:
584  case Instruction::Or:
585  case Instruction::Xor: {
586  // These operators commute.
587  // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
588  if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
589  match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
590  m_Specific(Op1)))) {
591  Value *YS = // (Y << C)
592  Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
593  // (X + (Y << C))
594  Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1,
595  Op0BO->getOperand(1)->getName());
596  unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
597 
598  APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
600  if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
601  Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
602  return BinaryOperator::CreateAnd(X, Mask);
603  }
604 
605  // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
606  Value *Op0BOOp1 = Op0BO->getOperand(1);
607  if (isLeftShift && Op0BOOp1->hasOneUse() &&
608  match(Op0BOOp1,
609  m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
610  m_ConstantInt(CC)))) {
611  Value *YS = // (Y << C)
612  Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
613  // X & (CC << C)
614  Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
615  V1->getName()+".mask");
616  return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
617  }
619  }
620 
621  case Instruction::Sub: {
622  // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
623  if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
624  match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
625  m_Specific(Op1)))) {
626  Value *YS = // (Y << C)
627  Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
628  // (X + (Y << C))
629  Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS,
630  Op0BO->getOperand(0)->getName());
631  unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
632 
633  APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
635  if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
636  Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
637  return BinaryOperator::CreateAnd(X, Mask);
638  }
639 
640  // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
641  if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
642  match(Op0BO->getOperand(0),
643  m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
644  m_ConstantInt(CC))) && V2 == Op1) {
645  Value *YS = // (Y << C)
646  Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
647  // X & (CC << C)
648  Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
649  V1->getName()+".mask");
650 
651  return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
652  }
653 
654  break;
655  }
656  }
657 
658 
659  // If the operand is a bitwise operator with a constant RHS, and the
660  // shift is the only use, we can pull it out of the shift.
661  const APInt *Op0C;
662  if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
663  if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
664  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
665  cast<Constant>(Op0BO->getOperand(1)), Op1);
666 
667  Value *NewShift =
668  Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
669  NewShift->takeName(Op0BO);
670 
671  return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
672  NewRHS);
673  }
674  }
675 
676  // If the operand is a subtract with a constant LHS, and the shift
677  // is the only use, we can pull it out of the shift.
678  // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2))
679  if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub &&
680  match(Op0BO->getOperand(0), m_APInt(Op0C))) {
681  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
682  cast<Constant>(Op0BO->getOperand(0)), Op1);
683 
684  Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1);
685  NewShift->takeName(Op0BO);
686 
687  return BinaryOperator::CreateSub(NewRHS, NewShift);
688  }
689  }
690 
691  // If we have a select that conditionally executes some binary operator,
692  // see if we can pull it the select and operator through the shift.
693  //
694  // For example, turning:
695  // shl (select C, (add X, C1), X), C2
696  // Into:
697  // Y = shl X, C2
698  // select C, (add Y, C1 << C2), Y
699  Value *Cond;
700  BinaryOperator *TBO;
701  Value *FalseVal;
702  if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
703  m_Value(FalseVal)))) {
704  const APInt *C;
705  if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
706  match(TBO->getOperand(1), m_APInt(C)) &&
708  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
709  cast<Constant>(TBO->getOperand(1)), Op1);
710 
711  Value *NewShift =
712  Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1);
713  Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift,
714  NewRHS);
715  return SelectInst::Create(Cond, NewOp, NewShift);
716  }
717  }
718 
719  BinaryOperator *FBO;
720  Value *TrueVal;
721  if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
722  m_OneUse(m_BinOp(FBO))))) {
723  const APInt *C;
724  if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
725  match(FBO->getOperand(1), m_APInt(C)) &&
727  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
728  cast<Constant>(FBO->getOperand(1)), Op1);
729 
730  Value *NewShift =
731  Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1);
732  Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift,
733  NewRHS);
734  return SelectInst::Create(Cond, NewShift, NewOp);
735  }
736  }
737  }
738 
739  return nullptr;
740 }
741 
743  if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
745  SQ.getWithInstruction(&I)))
746  return replaceInstUsesWith(I, V);
747 
748  if (Instruction *X = foldVectorBinop(I))
749  return X;
750 
751  if (Instruction *V = commonShiftTransforms(I))
752  return V;
753 
755  return V;
756 
757  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
758  Type *Ty = I.getType();
759  unsigned BitWidth = Ty->getScalarSizeInBits();
760 
761  const APInt *ShAmtAPInt;
762  if (match(Op1, m_APInt(ShAmtAPInt))) {
763  unsigned ShAmt = ShAmtAPInt->getZExtValue();
764  unsigned BitWidth = Ty->getScalarSizeInBits();
765 
766  // shl (zext X), ShAmt --> zext (shl X, ShAmt)
767  // This is only valid if X would have zeros shifted out.
768  Value *X;
769  if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
770  unsigned SrcWidth = X->getType()->getScalarSizeInBits();
771  if (ShAmt < SrcWidth &&
772  MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
773  return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty);
774  }
775 
776  // (X >> C) << C --> X & (-1 << C)
777  if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
778  APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
779  return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
780  }
781 
782  // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine)
783  // needs a few fixes for the rotate pattern recognition first.
784  const APInt *ShOp1;
785  if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) {
786  unsigned ShrAmt = ShOp1->getZExtValue();
787  if (ShrAmt < ShAmt) {
788  // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
789  Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt);
790  auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
791  NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
792  NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
793  return NewShl;
794  }
795  if (ShrAmt > ShAmt) {
796  // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2)
797  Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt);
798  auto *NewShr = BinaryOperator::Create(
799  cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
800  NewShr->setIsExact(true);
801  return NewShr;
802  }
803  }
804 
805  if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) {
806  unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
807  // Oversized shifts are simplified to zero in InstSimplify.
808  if (AmtSum < BitWidth)
809  // (X << C1) << C2 --> X << (C1 + C2)
810  return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
811  }
812 
813  // If the shifted-out value is known-zero, then this is a NUW shift.
814  if (!I.hasNoUnsignedWrap() &&
815  MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
817  return &I;
818  }
819 
820  // If the shifted-out value is all signbits, then this is a NSW shift.
821  if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
822  I.setHasNoSignedWrap();
823  return &I;
824  }
825  }
826 
827  // Transform (x >> y) << y to x & (-1 << y)
828  // Valid for any type of right-shift.
829  Value *X;
830  if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
831  Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
832  Value *Mask = Builder.CreateShl(AllOnes, Op1);
833  return BinaryOperator::CreateAnd(Mask, X);
834  }
835 
836  Constant *C1;
837  if (match(Op1, m_Constant(C1))) {
838  Constant *C2;
839  Value *X;
840  // (C2 << X) << C1 --> (C2 << C1) << X
841  if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X)))))
842  return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X);
843 
844  // (X * C2) << C1 --> X * (C2 << C1)
845  if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
847  }
848 
849  // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
850  if (match(Op0, m_One()) &&
851  match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
852  return BinaryOperator::CreateLShr(
853  ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
854 
855  return nullptr;
856 }
857 
859  if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
860  SQ.getWithInstruction(&I)))
861  return replaceInstUsesWith(I, V);
862 
863  if (Instruction *X = foldVectorBinop(I))
864  return X;
865 
866  if (Instruction *R = commonShiftTransforms(I))
867  return R;
868 
869  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
870  Type *Ty = I.getType();
871  const APInt *ShAmtAPInt;
872  if (match(Op1, m_APInt(ShAmtAPInt))) {
873  unsigned ShAmt = ShAmtAPInt->getZExtValue();
874  unsigned BitWidth = Ty->getScalarSizeInBits();
875  auto *II = dyn_cast<IntrinsicInst>(Op0);
876  if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
877  (II->getIntrinsicID() == Intrinsic::ctlz ||
878  II->getIntrinsicID() == Intrinsic::cttz ||
879  II->getIntrinsicID() == Intrinsic::ctpop)) {
880  // ctlz.i32(x)>>5 --> zext(x == 0)
881  // cttz.i32(x)>>5 --> zext(x == 0)
882  // ctpop.i32(x)>>5 --> zext(x == -1)
883  bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
884  Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
885  Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
886  return new ZExtInst(Cmp, Ty);
887  }
888 
889  Value *X;
890  const APInt *ShOp1;
891  if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) {
892  if (ShOp1->ult(ShAmt)) {
893  unsigned ShlAmt = ShOp1->getZExtValue();
894  Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
895  if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
896  // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
897  auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
898  NewLShr->setIsExact(I.isExact());
899  return NewLShr;
900  }
901  // (X << C1) >>u C2 --> (X >>u (C2 - C1)) & (-1 >> C2)
902  Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
903  APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
904  return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
905  }
906  if (ShOp1->ugt(ShAmt)) {
907  unsigned ShlAmt = ShOp1->getZExtValue();
908  Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
909  if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
910  // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2)
911  auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
912  NewShl->setHasNoUnsignedWrap(true);
913  return NewShl;
914  }
915  // (X << C1) >>u C2 --> X << (C1 - C2) & (-1 >> C2)
916  Value *NewShl = Builder.CreateShl(X, ShiftDiff);
917  APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
918  return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
919  }
920  assert(*ShOp1 == ShAmt);
921  // (X << C) >>u C --> X & (-1 >>u C)
922  APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
923  return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
924  }
925 
926  if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
927  (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
928  assert(ShAmt < X->getType()->getScalarSizeInBits() &&
929  "Big shift not simplified to zero?");
930  // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
931  Value *NewLShr = Builder.CreateLShr(X, ShAmt);
932  return new ZExtInst(NewLShr, Ty);
933  }
934 
935  if (match(Op0, m_SExt(m_Value(X))) &&
936  (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
937  // Are we moving the sign bit to the low bit and widening with high zeros?
938  unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
939  if (ShAmt == BitWidth - 1) {
940  // lshr (sext i1 X to iN), N-1 --> zext X to iN
941  if (SrcTyBitWidth == 1)
942  return new ZExtInst(X, Ty);
943 
944  // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
945  if (Op0->hasOneUse()) {
946  Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
947  return new ZExtInst(NewLShr, Ty);
948  }
949  }
950 
951  // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
952  if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) {
953  // The new shift amount can't be more than the narrow source type.
954  unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1);
955  Value *AShr = Builder.CreateAShr(X, NewShAmt);
956  return new ZExtInst(AShr, Ty);
957  }
958  }
959 
960  if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) {
961  unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
962  // Oversized shifts are simplified to zero in InstSimplify.
963  if (AmtSum < BitWidth)
964  // (X >>u C1) >>u C2 --> X >>u (C1 + C2)
965  return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
966  }
967 
968  // If the shifted-out value is known-zero, then this is an exact shift.
969  if (!I.isExact() &&
970  MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
971  I.setIsExact();
972  return &I;
973  }
974  }
975 
976  // Transform (x << y) >> y to x & (-1 >> y)
977  Value *X;
978  if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
979  Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
980  Value *Mask = Builder.CreateLShr(AllOnes, Op1);
981  return BinaryOperator::CreateAnd(Mask, X);
982  }
983 
984  return nullptr;
985 }
986 
988  if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
989  SQ.getWithInstruction(&I)))
990  return replaceInstUsesWith(I, V);
991 
992  if (Instruction *X = foldVectorBinop(I))
993  return X;
994 
995  if (Instruction *R = commonShiftTransforms(I))
996  return R;
997 
998  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
999  Type *Ty = I.getType();
1000  unsigned BitWidth = Ty->getScalarSizeInBits();
1001  const APInt *ShAmtAPInt;
1002  if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1003  unsigned ShAmt = ShAmtAPInt->getZExtValue();
1004 
1005  // If the shift amount equals the difference in width of the destination
1006  // and source scalar types:
1007  // ashr (shl (zext X), C), C --> sext X
1008  Value *X;
1009  if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1010  ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1011  return new SExtInst(X, Ty);
1012 
1013  // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1014  // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1015  const APInt *ShOp1;
1016  if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1017  ShOp1->ult(BitWidth)) {
1018  unsigned ShlAmt = ShOp1->getZExtValue();
1019  if (ShlAmt < ShAmt) {
1020  // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1021  Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1022  auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1023  NewAShr->setIsExact(I.isExact());
1024  return NewAShr;
1025  }
1026  if (ShlAmt > ShAmt) {
1027  // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1028  Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1029  auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1030  NewShl->setHasNoSignedWrap(true);
1031  return NewShl;
1032  }
1033  }
1034 
1035  if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1036  ShOp1->ult(BitWidth)) {
1037  unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1038  // Oversized arithmetic shifts replicate the sign bit.
1039  AmtSum = std::min(AmtSum, BitWidth - 1);
1040  // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1041  return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1042  }
1043 
1044  if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1045  (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1046  // ashr (sext X), C --> sext (ashr X, C')
1047  Type *SrcTy = X->getType();
1048  ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1049  Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1050  return new SExtInst(NewSh, Ty);
1051  }
1052 
1053  // If the shifted-out value is known-zero, then this is an exact shift.
1054  if (!I.isExact() &&
1055  MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1056  I.setIsExact();
1057  return &I;
1058  }
1059  }
1060 
1061  // See if we can turn a signed shr into an unsigned shr.
1062  if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1063  return BinaryOperator::CreateLShr(Op0, Op1);
1064 
1065  return nullptr;
1066 }
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing &#39;pred&#39; (eg/ne/...) to Threshold.
Definition: PatternMatch.h:489
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Definition: PatternMatch.h:831
uint64_t CallInst * C
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of nonnegative values.
Definition: PatternMatch.h:365
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:70
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1569
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:728
static Instruction * dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift, const SimplifyQuery &SQ)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
SimplifyQuery getWithInstruction(Instruction *I) const
BinaryOps getOpcode() const
Definition: InstrTypes.h:402
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
Definition: PatternMatch.h:819
This class represents zero extension of integer types.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
Definition: PatternMatch.h:783
static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift, InstCombiner &IC, Instruction *CxtI)
See if we can compute the specified value, but shifted logically to the left or right by some number ...
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
Definition: APInt.h:647
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:89
const Value * getTrueValue() const
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
Definition: PatternMatch.h:861
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:733
void Add(Instruction *I)
Add - Add the specified instruction to the worklist if it isn&#39;t already in it.
static Instruction * reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, const SimplifyQuery &SQ, InstCombiner::BuilderTy &Builder)
This class represents a sign extension of integer types.
Value * SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, const SimplifyQuery &Q)
Given operands for a Shl, fold the result or return null.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:289
Value * SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, const SimplifyQuery &Q)
Given operands for a LShr, fold the result or return null.
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, OpTy > m_ZExtOrSelf(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
Definition: PatternMatch.h:843
This class represents the LLVM &#39;select&#39; instruction.
Instruction * commonShiftTransforms(BinaryOperator &I)
Exact_match< T > m_Exact(const T &SubPattern)
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:196
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
The core instruction combiner logic.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if &#39;V & Mask&#39; is known to be zero.
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:977
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Definition: PatternMatch.h:716
static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift, BinaryOperator *BO)
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1696
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
Definition: PatternMatch.h:137
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:81
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:137
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the give value is known to be non-negative.
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:407
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
This class represents a truncation of integer types.
Value * getOperand(unsigned i) const
Definition: User.h:169
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
Definition: APInt.h:635
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:61
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
Definition: PatternMatch.h:855
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
Definition: PatternMatch.h:189
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:428
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1184
This is an important base class in LLVM.
Definition: Constant.h:41
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
static unsigned getScalarSizeInBits(Type *Ty)
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:331
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:576
Value * SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
Definition: PatternMatch.h:849
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:73
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:343
Instruction * visitLShr(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool isExact() const
Determine whether the exact flag is set.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
deferredval_ty< Value > m_Deferred(Value *const &V)
A commutative-friendly version of m_Specific().
Definition: PatternMatch.h:589
TargetLibraryInfo & getTargetLibraryInfo() const
InstCombineWorklist & Worklist
A worklist of the instructions that need to be simplified.
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:50
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:554
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1150
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition: Constants.h:250
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl, Instruction *InnerShift, InstCombiner &IC, Instruction *CxtI)
Return true if we can simplify two logical (either left or right) shifts that have constant shift amo...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:653
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.cpp:667
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1292
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:538
Class to represent vector types.
Definition: DerivedTypes.h:427
Class for arbitrary precision integers.
Definition: APInt.h:69
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1207
const Value * getFalseValue() const
static Constant * getZExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:1600
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass&#39;s ...
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Definition: APInt.h:1254
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
Definition: APInt.h:481
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
Value * SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, const SimplifyQuery &Q)
Given operands for a AShr, fold the result or return nulll.
#define I(x, y, z)
Definition: MD5.cpp:58
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
Definition: PatternMatch.h:918
static Value * getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift, InstCombiner &IC, const DataLayout &DL)
When canEvaluateShifted() returns true for an expression, this function inserts the new computation t...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2321
bool isLogicalShift() const
Return true if this is a logical shift left or a logical shift right.
Definition: Instruction.h:165
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1268
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:830
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static Value * foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt, bool IsOuterShl, InstCombiner::BuilderTy &Builder)
Fold OuterShift (InnerShift X, C1), C2.
LLVM Value Representation.
Definition: Value.h:73
This file provides internal interfaces used to implement the InstCombine.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:377
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:265
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1228
Value * SimplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW, const SimplifyQuery &Q)
Given operands for a Sub, fold the result or return null.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:143
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:432
Instruction * visitAShr(BinaryOperator &I)
specific_intval m_SpecificInt(uint64_t V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:653
void setIncomingValue(unsigned i, Value *V)
Instruction * visitShl(BinaryOperator &I)
static BinaryOperator * CreateMul(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
#define LLVM_DEBUG(X)
Definition: Debug.h:122
op_range incoming_values()
Instruction * FoldShiftByConstant(Value *Op0, Constant *Op1, BinaryOperator &I)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:553
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:43
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
Definition: Constants.cpp:1837