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  InstCombiner::BuilderTy &Builder) {
136  assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
137  "The input must be 'shl'!");
138 
139  Value *Masked = OuterShift->getOperand(0);
140  Value *ShiftShAmt = OuterShift->getOperand(1);
141 
142  Value *MaskShAmt;
143 
144  // ((1 << MaskShAmt) - 1)
145  auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
146  // (~(-1 << maskNbits))
147  auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
148  // (-1 >> MaskShAmt)
149  auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt));
150  // ((-1 << MaskShAmt) >> MaskShAmt)
151  auto MaskD =
152  m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
153 
154  Value *X;
155  if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
156  // Can we simplify (MaskShAmt+ShiftShAmt) ?
157  auto *SumOfShAmts = dyn_cast_or_null<Constant>(
158  SimplifyAddInst(MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
159  SQ.getWithInstruction(OuterShift)));
160  if (!SumOfShAmts)
161  return nullptr; // Did not simplify.
162  Type *Ty = X->getType();
163  unsigned BitWidth = Ty->getScalarSizeInBits();
164  // In this pattern SumOfShAmts correlates with the number of low bits that
165  // shall remain in the root value (OuterShift). If SumOfShAmts is less than
166  // bitwidth, we'll need to also produce a mask to keep SumOfShAmts low bits.
167  // So, does *any* channel need a mask?
168  if (!match(SumOfShAmts, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_UGE,
169  APInt(BitWidth, BitWidth))))
170  return nullptr; // FIXME.
171  // All good, we can do this fold.
172  } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
173  match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
174  m_Deferred(MaskShAmt)))) {
175  // Can we simplify (ShiftShAmt-MaskShAmt) ?
176  auto *ShAmtsDiff = dyn_cast_or_null<Constant>(
177  SimplifySubInst(ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
178  SQ.getWithInstruction(OuterShift)));
179  if (!ShAmtsDiff)
180  return nullptr; // Did not simplify.
181  // In this pattern ShAmtsDiff correlates with the number of high bits that
182  // shall be unset in the root value (OuterShift). If ShAmtsDiff is negative,
183  // we'll need to also produce a mask to unset ShAmtsDiff high bits.
184  // So, does *any* channel need a mask? (is ShiftShAmt u>= MaskShAmt ?)
185  if (!match(ShAmtsDiff, m_NonNegative()))
186  return nullptr; // FIXME.
187  // All good, we can do this fold.
188  } else
189  return nullptr; // Don't know anything about this pattern.
190 
191  // No 'NUW'/'NSW'!
192  // We no longer know that we won't shift-out non-0 bits.
193  return BinaryOperator::Create(OuterShift->getOpcode(), X, ShiftShAmt);
194 }
195 
197  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
198  assert(Op0->getType() == Op1->getType());
199 
200  // See if we can fold away this shift.
201  if (SimplifyDemandedInstructionBits(I))
202  return &I;
203 
204  // Try to fold constant and into select arguments.
205  if (isa<Constant>(Op0))
206  if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
207  if (Instruction *R = FoldOpIntoSelect(I, SI))
208  return R;
209 
210  if (Constant *CUI = dyn_cast<Constant>(Op1))
211  if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
212  return Res;
213 
214  if (Instruction *NewShift =
216  return NewShift;
217 
218  // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
219  // iff A and C2 are both positive.
220  Value *A;
221  Constant *C;
222  if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
223  if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) &&
224  isKnownNonNegative(C, DL, 0, &AC, &I, &DT))
225  return BinaryOperator::Create(
226  I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A);
227 
228  // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
229  // Because shifts by negative values (which could occur if A were negative)
230  // are undefined.
231  const APInt *B;
232  if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
233  // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
234  // demand the sign bit (and many others) here??
235  Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1),
236  Op1->getName());
237  I.setOperand(1, Rem);
238  return &I;
239  }
240 
241  return nullptr;
242 }
243 
244 /// Return true if we can simplify two logical (either left or right) shifts
245 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
246 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
247  Instruction *InnerShift, InstCombiner &IC,
248  Instruction *CxtI) {
249  assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
250 
251  // We need constant scalar or constant splat shifts.
252  const APInt *InnerShiftConst;
253  if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
254  return false;
255 
256  // Two logical shifts in the same direction:
257  // shl (shl X, C1), C2 --> shl X, C1 + C2
258  // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
259  bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
260  if (IsInnerShl == IsOuterShl)
261  return true;
262 
263  // Equal shift amounts in opposite directions become bitwise 'and':
264  // lshr (shl X, C), C --> and X, C'
265  // shl (lshr X, C), C --> and X, C'
266  if (*InnerShiftConst == OuterShAmt)
267  return true;
268 
269  // If the 2nd shift is bigger than the 1st, we can fold:
270  // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
271  // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
272  // but it isn't profitable unless we know the and'd out bits are already zero.
273  // Also, check that the inner shift is valid (less than the type width) or
274  // we'll crash trying to produce the bit mask for the 'and'.
275  unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
276  if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
277  unsigned InnerShAmt = InnerShiftConst->getZExtValue();
278  unsigned MaskShift =
279  IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
280  APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
281  if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
282  return true;
283  }
284 
285  return false;
286 }
287 
288 /// See if we can compute the specified value, but shifted logically to the left
289 /// or right by some number of bits. This should return true if the expression
290 /// can be computed for the same cost as the current expression tree. This is
291 /// used to eliminate extraneous shifting from things like:
292 /// %C = shl i128 %A, 64
293 /// %D = shl i128 %B, 96
294 /// %E = or i128 %C, %D
295 /// %F = lshr i128 %E, 64
296 /// where the client will ask if E can be computed shifted right by 64-bits. If
297 /// this succeeds, getShiftedValue() will be called to produce the value.
298 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
299  InstCombiner &IC, Instruction *CxtI) {
300  // We can always evaluate constants shifted.
301  if (isa<Constant>(V))
302  return true;
303 
305  if (!I) return false;
306 
307  // If this is the opposite shift, we can directly reuse the input of the shift
308  // if the needed bits are already zero in the input. This allows us to reuse
309  // the value which means that we don't care if the shift has multiple uses.
310  // TODO: Handle opposite shift by exact value.
311  ConstantInt *CI = nullptr;
312  if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
313  (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
314  if (CI->getValue() == NumBits) {
315  // TODO: Check that the input bits are already zero with MaskedValueIsZero
316 #if 0
317  // If this is a truncate of a logical shr, we can truncate it to a smaller
318  // lshr iff we know that the bits we would otherwise be shifting in are
319  // already zeros.
320  uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
321  uint32_t BitWidth = Ty->getScalarSizeInBits();
322  if (MaskedValueIsZero(I->getOperand(0),
323  APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
324  CI->getLimitedValue(BitWidth) < BitWidth) {
325  return CanEvaluateTruncated(I->getOperand(0), Ty);
326  }
327 #endif
328 
329  }
330  }
331 
332  // We can't mutate something that has multiple uses: doing so would
333  // require duplicating the instruction in general, which isn't profitable.
334  if (!I->hasOneUse()) return false;
335 
336  switch (I->getOpcode()) {
337  default: return false;
338  case Instruction::And:
339  case Instruction::Or:
340  case Instruction::Xor:
341  // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
342  return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
343  canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
344 
345  case Instruction::Shl:
346  case Instruction::LShr:
347  return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
348 
349  case Instruction::Select: {
350  SelectInst *SI = cast<SelectInst>(I);
351  Value *TrueVal = SI->getTrueValue();
352  Value *FalseVal = SI->getFalseValue();
353  return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
354  canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
355  }
356  case Instruction::PHI: {
357  // We can change a phi if we can change all operands. Note that we never
358  // get into trouble with cyclic PHIs here because we only consider
359  // instructions with a single use.
360  PHINode *PN = cast<PHINode>(I);
361  for (Value *IncValue : PN->incoming_values())
362  if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
363  return false;
364  return true;
365  }
366  }
367 }
368 
369 /// Fold OuterShift (InnerShift X, C1), C2.
370 /// See canEvaluateShiftedShift() for the constraints on these instructions.
371 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
372  bool IsOuterShl,
373  InstCombiner::BuilderTy &Builder) {
374  bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
375  Type *ShType = InnerShift->getType();
376  unsigned TypeWidth = ShType->getScalarSizeInBits();
377 
378  // We only accept shifts-by-a-constant in canEvaluateShifted().
379  const APInt *C1;
380  match(InnerShift->getOperand(1), m_APInt(C1));
381  unsigned InnerShAmt = C1->getZExtValue();
382 
383  // Change the shift amount and clear the appropriate IR flags.
384  auto NewInnerShift = [&](unsigned ShAmt) {
385  InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
386  if (IsInnerShl) {
387  InnerShift->setHasNoUnsignedWrap(false);
388  InnerShift->setHasNoSignedWrap(false);
389  } else {
390  InnerShift->setIsExact(false);
391  }
392  return InnerShift;
393  };
394 
395  // Two logical shifts in the same direction:
396  // shl (shl X, C1), C2 --> shl X, C1 + C2
397  // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
398  if (IsInnerShl == IsOuterShl) {
399  // If this is an oversized composite shift, then unsigned shifts get 0.
400  if (InnerShAmt + OuterShAmt >= TypeWidth)
401  return Constant::getNullValue(ShType);
402 
403  return NewInnerShift(InnerShAmt + OuterShAmt);
404  }
405 
406  // Equal shift amounts in opposite directions become bitwise 'and':
407  // lshr (shl X, C), C --> and X, C'
408  // shl (lshr X, C), C --> and X, C'
409  if (InnerShAmt == OuterShAmt) {
410  APInt Mask = IsInnerShl
411  ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
412  : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
413  Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
414  ConstantInt::get(ShType, Mask));
415  if (auto *AndI = dyn_cast<Instruction>(And)) {
416  AndI->moveBefore(InnerShift);
417  AndI->takeName(InnerShift);
418  }
419  return And;
420  }
421 
422  assert(InnerShAmt > OuterShAmt &&
423  "Unexpected opposite direction logical shift pair");
424 
425  // In general, we would need an 'and' for this transform, but
426  // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
427  // lshr (shl X, C1), C2 --> shl X, C1 - C2
428  // shl (lshr X, C1), C2 --> lshr X, C1 - C2
429  return NewInnerShift(InnerShAmt - OuterShAmt);
430 }
431 
432 /// When canEvaluateShifted() returns true for an expression, this function
433 /// inserts the new computation that produces the shifted value.
434 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
435  InstCombiner &IC, const DataLayout &DL) {
436  // We can always evaluate constants shifted.
437  if (Constant *C = dyn_cast<Constant>(V)) {
438  if (isLeftShift)
439  V = IC.Builder.CreateShl(C, NumBits);
440  else
441  V = IC.Builder.CreateLShr(C, NumBits);
442  // If we got a constantexpr back, try to simplify it with TD info.
443  if (auto *C = dyn_cast<Constant>(V))
444  if (auto *FoldedC =
446  V = FoldedC;
447  return V;
448  }
449 
450  Instruction *I = cast<Instruction>(V);
451  IC.Worklist.Add(I);
452 
453  switch (I->getOpcode()) {
454  default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
455  case Instruction::And:
456  case Instruction::Or:
457  case Instruction::Xor:
458  // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
459  I->setOperand(
460  0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
461  I->setOperand(
462  1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
463  return I;
464 
465  case Instruction::Shl:
466  case Instruction::LShr:
467  return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
468  IC.Builder);
469 
470  case Instruction::Select:
471  I->setOperand(
472  1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
473  I->setOperand(
474  2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
475  return I;
476  case Instruction::PHI: {
477  // We can change a phi if we can change all operands. Note that we never
478  // get into trouble with cyclic PHIs here because we only consider
479  // instructions with a single use.
480  PHINode *PN = cast<PHINode>(I);
481  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
482  PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
483  isLeftShift, IC, DL));
484  return PN;
485  }
486  }
487 }
488 
489 // If this is a bitwise operator or add with a constant RHS we might be able
490 // to pull it through a shift.
492  BinaryOperator *BO) {
493  switch (BO->getOpcode()) {
494  default:
495  return false; // Do not perform transform!
496  case Instruction::Add:
497  return Shift.getOpcode() == Instruction::Shl;
498  case Instruction::Or:
499  case Instruction::Xor:
500  case Instruction::And:
501  return true;
502  }
503 }
504 
506  BinaryOperator &I) {
507  bool isLeftShift = I.getOpcode() == Instruction::Shl;
508 
509  const APInt *Op1C;
510  if (!match(Op1, m_APInt(Op1C)))
511  return nullptr;
512 
513  // See if we can propagate this shift into the input, this covers the trivial
514  // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
515  if (I.getOpcode() != Instruction::AShr &&
516  canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
517  LLVM_DEBUG(
518  dbgs() << "ICE: GetShiftedValue propagating shift through expression"
519  " to eliminate shift:\n IN: "
520  << *Op0 << "\n SH: " << I << "\n");
521 
522  return replaceInstUsesWith(
523  I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
524  }
525 
526  // See if we can simplify any instructions used by the instruction whose sole
527  // purpose is to compute bits we don't care about.
528  unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
529 
530  assert(!Op1C->uge(TypeBits) &&
531  "Shift over the type width should have been removed already");
532 
533  if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
534  return FoldedShift;
535 
536  // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
537  if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
538  Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
539  // If 'shift2' is an ashr, we would have to get the sign bit into a funny
540  // place. Don't try to do this transformation in this case. Also, we
541  // require that the input operand is a shift-by-constant so that we have
542  // confidence that the shifts will get folded together. We could do this
543  // xform in more cases, but it is unlikely to be profitable.
544  if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
545  isa<ConstantInt>(TrOp->getOperand(1))) {
546  // Okay, we'll do this xform. Make the shift of shift.
547  Constant *ShAmt =
548  ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
549  // (shift2 (shift1 & 0x00FF), c2)
550  Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName());
551 
552  // For logical shifts, the truncation has the effect of making the high
553  // part of the register be zeros. Emulate this by inserting an AND to
554  // clear the top bits as needed. This 'and' will usually be zapped by
555  // other xforms later if dead.
556  unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
557  unsigned DstSize = TI->getType()->getScalarSizeInBits();
558  APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
559 
560  // The mask we constructed says what the trunc would do if occurring
561  // between the shifts. We want to know the effect *after* the second
562  // shift. We know that it is a logical shift by a constant, so adjust the
563  // mask as appropriate.
564  if (I.getOpcode() == Instruction::Shl)
565  MaskV <<= Op1C->getZExtValue();
566  else {
567  assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
568  MaskV.lshrInPlace(Op1C->getZExtValue());
569  }
570 
571  // shift1 & 0x00FF
572  Value *And = Builder.CreateAnd(NSh,
573  ConstantInt::get(I.getContext(), MaskV),
574  TI->getName());
575 
576  // Return the value truncated to the interesting size.
577  return new TruncInst(And, I.getType());
578  }
579  }
580 
581  if (Op0->hasOneUse()) {
582  if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
583  // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
584  Value *V1, *V2;
585  ConstantInt *CC;
586  switch (Op0BO->getOpcode()) {
587  default: break;
588  case Instruction::Add:
589  case Instruction::And:
590  case Instruction::Or:
591  case Instruction::Xor: {
592  // These operators commute.
593  // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
594  if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
595  match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
596  m_Specific(Op1)))) {
597  Value *YS = // (Y << C)
598  Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
599  // (X + (Y << C))
600  Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1,
601  Op0BO->getOperand(1)->getName());
602  unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
603 
604  APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
606  if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
607  Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
608  return BinaryOperator::CreateAnd(X, Mask);
609  }
610 
611  // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
612  Value *Op0BOOp1 = Op0BO->getOperand(1);
613  if (isLeftShift && Op0BOOp1->hasOneUse() &&
614  match(Op0BOOp1,
615  m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
616  m_ConstantInt(CC)))) {
617  Value *YS = // (Y << C)
618  Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
619  // X & (CC << C)
620  Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
621  V1->getName()+".mask");
622  return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
623  }
625  }
626 
627  case Instruction::Sub: {
628  // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
629  if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
630  match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
631  m_Specific(Op1)))) {
632  Value *YS = // (Y << C)
633  Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
634  // (X + (Y << C))
635  Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS,
636  Op0BO->getOperand(0)->getName());
637  unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
638 
639  APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
641  if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
642  Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
643  return BinaryOperator::CreateAnd(X, Mask);
644  }
645 
646  // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
647  if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
648  match(Op0BO->getOperand(0),
649  m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
650  m_ConstantInt(CC))) && V2 == Op1) {
651  Value *YS = // (Y << C)
652  Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
653  // X & (CC << C)
654  Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
655  V1->getName()+".mask");
656 
657  return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
658  }
659 
660  break;
661  }
662  }
663 
664 
665  // If the operand is a bitwise operator with a constant RHS, and the
666  // shift is the only use, we can pull it out of the shift.
667  const APInt *Op0C;
668  if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
669  if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
670  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
671  cast<Constant>(Op0BO->getOperand(1)), Op1);
672 
673  Value *NewShift =
674  Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
675  NewShift->takeName(Op0BO);
676 
677  return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
678  NewRHS);
679  }
680  }
681 
682  // If the operand is a subtract with a constant LHS, and the shift
683  // is the only use, we can pull it out of the shift.
684  // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2))
685  if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub &&
686  match(Op0BO->getOperand(0), m_APInt(Op0C))) {
687  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
688  cast<Constant>(Op0BO->getOperand(0)), Op1);
689 
690  Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1);
691  NewShift->takeName(Op0BO);
692 
693  return BinaryOperator::CreateSub(NewRHS, NewShift);
694  }
695  }
696 
697  // If we have a select that conditionally executes some binary operator,
698  // see if we can pull it the select and operator through the shift.
699  //
700  // For example, turning:
701  // shl (select C, (add X, C1), X), C2
702  // Into:
703  // Y = shl X, C2
704  // select C, (add Y, C1 << C2), Y
705  Value *Cond;
706  BinaryOperator *TBO;
707  Value *FalseVal;
708  if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
709  m_Value(FalseVal)))) {
710  const APInt *C;
711  if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
712  match(TBO->getOperand(1), m_APInt(C)) &&
714  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
715  cast<Constant>(TBO->getOperand(1)), Op1);
716 
717  Value *NewShift =
718  Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1);
719  Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift,
720  NewRHS);
721  return SelectInst::Create(Cond, NewOp, NewShift);
722  }
723  }
724 
725  BinaryOperator *FBO;
726  Value *TrueVal;
727  if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
728  m_OneUse(m_BinOp(FBO))))) {
729  const APInt *C;
730  if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
731  match(FBO->getOperand(1), m_APInt(C)) &&
733  Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
734  cast<Constant>(FBO->getOperand(1)), Op1);
735 
736  Value *NewShift =
737  Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1);
738  Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift,
739  NewRHS);
740  return SelectInst::Create(Cond, NewShift, NewOp);
741  }
742  }
743  }
744 
745  return nullptr;
746 }
747 
749  if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
751  SQ.getWithInstruction(&I)))
752  return replaceInstUsesWith(I, V);
753 
754  if (Instruction *X = foldVectorBinop(I))
755  return X;
756 
757  if (Instruction *V = commonShiftTransforms(I))
758  return V;
759 
760  if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, SQ, Builder))
761  return V;
762 
763  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
764  Type *Ty = I.getType();
765  unsigned BitWidth = Ty->getScalarSizeInBits();
766 
767  const APInt *ShAmtAPInt;
768  if (match(Op1, m_APInt(ShAmtAPInt))) {
769  unsigned ShAmt = ShAmtAPInt->getZExtValue();
770 
771  // shl (zext X), ShAmt --> zext (shl X, ShAmt)
772  // This is only valid if X would have zeros shifted out.
773  Value *X;
774  if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
775  unsigned SrcWidth = X->getType()->getScalarSizeInBits();
776  if (ShAmt < SrcWidth &&
777  MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
778  return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty);
779  }
780 
781  // (X >> C) << C --> X & (-1 << C)
782  if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
783  APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
784  return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
785  }
786 
787  // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine)
788  // needs a few fixes for the rotate pattern recognition first.
789  const APInt *ShOp1;
790  if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) {
791  unsigned ShrAmt = ShOp1->getZExtValue();
792  if (ShrAmt < ShAmt) {
793  // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
794  Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt);
795  auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
796  NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
797  NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
798  return NewShl;
799  }
800  if (ShrAmt > ShAmt) {
801  // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2)
802  Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt);
803  auto *NewShr = BinaryOperator::Create(
804  cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
805  NewShr->setIsExact(true);
806  return NewShr;
807  }
808  }
809 
810  if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) {
811  unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
812  // Oversized shifts are simplified to zero in InstSimplify.
813  if (AmtSum < BitWidth)
814  // (X << C1) << C2 --> X << (C1 + C2)
815  return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
816  }
817 
818  // If the shifted-out value is known-zero, then this is a NUW shift.
819  if (!I.hasNoUnsignedWrap() &&
820  MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
822  return &I;
823  }
824 
825  // If the shifted-out value is all signbits, then this is a NSW shift.
826  if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
827  I.setHasNoSignedWrap();
828  return &I;
829  }
830  }
831 
832  // Transform (x >> y) << y to x & (-1 << y)
833  // Valid for any type of right-shift.
834  Value *X;
835  if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
836  Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
837  Value *Mask = Builder.CreateShl(AllOnes, Op1);
838  return BinaryOperator::CreateAnd(Mask, X);
839  }
840 
841  Constant *C1;
842  if (match(Op1, m_Constant(C1))) {
843  Constant *C2;
844  Value *X;
845  // (C2 << X) << C1 --> (C2 << C1) << X
846  if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X)))))
847  return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X);
848 
849  // (X * C2) << C1 --> X * (C2 << C1)
850  if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
852  }
853 
854  // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
855  if (match(Op0, m_One()) &&
856  match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
857  return BinaryOperator::CreateLShr(
858  ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
859 
860  return nullptr;
861 }
862 
864  if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
865  SQ.getWithInstruction(&I)))
866  return replaceInstUsesWith(I, V);
867 
868  if (Instruction *X = foldVectorBinop(I))
869  return X;
870 
871  if (Instruction *R = commonShiftTransforms(I))
872  return R;
873 
874  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
875  Type *Ty = I.getType();
876  const APInt *ShAmtAPInt;
877  if (match(Op1, m_APInt(ShAmtAPInt))) {
878  unsigned ShAmt = ShAmtAPInt->getZExtValue();
879  unsigned BitWidth = Ty->getScalarSizeInBits();
880  auto *II = dyn_cast<IntrinsicInst>(Op0);
881  if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
882  (II->getIntrinsicID() == Intrinsic::ctlz ||
883  II->getIntrinsicID() == Intrinsic::cttz ||
884  II->getIntrinsicID() == Intrinsic::ctpop)) {
885  // ctlz.i32(x)>>5 --> zext(x == 0)
886  // cttz.i32(x)>>5 --> zext(x == 0)
887  // ctpop.i32(x)>>5 --> zext(x == -1)
888  bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
889  Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
890  Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
891  return new ZExtInst(Cmp, Ty);
892  }
893 
894  Value *X;
895  const APInt *ShOp1;
896  if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) {
897  if (ShOp1->ult(ShAmt)) {
898  unsigned ShlAmt = ShOp1->getZExtValue();
899  Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
900  if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
901  // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
902  auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
903  NewLShr->setIsExact(I.isExact());
904  return NewLShr;
905  }
906  // (X << C1) >>u C2 --> (X >>u (C2 - C1)) & (-1 >> C2)
907  Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
908  APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
909  return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
910  }
911  if (ShOp1->ugt(ShAmt)) {
912  unsigned ShlAmt = ShOp1->getZExtValue();
913  Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
914  if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
915  // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2)
916  auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
917  NewShl->setHasNoUnsignedWrap(true);
918  return NewShl;
919  }
920  // (X << C1) >>u C2 --> X << (C1 - C2) & (-1 >> C2)
921  Value *NewShl = Builder.CreateShl(X, ShiftDiff);
922  APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
923  return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
924  }
925  assert(*ShOp1 == ShAmt);
926  // (X << C) >>u C --> X & (-1 >>u C)
927  APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
928  return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
929  }
930 
931  if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
932  (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
933  assert(ShAmt < X->getType()->getScalarSizeInBits() &&
934  "Big shift not simplified to zero?");
935  // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
936  Value *NewLShr = Builder.CreateLShr(X, ShAmt);
937  return new ZExtInst(NewLShr, Ty);
938  }
939 
940  if (match(Op0, m_SExt(m_Value(X))) &&
941  (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
942  // Are we moving the sign bit to the low bit and widening with high zeros?
943  unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
944  if (ShAmt == BitWidth - 1) {
945  // lshr (sext i1 X to iN), N-1 --> zext X to iN
946  if (SrcTyBitWidth == 1)
947  return new ZExtInst(X, Ty);
948 
949  // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
950  if (Op0->hasOneUse()) {
951  Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
952  return new ZExtInst(NewLShr, Ty);
953  }
954  }
955 
956  // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
957  if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) {
958  // The new shift amount can't be more than the narrow source type.
959  unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1);
960  Value *AShr = Builder.CreateAShr(X, NewShAmt);
961  return new ZExtInst(AShr, Ty);
962  }
963  }
964 
965  if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) {
966  unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
967  // Oversized shifts are simplified to zero in InstSimplify.
968  if (AmtSum < BitWidth)
969  // (X >>u C1) >>u C2 --> X >>u (C1 + C2)
970  return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
971  }
972 
973  // If the shifted-out value is known-zero, then this is an exact shift.
974  if (!I.isExact() &&
975  MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
976  I.setIsExact();
977  return &I;
978  }
979  }
980 
981  // Transform (x << y) >> y to x & (-1 >> y)
982  Value *X;
983  if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
984  Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
985  Value *Mask = Builder.CreateLShr(AllOnes, Op1);
986  return BinaryOperator::CreateAnd(Mask, X);
987  }
988 
989  return nullptr;
990 }
991 
993  if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
994  SQ.getWithInstruction(&I)))
995  return replaceInstUsesWith(I, V);
996 
997  if (Instruction *X = foldVectorBinop(I))
998  return X;
999 
1000  if (Instruction *R = commonShiftTransforms(I))
1001  return R;
1002 
1003  Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1004  Type *Ty = I.getType();
1005  unsigned BitWidth = Ty->getScalarSizeInBits();
1006  const APInt *ShAmtAPInt;
1007  if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1008  unsigned ShAmt = ShAmtAPInt->getZExtValue();
1009 
1010  // If the shift amount equals the difference in width of the destination
1011  // and source scalar types:
1012  // ashr (shl (zext X), C), C --> sext X
1013  Value *X;
1014  if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1015  ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1016  return new SExtInst(X, Ty);
1017 
1018  // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1019  // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1020  const APInt *ShOp1;
1021  if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1022  ShOp1->ult(BitWidth)) {
1023  unsigned ShlAmt = ShOp1->getZExtValue();
1024  if (ShlAmt < ShAmt) {
1025  // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1026  Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1027  auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1028  NewAShr->setIsExact(I.isExact());
1029  return NewAShr;
1030  }
1031  if (ShlAmt > ShAmt) {
1032  // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1033  Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1034  auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1035  NewShl->setHasNoSignedWrap(true);
1036  return NewShl;
1037  }
1038  }
1039 
1040  if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1041  ShOp1->ult(BitWidth)) {
1042  unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1043  // Oversized arithmetic shifts replicate the sign bit.
1044  AmtSum = std::min(AmtSum, BitWidth - 1);
1045  // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1046  return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1047  }
1048 
1049  if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1050  (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1051  // ashr (sext X), C --> sext (ashr X, C')
1052  Type *SrcTy = X->getType();
1053  ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1054  Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1055  return new SExtInst(NewSh, Ty);
1056  }
1057 
1058  // If the shifted-out value is known-zero, then this is an exact shift.
1059  if (!I.isExact() &&
1060  MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1061  I.setIsExact();
1062  return &I;
1063  }
1064  }
1065 
1066  // See if we can turn a signed shr into an unsigned shr.
1067  if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1068  return BinaryOperator::CreateLShr(Op0, Op1);
1069 
1070  return nullptr;
1071 }
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:1571
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
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
static Instruction * dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift, const SimplifyQuery &SQ, InstCombiner::BuilderTy &Builder)
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