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