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"
14 #include "llvm/Analysis/ConstantFolding.h"
15 #include "llvm/Analysis/InstructionSimplify.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 *
29 reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0,
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,
45         m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)),
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 *
133 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
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 
190 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
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 =
209           reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ, Builder))
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 
298   Instruction *I = dyn_cast<Instruction>(V);
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 =
439               ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
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.
485 static bool canShiftBinOpWithConstantRHS(BinaryOperator &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 
499 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
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);
599           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
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         }
618         LLVM_FALLTHROUGH;
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);
634           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
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)) &&
707           canShiftBinOpWithConstantRHS(I, TBO)) {
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)) &&
726           canShiftBinOpWithConstantRHS(I, FBO)) {
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 
742 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
743   if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
744                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
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 
754   if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, SQ))
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)) {
816       I.setHasNoUnsignedWrap();
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))))
846       return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
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 
858 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
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 
987 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
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 }
1067