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/InstructionSimplify.h"
15 #include "llvm/IR/IntrinsicInst.h"
16 #include "llvm/IR/PatternMatch.h"
17 #include "llvm/Transforms/InstCombine/InstCombiner.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20 
21 #define DEBUG_TYPE "instcombine"
22 
23 bool canTryToConstantAddTwoShiftAmounts(Value *Sh0, Value *ShAmt0, Value *Sh1,
24                                         Value *ShAmt1) {
25   // We have two shift amounts from two different shifts. The types of those
26   // shift amounts may not match. If that's the case let's bailout now..
27   if (ShAmt0->getType() != ShAmt1->getType())
28     return false;
29 
30   // As input, we have the following pattern:
31   //   Sh0 (Sh1 X, Q), K
32   // We want to rewrite that as:
33   //   Sh x, (Q+K)  iff (Q+K) u< bitwidth(x)
34   // While we know that originally (Q+K) would not overflow
35   // (because  2 * (N-1) u<= iN -1), we have looked past extensions of
36   // shift amounts. so it may now overflow in smaller bitwidth.
37   // To ensure that does not happen, we need to ensure that the total maximal
38   // shift amount is still representable in that smaller bit width.
39   unsigned MaximalPossibleTotalShiftAmount =
40       (Sh0->getType()->getScalarSizeInBits() - 1) +
41       (Sh1->getType()->getScalarSizeInBits() - 1);
42   APInt MaximalRepresentableShiftAmount =
43       APInt::getAllOnes(ShAmt0->getType()->getScalarSizeInBits());
44   return MaximalRepresentableShiftAmount.uge(MaximalPossibleTotalShiftAmount);
45 }
46 
47 // Given pattern:
48 //   (x shiftopcode Q) shiftopcode K
49 // we should rewrite it as
50 //   x shiftopcode (Q+K)  iff (Q+K) u< bitwidth(x) and
51 //
52 // This is valid for any shift, but they must be identical, and we must be
53 // careful in case we have (zext(Q)+zext(K)) and look past extensions,
54 // (Q+K) must not overflow or else (Q+K) u< bitwidth(x) is bogus.
55 //
56 // AnalyzeForSignBitExtraction indicates that we will only analyze whether this
57 // pattern has any 2 right-shifts that sum to 1 less than original bit width.
58 Value *InstCombinerImpl::reassociateShiftAmtsOfTwoSameDirectionShifts(
59     BinaryOperator *Sh0, const SimplifyQuery &SQ,
60     bool AnalyzeForSignBitExtraction) {
61   // Look for a shift of some instruction, ignore zext of shift amount if any.
62   Instruction *Sh0Op0;
63   Value *ShAmt0;
64   if (!match(Sh0,
65              m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0)))))
66     return nullptr;
67 
68   // If there is a truncation between the two shifts, we must make note of it
69   // and look through it. The truncation imposes additional constraints on the
70   // transform.
71   Instruction *Sh1;
72   Value *Trunc = nullptr;
73   match(Sh0Op0,
74         m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)),
75                     m_Instruction(Sh1)));
76 
77   // Inner shift: (x shiftopcode ShAmt1)
78   // Like with other shift, ignore zext of shift amount if any.
79   Value *X, *ShAmt1;
80   if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1)))))
81     return nullptr;
82 
83   // Verify that it would be safe to try to add those two shift amounts.
84   if (!canTryToConstantAddTwoShiftAmounts(Sh0, ShAmt0, Sh1, ShAmt1))
85     return nullptr;
86 
87   // We are only looking for signbit extraction if we have two right shifts.
88   bool HadTwoRightShifts = match(Sh0, m_Shr(m_Value(), m_Value())) &&
89                            match(Sh1, m_Shr(m_Value(), m_Value()));
90   // ... and if it's not two right-shifts, we know the answer already.
91   if (AnalyzeForSignBitExtraction && !HadTwoRightShifts)
92     return nullptr;
93 
94   // The shift opcodes must be identical, unless we are just checking whether
95   // this pattern can be interpreted as a sign-bit-extraction.
96   Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
97   bool IdenticalShOpcodes = Sh0->getOpcode() == Sh1->getOpcode();
98   if (!IdenticalShOpcodes && !AnalyzeForSignBitExtraction)
99     return nullptr;
100 
101   // If we saw truncation, we'll need to produce extra instruction,
102   // and for that one of the operands of the shift must be one-use,
103   // unless of course we don't actually plan to produce any instructions here.
104   if (Trunc && !AnalyzeForSignBitExtraction &&
105       !match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
106     return nullptr;
107 
108   // Can we fold (ShAmt0+ShAmt1) ?
109   auto *NewShAmt = dyn_cast_or_null<Constant>(
110       simplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
111                       SQ.getWithInstruction(Sh0)));
112   if (!NewShAmt)
113     return nullptr; // Did not simplify.
114   unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits();
115   unsigned XBitWidth = X->getType()->getScalarSizeInBits();
116   // Is the new shift amount smaller than the bit width of inner/new shift?
117   if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
118                                           APInt(NewShAmtBitWidth, XBitWidth))))
119     return nullptr; // FIXME: could perform constant-folding.
120 
121   // If there was a truncation, and we have a right-shift, we can only fold if
122   // we are left with the original sign bit. Likewise, if we were just checking
123   // that this is a sighbit extraction, this is the place to check it.
124   // FIXME: zero shift amount is also legal here, but we can't *easily* check
125   // more than one predicate so it's not really worth it.
126   if (HadTwoRightShifts && (Trunc || AnalyzeForSignBitExtraction)) {
127     // If it's not a sign bit extraction, then we're done.
128     if (!match(NewShAmt,
129                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
130                                   APInt(NewShAmtBitWidth, XBitWidth - 1))))
131       return nullptr;
132     // If it is, and that was the question, return the base value.
133     if (AnalyzeForSignBitExtraction)
134       return X;
135   }
136 
137   assert(IdenticalShOpcodes && "Should not get here with different shifts.");
138 
139   // All good, we can do this fold.
140   NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
141 
142   BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
143 
144   // The flags can only be propagated if there wasn't a trunc.
145   if (!Trunc) {
146     // If the pattern did not involve trunc, and both of the original shifts
147     // had the same flag set, preserve the flag.
148     if (ShiftOpcode == Instruction::BinaryOps::Shl) {
149       NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
150                                      Sh1->hasNoUnsignedWrap());
151       NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
152                                    Sh1->hasNoSignedWrap());
153     } else {
154       NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
155     }
156   }
157 
158   Instruction *Ret = NewShift;
159   if (Trunc) {
160     Builder.Insert(NewShift);
161     Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
162   }
163 
164   return Ret;
165 }
166 
167 // If we have some pattern that leaves only some low bits set, and then performs
168 // left-shift of those bits, if none of the bits that are left after the final
169 // shift are modified by the mask, we can omit the mask.
170 //
171 // There are many variants to this pattern:
172 //   a)  (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
173 //   b)  (x & (~(-1 << MaskShAmt))) << ShiftShAmt
174 //   c)  (x & (-1 l>> MaskShAmt)) << ShiftShAmt
175 //   d)  (x & ((-1 << MaskShAmt) l>> MaskShAmt)) << ShiftShAmt
176 //   e)  ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
177 //   f)  ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
178 // All these patterns can be simplified to just:
179 //   x << ShiftShAmt
180 // iff:
181 //   a,b)     (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
182 //   c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
183 static Instruction *
184 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
185                                      const SimplifyQuery &Q,
186                                      InstCombiner::BuilderTy &Builder) {
187   assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
188          "The input must be 'shl'!");
189 
190   Value *Masked, *ShiftShAmt;
191   match(OuterShift,
192         m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt))));
193 
194   // *If* there is a truncation between an outer shift and a possibly-mask,
195   // then said truncation *must* be one-use, else we can't perform the fold.
196   Value *Trunc;
197   if (match(Masked, m_CombineAnd(m_Trunc(m_Value(Masked)), m_Value(Trunc))) &&
198       !Trunc->hasOneUse())
199     return nullptr;
200 
201   Type *NarrowestTy = OuterShift->getType();
202   Type *WidestTy = Masked->getType();
203   bool HadTrunc = WidestTy != NarrowestTy;
204 
205   // The mask must be computed in a type twice as wide to ensure
206   // that no bits are lost if the sum-of-shifts is wider than the base type.
207   Type *ExtendedTy = WidestTy->getExtendedType();
208 
209   Value *MaskShAmt;
210 
211   // ((1 << MaskShAmt) - 1)
212   auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
213   // (~(-1 << maskNbits))
214   auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
215   // (-1 l>> MaskShAmt)
216   auto MaskC = m_LShr(m_AllOnes(), m_Value(MaskShAmt));
217   // ((-1 << MaskShAmt) l>> MaskShAmt)
218   auto MaskD =
219       m_LShr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
220 
221   Value *X;
222   Constant *NewMask;
223 
224   if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
225     // Peek through an optional zext of the shift amount.
226     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
227 
228     // Verify that it would be safe to try to add those two shift amounts.
229     if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
230                                             MaskShAmt))
231       return nullptr;
232 
233     // Can we simplify (MaskShAmt+ShiftShAmt) ?
234     auto *SumOfShAmts = dyn_cast_or_null<Constant>(simplifyAddInst(
235         MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
236     if (!SumOfShAmts)
237       return nullptr; // Did not simplify.
238     // In this pattern SumOfShAmts correlates with the number of low bits
239     // that shall remain in the root value (OuterShift).
240 
241     // An extend of an undef value becomes zero because the high bits are never
242     // completely unknown. Replace the `undef` shift amounts with final
243     // shift bitwidth to ensure that the value remains undef when creating the
244     // subsequent shift op.
245     SumOfShAmts = Constant::replaceUndefsWith(
246         SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
247                                       ExtendedTy->getScalarSizeInBits()));
248     auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy);
249     // And compute the mask as usual: ~(-1 << (SumOfShAmts))
250     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
251     auto *ExtendedInvertedMask =
252         ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts);
253     NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
254   } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
255              match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
256                                  m_Deferred(MaskShAmt)))) {
257     // Peek through an optional zext of the shift amount.
258     match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
259 
260     // Verify that it would be safe to try to add those two shift amounts.
261     if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
262                                             MaskShAmt))
263       return nullptr;
264 
265     // Can we simplify (ShiftShAmt-MaskShAmt) ?
266     auto *ShAmtsDiff = dyn_cast_or_null<Constant>(simplifySubInst(
267         ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
268     if (!ShAmtsDiff)
269       return nullptr; // Did not simplify.
270     // In this pattern ShAmtsDiff correlates with the number of high bits that
271     // shall be unset in the root value (OuterShift).
272 
273     // An extend of an undef value becomes zero because the high bits are never
274     // completely unknown. Replace the `undef` shift amounts with negated
275     // bitwidth of innermost shift to ensure that the value remains undef when
276     // creating the subsequent shift op.
277     unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
278     ShAmtsDiff = Constant::replaceUndefsWith(
279         ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(),
280                                      -WidestTyBitWidth));
281     auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt(
282         ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
283                                               WidestTyBitWidth,
284                                               /*isSigned=*/false),
285                              ShAmtsDiff),
286         ExtendedTy);
287     // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
288     auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
289     NewMask =
290         ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear);
291   } else
292     return nullptr; // Don't know anything about this pattern.
293 
294   NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
295 
296   // Does this mask has any unset bits? If not then we can just not apply it.
297   bool NeedMask = !match(NewMask, m_AllOnes());
298 
299   // If we need to apply a mask, there are several more restrictions we have.
300   if (NeedMask) {
301     // The old masking instruction must go away.
302     if (!Masked->hasOneUse())
303       return nullptr;
304     // The original "masking" instruction must not have been`ashr`.
305     if (match(Masked, m_AShr(m_Value(), m_Value())))
306       return nullptr;
307   }
308 
309   // If we need to apply truncation, let's do it first, since we can.
310   // We have already ensured that the old truncation will go away.
311   if (HadTrunc)
312     X = Builder.CreateTrunc(X, NarrowestTy);
313 
314   // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
315   // We didn't change the Type of this outermost shift, so we can just do it.
316   auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
317                                           OuterShift->getOperand(1));
318   if (!NeedMask)
319     return NewShift;
320 
321   Builder.Insert(NewShift);
322   return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
323 }
324 
325 /// If we have a shift-by-constant of a bitwise logic op that itself has a
326 /// shift-by-constant operand with identical opcode, we may be able to convert
327 /// that into 2 independent shifts followed by the logic op. This eliminates a
328 /// a use of an intermediate value (reduces dependency chain).
329 static Instruction *foldShiftOfShiftedLogic(BinaryOperator &I,
330                                             InstCombiner::BuilderTy &Builder) {
331   assert(I.isShift() && "Expected a shift as input");
332   auto *LogicInst = dyn_cast<BinaryOperator>(I.getOperand(0));
333   if (!LogicInst || !LogicInst->isBitwiseLogicOp() || !LogicInst->hasOneUse())
334     return nullptr;
335 
336   Constant *C0, *C1;
337   if (!match(I.getOperand(1), m_Constant(C1)))
338     return nullptr;
339 
340   Instruction::BinaryOps ShiftOpcode = I.getOpcode();
341   Type *Ty = I.getType();
342 
343   // Find a matching one-use shift by constant. The fold is not valid if the sum
344   // of the shift values equals or exceeds bitwidth.
345   // TODO: Remove the one-use check if the other logic operand (Y) is constant.
346   Value *X, *Y;
347   auto matchFirstShift = [&](Value *V) {
348     APInt Threshold(Ty->getScalarSizeInBits(), Ty->getScalarSizeInBits());
349     return match(V, m_BinOp(ShiftOpcode, m_Value(), m_Value())) &&
350            match(V, m_OneUse(m_Shift(m_Value(X), m_Constant(C0)))) &&
351            match(ConstantExpr::getAdd(C0, C1),
352                  m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
353   };
354 
355   // Logic ops are commutative, so check each operand for a match.
356   if (matchFirstShift(LogicInst->getOperand(0)))
357     Y = LogicInst->getOperand(1);
358   else if (matchFirstShift(LogicInst->getOperand(1)))
359     Y = LogicInst->getOperand(0);
360   else
361     return nullptr;
362 
363   // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
364   Constant *ShiftSumC = ConstantExpr::getAdd(C0, C1);
365   Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
366   Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, I.getOperand(1));
367   return BinaryOperator::Create(LogicInst->getOpcode(), NewShift1, NewShift2);
368 }
369 
370 Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) {
371   if (Instruction *Phi = foldBinopWithPhiOperands(I))
372     return Phi;
373 
374   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
375   assert(Op0->getType() == Op1->getType());
376   Type *Ty = I.getType();
377 
378   // If the shift amount is a one-use `sext`, we can demote it to `zext`.
379   Value *Y;
380   if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
381     Value *NewExt = Builder.CreateZExt(Y, Ty, Op1->getName());
382     return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
383   }
384 
385   // See if we can fold away this shift.
386   if (SimplifyDemandedInstructionBits(I))
387     return &I;
388 
389   // Try to fold constant and into select arguments.
390   if (isa<Constant>(Op0))
391     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
392       if (Instruction *R = FoldOpIntoSelect(I, SI))
393         return R;
394 
395   if (Constant *CUI = dyn_cast<Constant>(Op1))
396     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
397       return Res;
398 
399   if (auto *NewShift = cast_or_null<Instruction>(
400           reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ)))
401     return NewShift;
402 
403   // Pre-shift a constant shifted by a variable amount with constant offset:
404   // C shift (A add nuw C1) --> (C shift C1) shift A
405   Value *A;
406   Constant *C, *C1;
407   if (match(Op0, m_Constant(C)) &&
408       match(Op1, m_NUWAdd(m_Value(A), m_Constant(C1)))) {
409     Constant *NewC = ConstantExpr::get(I.getOpcode(), C, C1);
410     return BinaryOperator::Create(I.getOpcode(), NewC, A);
411   }
412 
413   unsigned BitWidth = Ty->getScalarSizeInBits();
414 
415   const APInt *AC, *AddC;
416   // Try to pre-shift a constant shifted by a variable amount added with a
417   // negative number:
418   // C << (X - AddC) --> (C >> AddC) << X
419   // and
420   // C >> (X - AddC) --> (C << AddC) >> X
421   if (match(Op0, m_APInt(AC)) && match(Op1, m_Add(m_Value(A), m_APInt(AddC))) &&
422       AddC->isNegative() && (-*AddC).ult(BitWidth)) {
423     assert(!AC->isZero() && "Expected simplify of shifted zero");
424     unsigned PosOffset = (-*AddC).getZExtValue();
425 
426     auto isSuitableForPreShift = [PosOffset, &I, AC]() {
427       switch (I.getOpcode()) {
428       default:
429         return false;
430       case Instruction::Shl:
431         return (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) &&
432                AC->eq(AC->lshr(PosOffset).shl(PosOffset));
433       case Instruction::LShr:
434         return I.isExact() && AC->eq(AC->shl(PosOffset).lshr(PosOffset));
435       case Instruction::AShr:
436         return I.isExact() && AC->eq(AC->shl(PosOffset).ashr(PosOffset));
437       }
438     };
439     if (isSuitableForPreShift()) {
440       Constant *NewC = ConstantInt::get(Ty, I.getOpcode() == Instruction::Shl
441                                                 ? AC->lshr(PosOffset)
442                                                 : AC->shl(PosOffset));
443       BinaryOperator *NewShiftOp =
444           BinaryOperator::Create(I.getOpcode(), NewC, A);
445       if (I.getOpcode() == Instruction::Shl) {
446         NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
447       } else {
448         NewShiftOp->setIsExact();
449       }
450       return NewShiftOp;
451     }
452   }
453 
454   // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2.
455   // Because shifts by negative values (which could occur if A were negative)
456   // are undefined.
457   if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Constant(C))) &&
458       match(C, m_Power2())) {
459     // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
460     // demand the sign bit (and many others) here??
461     Constant *Mask = ConstantExpr::getSub(C, ConstantInt::get(Ty, 1));
462     Value *Rem = Builder.CreateAnd(A, Mask, Op1->getName());
463     return replaceOperand(I, 1, Rem);
464   }
465 
466   if (Instruction *Logic = foldShiftOfShiftedLogic(I, Builder))
467     return Logic;
468 
469   return nullptr;
470 }
471 
472 /// Return true if we can simplify two logical (either left or right) shifts
473 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
474 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
475                                     Instruction *InnerShift,
476                                     InstCombinerImpl &IC, Instruction *CxtI) {
477   assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
478 
479   // We need constant scalar or constant splat shifts.
480   const APInt *InnerShiftConst;
481   if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
482     return false;
483 
484   // Two logical shifts in the same direction:
485   // shl (shl X, C1), C2 -->  shl X, C1 + C2
486   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
487   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
488   if (IsInnerShl == IsOuterShl)
489     return true;
490 
491   // Equal shift amounts in opposite directions become bitwise 'and':
492   // lshr (shl X, C), C --> and X, C'
493   // shl (lshr X, C), C --> and X, C'
494   if (*InnerShiftConst == OuterShAmt)
495     return true;
496 
497   // If the 2nd shift is bigger than the 1st, we can fold:
498   // lshr (shl X, C1), C2 -->  and (shl X, C1 - C2), C3
499   // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
500   // but it isn't profitable unless we know the and'd out bits are already zero.
501   // Also, check that the inner shift is valid (less than the type width) or
502   // we'll crash trying to produce the bit mask for the 'and'.
503   unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
504   if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
505     unsigned InnerShAmt = InnerShiftConst->getZExtValue();
506     unsigned MaskShift =
507         IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
508     APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
509     if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
510       return true;
511   }
512 
513   return false;
514 }
515 
516 /// See if we can compute the specified value, but shifted logically to the left
517 /// or right by some number of bits. This should return true if the expression
518 /// can be computed for the same cost as the current expression tree. This is
519 /// used to eliminate extraneous shifting from things like:
520 ///      %C = shl i128 %A, 64
521 ///      %D = shl i128 %B, 96
522 ///      %E = or i128 %C, %D
523 ///      %F = lshr i128 %E, 64
524 /// where the client will ask if E can be computed shifted right by 64-bits. If
525 /// this succeeds, getShiftedValue() will be called to produce the value.
526 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
527                                InstCombinerImpl &IC, Instruction *CxtI) {
528   // We can always evaluate constants shifted.
529   if (isa<Constant>(V))
530     return true;
531 
532   Instruction *I = dyn_cast<Instruction>(V);
533   if (!I) return false;
534 
535   // We can't mutate something that has multiple uses: doing so would
536   // require duplicating the instruction in general, which isn't profitable.
537   if (!I->hasOneUse()) return false;
538 
539   switch (I->getOpcode()) {
540   default: return false;
541   case Instruction::And:
542   case Instruction::Or:
543   case Instruction::Xor:
544     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
545     return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
546            canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
547 
548   case Instruction::Shl:
549   case Instruction::LShr:
550     return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
551 
552   case Instruction::Select: {
553     SelectInst *SI = cast<SelectInst>(I);
554     Value *TrueVal = SI->getTrueValue();
555     Value *FalseVal = SI->getFalseValue();
556     return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
557            canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
558   }
559   case Instruction::PHI: {
560     // We can change a phi if we can change all operands.  Note that we never
561     // get into trouble with cyclic PHIs here because we only consider
562     // instructions with a single use.
563     PHINode *PN = cast<PHINode>(I);
564     for (Value *IncValue : PN->incoming_values())
565       if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
566         return false;
567     return true;
568   }
569   }
570 }
571 
572 /// Fold OuterShift (InnerShift X, C1), C2.
573 /// See canEvaluateShiftedShift() for the constraints on these instructions.
574 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
575                                bool IsOuterShl,
576                                InstCombiner::BuilderTy &Builder) {
577   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
578   Type *ShType = InnerShift->getType();
579   unsigned TypeWidth = ShType->getScalarSizeInBits();
580 
581   // We only accept shifts-by-a-constant in canEvaluateShifted().
582   const APInt *C1;
583   match(InnerShift->getOperand(1), m_APInt(C1));
584   unsigned InnerShAmt = C1->getZExtValue();
585 
586   // Change the shift amount and clear the appropriate IR flags.
587   auto NewInnerShift = [&](unsigned ShAmt) {
588     InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
589     if (IsInnerShl) {
590       InnerShift->setHasNoUnsignedWrap(false);
591       InnerShift->setHasNoSignedWrap(false);
592     } else {
593       InnerShift->setIsExact(false);
594     }
595     return InnerShift;
596   };
597 
598   // Two logical shifts in the same direction:
599   // shl (shl X, C1), C2 -->  shl X, C1 + C2
600   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
601   if (IsInnerShl == IsOuterShl) {
602     // If this is an oversized composite shift, then unsigned shifts get 0.
603     if (InnerShAmt + OuterShAmt >= TypeWidth)
604       return Constant::getNullValue(ShType);
605 
606     return NewInnerShift(InnerShAmt + OuterShAmt);
607   }
608 
609   // Equal shift amounts in opposite directions become bitwise 'and':
610   // lshr (shl X, C), C --> and X, C'
611   // shl (lshr X, C), C --> and X, C'
612   if (InnerShAmt == OuterShAmt) {
613     APInt Mask = IsInnerShl
614                      ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
615                      : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
616     Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
617                                    ConstantInt::get(ShType, Mask));
618     if (auto *AndI = dyn_cast<Instruction>(And)) {
619       AndI->moveBefore(InnerShift);
620       AndI->takeName(InnerShift);
621     }
622     return And;
623   }
624 
625   assert(InnerShAmt > OuterShAmt &&
626          "Unexpected opposite direction logical shift pair");
627 
628   // In general, we would need an 'and' for this transform, but
629   // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
630   // lshr (shl X, C1), C2 -->  shl X, C1 - C2
631   // shl (lshr X, C1), C2 --> lshr X, C1 - C2
632   return NewInnerShift(InnerShAmt - OuterShAmt);
633 }
634 
635 /// When canEvaluateShifted() returns true for an expression, this function
636 /// inserts the new computation that produces the shifted value.
637 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
638                               InstCombinerImpl &IC, const DataLayout &DL) {
639   // We can always evaluate constants shifted.
640   if (Constant *C = dyn_cast<Constant>(V)) {
641     if (isLeftShift)
642       return IC.Builder.CreateShl(C, NumBits);
643     else
644       return IC.Builder.CreateLShr(C, NumBits);
645   }
646 
647   Instruction *I = cast<Instruction>(V);
648   IC.addToWorklist(I);
649 
650   switch (I->getOpcode()) {
651   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
652   case Instruction::And:
653   case Instruction::Or:
654   case Instruction::Xor:
655     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
656     I->setOperand(
657         0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
658     I->setOperand(
659         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
660     return I;
661 
662   case Instruction::Shl:
663   case Instruction::LShr:
664     return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
665                             IC.Builder);
666 
667   case Instruction::Select:
668     I->setOperand(
669         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
670     I->setOperand(
671         2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
672     return I;
673   case Instruction::PHI: {
674     // We can change a phi if we can change all operands.  Note that we never
675     // get into trouble with cyclic PHIs here because we only consider
676     // instructions with a single use.
677     PHINode *PN = cast<PHINode>(I);
678     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
679       PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
680                                               isLeftShift, IC, DL));
681     return PN;
682   }
683   }
684 }
685 
686 // If this is a bitwise operator or add with a constant RHS we might be able
687 // to pull it through a shift.
688 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
689                                          BinaryOperator *BO) {
690   switch (BO->getOpcode()) {
691   default:
692     return false; // Do not perform transform!
693   case Instruction::Add:
694     return Shift.getOpcode() == Instruction::Shl;
695   case Instruction::Or:
696   case Instruction::And:
697     return true;
698   case Instruction::Xor:
699     // Do not change a 'not' of logical shift because that would create a normal
700     // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
701     return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
702   }
703 }
704 
705 Instruction *InstCombinerImpl::FoldShiftByConstant(Value *Op0, Constant *C1,
706                                                    BinaryOperator &I) {
707   // (C2 << X) << C1 --> (C2 << C1) << X
708   // (C2 >> X) >> C1 --> (C2 >> C1) >> X
709   Constant *C2;
710   Value *X;
711   if (match(Op0, m_BinOp(I.getOpcode(), m_Constant(C2), m_Value(X))))
712     return BinaryOperator::Create(I.getOpcode(),
713                                   ConstantExpr::get(I.getOpcode(), C2, C1), X);
714 
715   const APInt *Op1C;
716   if (!match(C1, m_APInt(Op1C)))
717     return nullptr;
718 
719   // See if we can propagate this shift into the input, this covers the trivial
720   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
721   bool IsLeftShift = I.getOpcode() == Instruction::Shl;
722   if (I.getOpcode() != Instruction::AShr &&
723       canEvaluateShifted(Op0, Op1C->getZExtValue(), IsLeftShift, *this, &I)) {
724     LLVM_DEBUG(
725         dbgs() << "ICE: GetShiftedValue propagating shift through expression"
726                   " to eliminate shift:\n  IN: "
727                << *Op0 << "\n  SH: " << I << "\n");
728 
729     return replaceInstUsesWith(
730         I, getShiftedValue(Op0, Op1C->getZExtValue(), IsLeftShift, *this, DL));
731   }
732 
733   // See if we can simplify any instructions used by the instruction whose sole
734   // purpose is to compute bits we don't care about.
735   Type *Ty = I.getType();
736   unsigned TypeBits = Ty->getScalarSizeInBits();
737   assert(!Op1C->uge(TypeBits) &&
738          "Shift over the type width should have been removed already");
739   (void)TypeBits;
740 
741   if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
742     return FoldedShift;
743 
744   if (!Op0->hasOneUse())
745     return nullptr;
746 
747   if (auto *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
748     // If the operand is a bitwise operator with a constant RHS, and the
749     // shift is the only use, we can pull it out of the shift.
750     const APInt *Op0C;
751     if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
752       if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
753         Constant *NewRHS = ConstantExpr::get(
754             I.getOpcode(), cast<Constant>(Op0BO->getOperand(1)), C1);
755 
756         Value *NewShift =
757             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), C1);
758         NewShift->takeName(Op0BO);
759 
760         return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, NewRHS);
761       }
762     }
763   }
764 
765   // If we have a select that conditionally executes some binary operator,
766   // see if we can pull it the select and operator through the shift.
767   //
768   // For example, turning:
769   //   shl (select C, (add X, C1), X), C2
770   // Into:
771   //   Y = shl X, C2
772   //   select C, (add Y, C1 << C2), Y
773   Value *Cond;
774   BinaryOperator *TBO;
775   Value *FalseVal;
776   if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
777                           m_Value(FalseVal)))) {
778     const APInt *C;
779     if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
780         match(TBO->getOperand(1), m_APInt(C)) &&
781         canShiftBinOpWithConstantRHS(I, TBO)) {
782       Constant *NewRHS = ConstantExpr::get(
783           I.getOpcode(), cast<Constant>(TBO->getOperand(1)), C1);
784 
785       Value *NewShift = Builder.CreateBinOp(I.getOpcode(), FalseVal, C1);
786       Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, NewRHS);
787       return SelectInst::Create(Cond, NewOp, NewShift);
788     }
789   }
790 
791   BinaryOperator *FBO;
792   Value *TrueVal;
793   if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
794                           m_OneUse(m_BinOp(FBO))))) {
795     const APInt *C;
796     if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
797         match(FBO->getOperand(1), m_APInt(C)) &&
798         canShiftBinOpWithConstantRHS(I, FBO)) {
799       Constant *NewRHS = ConstantExpr::get(
800           I.getOpcode(), cast<Constant>(FBO->getOperand(1)), C1);
801 
802       Value *NewShift = Builder.CreateBinOp(I.getOpcode(), TrueVal, C1);
803       Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, NewRHS);
804       return SelectInst::Create(Cond, NewShift, NewOp);
805     }
806   }
807 
808   return nullptr;
809 }
810 
811 Instruction *InstCombinerImpl::visitShl(BinaryOperator &I) {
812   const SimplifyQuery Q = SQ.getWithInstruction(&I);
813 
814   if (Value *V = simplifyShlInst(I.getOperand(0), I.getOperand(1),
815                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
816     return replaceInstUsesWith(I, V);
817 
818   if (Instruction *X = foldVectorBinop(I))
819     return X;
820 
821   if (Instruction *V = commonShiftTransforms(I))
822     return V;
823 
824   if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder))
825     return V;
826 
827   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
828   Type *Ty = I.getType();
829   unsigned BitWidth = Ty->getScalarSizeInBits();
830 
831   const APInt *C;
832   if (match(Op1, m_APInt(C))) {
833     unsigned ShAmtC = C->getZExtValue();
834 
835     // shl (zext X), C --> zext (shl X, C)
836     // This is only valid if X would have zeros shifted out.
837     Value *X;
838     if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
839       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
840       if (ShAmtC < SrcWidth &&
841           MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmtC), 0, &I))
842         return new ZExtInst(Builder.CreateShl(X, ShAmtC), Ty);
843     }
844 
845     // (X >> C) << C --> X & (-1 << C)
846     if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
847       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
848       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
849     }
850 
851     const APInt *C1;
852     if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(C1)))) &&
853         C1->ult(BitWidth)) {
854       unsigned ShrAmt = C1->getZExtValue();
855       if (ShrAmt < ShAmtC) {
856         // If C1 < C: (X >>?,exact C1) << C --> X << (C - C1)
857         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
858         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
859         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
860         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
861         return NewShl;
862       }
863       if (ShrAmt > ShAmtC) {
864         // If C1 > C: (X >>?exact C1) << C --> X >>?exact (C1 - C)
865         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
866         auto *NewShr = BinaryOperator::Create(
867             cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
868         NewShr->setIsExact(true);
869         return NewShr;
870       }
871     }
872 
873     if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_APInt(C1)))) &&
874         C1->ult(BitWidth)) {
875       unsigned ShrAmt = C1->getZExtValue();
876       if (ShrAmt < ShAmtC) {
877         // If C1 < C: (X >>? C1) << C --> (X << (C - C1)) & (-1 << C)
878         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
879         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
880         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
881         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
882         Builder.Insert(NewShl);
883         APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
884         return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
885       }
886       if (ShrAmt > ShAmtC) {
887         // If C1 > C: (X >>? C1) << C --> (X >>? (C1 - C)) & (-1 << C)
888         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
889         auto *OldShr = cast<BinaryOperator>(Op0);
890         auto *NewShr =
891             BinaryOperator::Create(OldShr->getOpcode(), X, ShiftDiff);
892         NewShr->setIsExact(OldShr->isExact());
893         Builder.Insert(NewShr);
894         APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
895         return BinaryOperator::CreateAnd(NewShr, ConstantInt::get(Ty, Mask));
896       }
897     }
898 
899     // Similar to above, but look through an intermediate trunc instruction.
900     BinaryOperator *Shr;
901     if (match(Op0, m_OneUse(m_Trunc(m_OneUse(m_BinOp(Shr))))) &&
902         match(Shr, m_Shr(m_Value(X), m_APInt(C1)))) {
903       // The larger shift direction survives through the transform.
904       unsigned ShrAmtC = C1->getZExtValue();
905       unsigned ShDiff = ShrAmtC > ShAmtC ? ShrAmtC - ShAmtC : ShAmtC - ShrAmtC;
906       Constant *ShiftDiffC = ConstantInt::get(X->getType(), ShDiff);
907       auto ShiftOpc = ShrAmtC > ShAmtC ? Shr->getOpcode() : Instruction::Shl;
908 
909       // If C1 > C:
910       // (trunc (X >> C1)) << C --> (trunc (X >> (C1 - C))) && (-1 << C)
911       // If C > C1:
912       // (trunc (X >> C1)) << C --> (trunc (X << (C - C1))) && (-1 << C)
913       Value *NewShift = Builder.CreateBinOp(ShiftOpc, X, ShiftDiffC, "sh.diff");
914       Value *Trunc = Builder.CreateTrunc(NewShift, Ty, "tr.sh.diff");
915       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmtC));
916       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, Mask));
917     }
918 
919     if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
920       unsigned AmtSum = ShAmtC + C1->getZExtValue();
921       // Oversized shifts are simplified to zero in InstSimplify.
922       if (AmtSum < BitWidth)
923         // (X << C1) << C2 --> X << (C1 + C2)
924         return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
925     }
926 
927     // If we have an opposite shift by the same amount, we may be able to
928     // reorder binops and shifts to eliminate math/logic.
929     auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
930       switch (BinOpcode) {
931       default:
932         return false;
933       case Instruction::Add:
934       case Instruction::And:
935       case Instruction::Or:
936       case Instruction::Xor:
937       case Instruction::Sub:
938         // NOTE: Sub is not commutable and the tranforms below may not be valid
939         //       when the shift-right is operand 1 (RHS) of the sub.
940         return true;
941       }
942     };
943     BinaryOperator *Op0BO;
944     if (match(Op0, m_OneUse(m_BinOp(Op0BO))) &&
945         isSuitableBinOpcode(Op0BO->getOpcode())) {
946       // Commute so shift-right is on LHS of the binop.
947       // (Y bop (X >> C)) << C         ->  ((X >> C) bop Y) << C
948       // (Y bop ((X >> C) & CC)) << C  ->  (((X >> C) & CC) bop Y) << C
949       Value *Shr = Op0BO->getOperand(0);
950       Value *Y = Op0BO->getOperand(1);
951       Value *X;
952       const APInt *CC;
953       if (Op0BO->isCommutative() && Y->hasOneUse() &&
954           (match(Y, m_Shr(m_Value(), m_Specific(Op1))) ||
955            match(Y, m_And(m_OneUse(m_Shr(m_Value(), m_Specific(Op1))),
956                           m_APInt(CC)))))
957         std::swap(Shr, Y);
958 
959       // ((X >> C) bop Y) << C  ->  (X bop (Y << C)) & (~0 << C)
960       if (match(Shr, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
961         // Y << C
962         Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
963         // (X bop (Y << C))
964         Value *B =
965             Builder.CreateBinOp(Op0BO->getOpcode(), X, YS, Shr->getName());
966         unsigned Op1Val = C->getLimitedValue(BitWidth);
967         APInt Bits = APInt::getHighBitsSet(BitWidth, BitWidth - Op1Val);
968         Constant *Mask = ConstantInt::get(Ty, Bits);
969         return BinaryOperator::CreateAnd(B, Mask);
970       }
971 
972       // (((X >> C) & CC) bop Y) << C  ->  (X & (CC << C)) bop (Y << C)
973       if (match(Shr,
974                 m_OneUse(m_And(m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))),
975                                m_APInt(CC))))) {
976         // Y << C
977         Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
978         // X & (CC << C)
979         Value *M = Builder.CreateAnd(X, ConstantInt::get(Ty, CC->shl(*C)),
980                                      X->getName() + ".mask");
981         return BinaryOperator::Create(Op0BO->getOpcode(), M, YS);
982       }
983     }
984 
985     // (C1 - X) << C --> (C1 << C) - (X << C)
986     if (match(Op0, m_OneUse(m_Sub(m_APInt(C1), m_Value(X))))) {
987       Constant *NewLHS = ConstantInt::get(Ty, C1->shl(*C));
988       Value *NewShift = Builder.CreateShl(X, Op1);
989       return BinaryOperator::CreateSub(NewLHS, NewShift);
990     }
991 
992     // If the shifted-out value is known-zero, then this is a NUW shift.
993     if (!I.hasNoUnsignedWrap() &&
994         MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmtC), 0,
995                           &I)) {
996       I.setHasNoUnsignedWrap();
997       return &I;
998     }
999 
1000     // If the shifted-out value is all signbits, then this is a NSW shift.
1001     if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmtC) {
1002       I.setHasNoSignedWrap();
1003       return &I;
1004     }
1005   }
1006 
1007   // Transform  (x >> y) << y  to  x & (-1 << y)
1008   // Valid for any type of right-shift.
1009   Value *X;
1010   if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1011     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1012     Value *Mask = Builder.CreateShl(AllOnes, Op1);
1013     return BinaryOperator::CreateAnd(Mask, X);
1014   }
1015 
1016   Constant *C1;
1017   if (match(Op1, m_Constant(C1))) {
1018     Constant *C2;
1019     Value *X;
1020     // (X * C2) << C1 --> X * (C2 << C1)
1021     if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
1022       return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
1023 
1024     // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1025     if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1026       auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1);
1027       return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1028     }
1029   }
1030 
1031   // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1032   if (match(Op0, m_One()) &&
1033       match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1034     return BinaryOperator::CreateLShr(
1035         ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
1036 
1037   return nullptr;
1038 }
1039 
1040 Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1041   if (Value *V = simplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1042                                   SQ.getWithInstruction(&I)))
1043     return replaceInstUsesWith(I, V);
1044 
1045   if (Instruction *X = foldVectorBinop(I))
1046     return X;
1047 
1048   if (Instruction *R = commonShiftTransforms(I))
1049     return R;
1050 
1051   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1052   Type *Ty = I.getType();
1053   const APInt *C;
1054   if (match(Op1, m_APInt(C))) {
1055     unsigned ShAmtC = C->getZExtValue();
1056     unsigned BitWidth = Ty->getScalarSizeInBits();
1057     auto *II = dyn_cast<IntrinsicInst>(Op0);
1058     if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmtC &&
1059         (II->getIntrinsicID() == Intrinsic::ctlz ||
1060          II->getIntrinsicID() == Intrinsic::cttz ||
1061          II->getIntrinsicID() == Intrinsic::ctpop)) {
1062       // ctlz.i32(x)>>5  --> zext(x == 0)
1063       // cttz.i32(x)>>5  --> zext(x == 0)
1064       // ctpop.i32(x)>>5 --> zext(x == -1)
1065       bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1066       Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1067       Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1068       return new ZExtInst(Cmp, Ty);
1069     }
1070 
1071     Value *X;
1072     const APInt *C1;
1073     if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1074       if (C1->ult(ShAmtC)) {
1075         unsigned ShlAmtC = C1->getZExtValue();
1076         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShlAmtC);
1077         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1078           // (X <<nuw C1) >>u C --> X >>u (C - C1)
1079           auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1080           NewLShr->setIsExact(I.isExact());
1081           return NewLShr;
1082         }
1083         if (Op0->hasOneUse()) {
1084           // (X << C1) >>u C  --> (X >>u (C - C1)) & (-1 >> C)
1085           Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1086           APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1087           return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1088         }
1089       } else if (C1->ugt(ShAmtC)) {
1090         unsigned ShlAmtC = C1->getZExtValue();
1091         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmtC - ShAmtC);
1092         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1093           // (X <<nuw C1) >>u C --> X <<nuw (C1 - C)
1094           auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1095           NewShl->setHasNoUnsignedWrap(true);
1096           return NewShl;
1097         }
1098         if (Op0->hasOneUse()) {
1099           // (X << C1) >>u C  --> X << (C1 - C) & (-1 >> C)
1100           Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1101           APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1102           return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1103         }
1104       } else {
1105         assert(*C1 == ShAmtC);
1106         // (X << C) >>u C --> X & (-1 >>u C)
1107         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1108         return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1109       }
1110     }
1111 
1112     // ((X << C) + Y) >>u C --> (X + (Y >>u C)) & (-1 >>u C)
1113     // TODO: Consolidate with the more general transform that starts from shl
1114     //       (the shifts are in the opposite order).
1115     Value *Y;
1116     if (match(Op0,
1117               m_OneUse(m_c_Add(m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))),
1118                                m_Value(Y))))) {
1119       Value *NewLshr = Builder.CreateLShr(Y, Op1);
1120       Value *NewAdd = Builder.CreateAdd(NewLshr, X);
1121       unsigned Op1Val = C->getLimitedValue(BitWidth);
1122       APInt Bits = APInt::getLowBitsSet(BitWidth, BitWidth - Op1Val);
1123       Constant *Mask = ConstantInt::get(Ty, Bits);
1124       return BinaryOperator::CreateAnd(NewAdd, Mask);
1125     }
1126 
1127     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1128         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1129       assert(ShAmtC < X->getType()->getScalarSizeInBits() &&
1130              "Big shift not simplified to zero?");
1131       // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1132       Value *NewLShr = Builder.CreateLShr(X, ShAmtC);
1133       return new ZExtInst(NewLShr, Ty);
1134     }
1135 
1136     if (match(Op0, m_SExt(m_Value(X)))) {
1137       unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1138       // lshr (sext i1 X to iN), C --> select (X, -1 >> C, 0)
1139       if (SrcTyBitWidth == 1) {
1140         auto *NewC = ConstantInt::get(
1141             Ty, APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1142         return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1143       }
1144 
1145       if ((!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType())) &&
1146           Op0->hasOneUse()) {
1147         // Are we moving the sign bit to the low bit and widening with high
1148         // zeros? lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1149         if (ShAmtC == BitWidth - 1) {
1150           Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1151           return new ZExtInst(NewLShr, Ty);
1152         }
1153 
1154         // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1155         if (ShAmtC == BitWidth - SrcTyBitWidth) {
1156           // The new shift amount can't be more than the narrow source type.
1157           unsigned NewShAmt = std::min(ShAmtC, SrcTyBitWidth - 1);
1158           Value *AShr = Builder.CreateAShr(X, NewShAmt);
1159           return new ZExtInst(AShr, Ty);
1160         }
1161       }
1162     }
1163 
1164     if (ShAmtC == BitWidth - 1) {
1165       // lshr i32 or(X,-X), 31 --> zext (X != 0)
1166       if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1167         return new ZExtInst(Builder.CreateIsNotNull(X), Ty);
1168 
1169       // lshr i32 (X -nsw Y), 31 --> zext (X < Y)
1170       if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1171         return new ZExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1172 
1173       // Check if a number is negative and odd:
1174       // lshr i32 (srem X, 2), 31 --> and (X >> 31), X
1175       if (match(Op0, m_OneUse(m_SRem(m_Value(X), m_SpecificInt(2))))) {
1176         Value *Signbit = Builder.CreateLShr(X, ShAmtC);
1177         return BinaryOperator::CreateAnd(Signbit, X);
1178       }
1179     }
1180 
1181     // (X >>u C1) >>u C --> X >>u (C1 + C)
1182     if (match(Op0, m_LShr(m_Value(X), m_APInt(C1)))) {
1183       // Oversized shifts are simplified to zero in InstSimplify.
1184       unsigned AmtSum = ShAmtC + C1->getZExtValue();
1185       if (AmtSum < BitWidth)
1186         return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
1187     }
1188 
1189     Instruction *TruncSrc;
1190     if (match(Op0, m_OneUse(m_Trunc(m_Instruction(TruncSrc)))) &&
1191         match(TruncSrc, m_LShr(m_Value(X), m_APInt(C1)))) {
1192       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1193       unsigned AmtSum = ShAmtC + C1->getZExtValue();
1194 
1195       // If the combined shift fits in the source width:
1196       // (trunc (X >>u C1)) >>u C --> and (trunc (X >>u (C1 + C)), MaskC
1197       //
1198       // If the first shift covers the number of bits truncated, then the
1199       // mask instruction is eliminated (and so the use check is relaxed).
1200       if (AmtSum < SrcWidth &&
1201           (TruncSrc->hasOneUse() || C1->uge(SrcWidth - BitWidth))) {
1202         Value *SumShift = Builder.CreateLShr(X, AmtSum, "sum.shift");
1203         Value *Trunc = Builder.CreateTrunc(SumShift, Ty, I.getName());
1204 
1205         // If the first shift does not cover the number of bits truncated, then
1206         // we require a mask to get rid of high bits in the result.
1207         APInt MaskC = APInt::getAllOnes(BitWidth).lshr(ShAmtC);
1208         return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, MaskC));
1209       }
1210     }
1211 
1212     const APInt *MulC;
1213     if (match(Op0, m_NUWMul(m_Value(X), m_APInt(MulC)))) {
1214       // Look for a "splat" mul pattern - it replicates bits across each half of
1215       // a value, so a right shift is just a mask of the low bits:
1216       // lshr i[2N] (mul nuw X, (2^N)+1), N --> and iN X, (2^N)-1
1217       // TODO: Generalize to allow more than just half-width shifts?
1218       if (BitWidth > 2 && ShAmtC * 2 == BitWidth && (*MulC - 1).isPowerOf2() &&
1219           MulC->logBase2() == ShAmtC)
1220         return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, *MulC - 2));
1221 
1222       // The one-use check is not strictly necessary, but codegen may not be
1223       // able to invert the transform and perf may suffer with an extra mul
1224       // instruction.
1225       if (Op0->hasOneUse()) {
1226         APInt NewMulC = MulC->lshr(ShAmtC);
1227         // if c is divisible by (1 << ShAmtC):
1228         // lshr (mul nuw x, MulC), ShAmtC -> mul nuw x, (MulC >> ShAmtC)
1229         if (MulC->eq(NewMulC.shl(ShAmtC))) {
1230           auto *NewMul =
1231               BinaryOperator::CreateNUWMul(X, ConstantInt::get(Ty, NewMulC));
1232           BinaryOperator *OrigMul = cast<BinaryOperator>(Op0);
1233           NewMul->setHasNoSignedWrap(OrigMul->hasNoSignedWrap());
1234           return NewMul;
1235         }
1236       }
1237     }
1238 
1239     // Try to narrow bswap.
1240     // In the case where the shift amount equals the bitwidth difference, the
1241     // shift is eliminated.
1242     if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::bswap>(
1243                        m_OneUse(m_ZExt(m_Value(X))))))) {
1244       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1245       unsigned WidthDiff = BitWidth - SrcWidth;
1246       if (SrcWidth % 16 == 0) {
1247         Value *NarrowSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1248         if (ShAmtC >= WidthDiff) {
1249           // (bswap (zext X)) >> C --> zext (bswap X >> C')
1250           Value *NewShift = Builder.CreateLShr(NarrowSwap, ShAmtC - WidthDiff);
1251           return new ZExtInst(NewShift, Ty);
1252         } else {
1253           // (bswap (zext X)) >> C --> (zext (bswap X)) << C'
1254           Value *NewZExt = Builder.CreateZExt(NarrowSwap, Ty);
1255           Constant *ShiftDiff = ConstantInt::get(Ty, WidthDiff - ShAmtC);
1256           return BinaryOperator::CreateShl(NewZExt, ShiftDiff);
1257         }
1258       }
1259     }
1260 
1261     // If the shifted-out value is known-zero, then this is an exact shift.
1262     if (!I.isExact() &&
1263         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmtC), 0, &I)) {
1264       I.setIsExact();
1265       return &I;
1266     }
1267   }
1268 
1269   // Transform  (x << y) >> y  to  x & (-1 >> y)
1270   Value *X;
1271   if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1272     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1273     Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1274     return BinaryOperator::CreateAnd(Mask, X);
1275   }
1276 
1277   return nullptr;
1278 }
1279 
1280 Instruction *
1281 InstCombinerImpl::foldVariableSignZeroExtensionOfVariableHighBitExtract(
1282     BinaryOperator &OldAShr) {
1283   assert(OldAShr.getOpcode() == Instruction::AShr &&
1284          "Must be called with arithmetic right-shift instruction only.");
1285 
1286   // Check that constant C is a splat of the element-wise bitwidth of V.
1287   auto BitWidthSplat = [](Constant *C, Value *V) {
1288     return match(
1289         C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1290                               APInt(C->getType()->getScalarSizeInBits(),
1291                                     V->getType()->getScalarSizeInBits())));
1292   };
1293 
1294   // It should look like variable-length sign-extension on the outside:
1295   //   (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1296   Value *NBits;
1297   Instruction *MaybeTrunc;
1298   Constant *C1, *C2;
1299   if (!match(&OldAShr,
1300              m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1301                           m_ZExtOrSelf(m_Sub(m_Constant(C1),
1302                                              m_ZExtOrSelf(m_Value(NBits))))),
1303                     m_ZExtOrSelf(m_Sub(m_Constant(C2),
1304                                        m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1305       !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1306     return nullptr;
1307 
1308   // There may or may not be a truncation after outer two shifts.
1309   Instruction *HighBitExtract;
1310   match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1311   bool HadTrunc = MaybeTrunc != HighBitExtract;
1312 
1313   // And finally, the innermost part of the pattern must be a right-shift.
1314   Value *X, *NumLowBitsToSkip;
1315   if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1316     return nullptr;
1317 
1318   // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1319   Constant *C0;
1320   if (!match(NumLowBitsToSkip,
1321              m_ZExtOrSelf(
1322                  m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1323       !BitWidthSplat(C0, HighBitExtract))
1324     return nullptr;
1325 
1326   // Since the NBits is identical for all shifts, if the outermost and
1327   // innermost shifts are identical, then outermost shifts are redundant.
1328   // If we had truncation, do keep it though.
1329   if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1330     return replaceInstUsesWith(OldAShr, MaybeTrunc);
1331 
1332   // Else, if there was a truncation, then we need to ensure that one
1333   // instruction will go away.
1334   if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1335     return nullptr;
1336 
1337   // Finally, bypass two innermost shifts, and perform the outermost shift on
1338   // the operands of the innermost shift.
1339   Instruction *NewAShr =
1340       BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1341   NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1342   if (!HadTrunc)
1343     return NewAShr;
1344 
1345   Builder.Insert(NewAShr);
1346   return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1347 }
1348 
1349 Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
1350   if (Value *V = simplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1351                                   SQ.getWithInstruction(&I)))
1352     return replaceInstUsesWith(I, V);
1353 
1354   if (Instruction *X = foldVectorBinop(I))
1355     return X;
1356 
1357   if (Instruction *R = commonShiftTransforms(I))
1358     return R;
1359 
1360   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1361   Type *Ty = I.getType();
1362   unsigned BitWidth = Ty->getScalarSizeInBits();
1363   const APInt *ShAmtAPInt;
1364   if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1365     unsigned ShAmt = ShAmtAPInt->getZExtValue();
1366 
1367     // If the shift amount equals the difference in width of the destination
1368     // and source scalar types:
1369     // ashr (shl (zext X), C), C --> sext X
1370     Value *X;
1371     if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1372         ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1373       return new SExtInst(X, Ty);
1374 
1375     // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1376     // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1377     const APInt *ShOp1;
1378     if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1379         ShOp1->ult(BitWidth)) {
1380       unsigned ShlAmt = ShOp1->getZExtValue();
1381       if (ShlAmt < ShAmt) {
1382         // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1383         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1384         auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1385         NewAShr->setIsExact(I.isExact());
1386         return NewAShr;
1387       }
1388       if (ShlAmt > ShAmt) {
1389         // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1390         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1391         auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1392         NewShl->setHasNoSignedWrap(true);
1393         return NewShl;
1394       }
1395     }
1396 
1397     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1398         ShOp1->ult(BitWidth)) {
1399       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1400       // Oversized arithmetic shifts replicate the sign bit.
1401       AmtSum = std::min(AmtSum, BitWidth - 1);
1402       // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1403       return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1404     }
1405 
1406     if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1407         (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1408       // ashr (sext X), C --> sext (ashr X, C')
1409       Type *SrcTy = X->getType();
1410       ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1411       Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1412       return new SExtInst(NewSh, Ty);
1413     }
1414 
1415     if (ShAmt == BitWidth - 1) {
1416       // ashr i32 or(X,-X), 31 --> sext (X != 0)
1417       if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1418         return new SExtInst(Builder.CreateIsNotNull(X), Ty);
1419 
1420       // ashr i32 (X -nsw Y), 31 --> sext (X < Y)
1421       Value *Y;
1422       if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1423         return new SExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1424     }
1425 
1426     // If the shifted-out value is known-zero, then this is an exact shift.
1427     if (!I.isExact() &&
1428         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1429       I.setIsExact();
1430       return &I;
1431     }
1432   }
1433 
1434   // Prefer `-(x & 1)` over `(x << (bitwidth(x)-1)) a>> (bitwidth(x)-1)`
1435   // as the pattern to splat the lowest bit.
1436   // FIXME: iff X is already masked, we don't need the one-use check.
1437   Value *X;
1438   if (match(Op1, m_SpecificIntAllowUndef(BitWidth - 1)) &&
1439       match(Op0, m_OneUse(m_Shl(m_Value(X),
1440                                 m_SpecificIntAllowUndef(BitWidth - 1))))) {
1441     Constant *Mask = ConstantInt::get(Ty, 1);
1442     // Retain the knowledge about the ignored lanes.
1443     Mask = Constant::mergeUndefsWith(
1444         Constant::mergeUndefsWith(Mask, cast<Constant>(Op1)),
1445         cast<Constant>(cast<Instruction>(Op0)->getOperand(1)));
1446     X = Builder.CreateAnd(X, Mask);
1447     return BinaryOperator::CreateNeg(X);
1448   }
1449 
1450   if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I))
1451     return R;
1452 
1453   // See if we can turn a signed shr into an unsigned shr.
1454   if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1455     return BinaryOperator::CreateLShr(Op0, Op1);
1456 
1457   // ashr (xor %x, -1), %y  -->  xor (ashr %x, %y), -1
1458   if (match(Op0, m_OneUse(m_Not(m_Value(X))))) {
1459     // Note that we must drop 'exact'-ness of the shift!
1460     // Note that we can't keep undef's in -1 vector constant!
1461     auto *NewAShr = Builder.CreateAShr(X, Op1, Op0->getName() + ".not");
1462     return BinaryOperator::CreateNot(NewAShr);
1463   }
1464 
1465   return nullptr;
1466 }
1467