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   // We can't mutate something that has multiple uses: doing so would
485   // require duplicating the instruction in general, which isn't profitable.
486   if (!I->hasOneUse()) return false;
487 
488   switch (I->getOpcode()) {
489   default: return false;
490   case Instruction::And:
491   case Instruction::Or:
492   case Instruction::Xor:
493     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
494     return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
495            canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
496 
497   case Instruction::Shl:
498   case Instruction::LShr:
499     return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
500 
501   case Instruction::Select: {
502     SelectInst *SI = cast<SelectInst>(I);
503     Value *TrueVal = SI->getTrueValue();
504     Value *FalseVal = SI->getFalseValue();
505     return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
506            canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
507   }
508   case Instruction::PHI: {
509     // We can change a phi if we can change all operands.  Note that we never
510     // get into trouble with cyclic PHIs here because we only consider
511     // instructions with a single use.
512     PHINode *PN = cast<PHINode>(I);
513     for (Value *IncValue : PN->incoming_values())
514       if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
515         return false;
516     return true;
517   }
518   }
519 }
520 
521 /// Fold OuterShift (InnerShift X, C1), C2.
522 /// See canEvaluateShiftedShift() for the constraints on these instructions.
523 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
524                                bool IsOuterShl,
525                                InstCombiner::BuilderTy &Builder) {
526   bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
527   Type *ShType = InnerShift->getType();
528   unsigned TypeWidth = ShType->getScalarSizeInBits();
529 
530   // We only accept shifts-by-a-constant in canEvaluateShifted().
531   const APInt *C1;
532   match(InnerShift->getOperand(1), m_APInt(C1));
533   unsigned InnerShAmt = C1->getZExtValue();
534 
535   // Change the shift amount and clear the appropriate IR flags.
536   auto NewInnerShift = [&](unsigned ShAmt) {
537     InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
538     if (IsInnerShl) {
539       InnerShift->setHasNoUnsignedWrap(false);
540       InnerShift->setHasNoSignedWrap(false);
541     } else {
542       InnerShift->setIsExact(false);
543     }
544     return InnerShift;
545   };
546 
547   // Two logical shifts in the same direction:
548   // shl (shl X, C1), C2 -->  shl X, C1 + C2
549   // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
550   if (IsInnerShl == IsOuterShl) {
551     // If this is an oversized composite shift, then unsigned shifts get 0.
552     if (InnerShAmt + OuterShAmt >= TypeWidth)
553       return Constant::getNullValue(ShType);
554 
555     return NewInnerShift(InnerShAmt + OuterShAmt);
556   }
557 
558   // Equal shift amounts in opposite directions become bitwise 'and':
559   // lshr (shl X, C), C --> and X, C'
560   // shl (lshr X, C), C --> and X, C'
561   if (InnerShAmt == OuterShAmt) {
562     APInt Mask = IsInnerShl
563                      ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
564                      : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
565     Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
566                                    ConstantInt::get(ShType, Mask));
567     if (auto *AndI = dyn_cast<Instruction>(And)) {
568       AndI->moveBefore(InnerShift);
569       AndI->takeName(InnerShift);
570     }
571     return And;
572   }
573 
574   assert(InnerShAmt > OuterShAmt &&
575          "Unexpected opposite direction logical shift pair");
576 
577   // In general, we would need an 'and' for this transform, but
578   // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
579   // lshr (shl X, C1), C2 -->  shl X, C1 - C2
580   // shl (lshr X, C1), C2 --> lshr X, C1 - C2
581   return NewInnerShift(InnerShAmt - OuterShAmt);
582 }
583 
584 /// When canEvaluateShifted() returns true for an expression, this function
585 /// inserts the new computation that produces the shifted value.
586 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
587                               InstCombinerImpl &IC, const DataLayout &DL) {
588   // We can always evaluate constants shifted.
589   if (Constant *C = dyn_cast<Constant>(V)) {
590     if (isLeftShift)
591       return IC.Builder.CreateShl(C, NumBits);
592     else
593       return IC.Builder.CreateLShr(C, NumBits);
594   }
595 
596   Instruction *I = cast<Instruction>(V);
597   IC.addToWorklist(I);
598 
599   switch (I->getOpcode()) {
600   default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
601   case Instruction::And:
602   case Instruction::Or:
603   case Instruction::Xor:
604     // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
605     I->setOperand(
606         0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
607     I->setOperand(
608         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
609     return I;
610 
611   case Instruction::Shl:
612   case Instruction::LShr:
613     return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
614                             IC.Builder);
615 
616   case Instruction::Select:
617     I->setOperand(
618         1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
619     I->setOperand(
620         2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
621     return I;
622   case Instruction::PHI: {
623     // We can change a phi if we can change all operands.  Note that we never
624     // get into trouble with cyclic PHIs here because we only consider
625     // instructions with a single use.
626     PHINode *PN = cast<PHINode>(I);
627     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
628       PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
629                                               isLeftShift, IC, DL));
630     return PN;
631   }
632   }
633 }
634 
635 // If this is a bitwise operator or add with a constant RHS we might be able
636 // to pull it through a shift.
637 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
638                                          BinaryOperator *BO) {
639   switch (BO->getOpcode()) {
640   default:
641     return false; // Do not perform transform!
642   case Instruction::Add:
643     return Shift.getOpcode() == Instruction::Shl;
644   case Instruction::Or:
645   case Instruction::And:
646     return true;
647   case Instruction::Xor:
648     // Do not change a 'not' of logical shift because that would create a normal
649     // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
650     return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
651   }
652 }
653 
654 Instruction *InstCombinerImpl::FoldShiftByConstant(Value *Op0, Constant *Op1,
655                                                    BinaryOperator &I) {
656   bool isLeftShift = I.getOpcode() == Instruction::Shl;
657 
658   const APInt *Op1C;
659   if (!match(Op1, m_APInt(Op1C)))
660     return nullptr;
661 
662   // See if we can propagate this shift into the input, this covers the trivial
663   // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
664   if (I.getOpcode() != Instruction::AShr &&
665       canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
666     LLVM_DEBUG(
667         dbgs() << "ICE: GetShiftedValue propagating shift through expression"
668                   " to eliminate shift:\n  IN: "
669                << *Op0 << "\n  SH: " << I << "\n");
670 
671     return replaceInstUsesWith(
672         I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
673   }
674 
675   // See if we can simplify any instructions used by the instruction whose sole
676   // purpose is to compute bits we don't care about.
677   unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
678 
679   assert(!Op1C->uge(TypeBits) &&
680          "Shift over the type width should have been removed already");
681 
682   if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
683     return FoldedShift;
684 
685   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
686   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
687     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
688     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
689     // place.  Don't try to do this transformation in this case.  Also, we
690     // require that the input operand is a shift-by-constant so that we have
691     // confidence that the shifts will get folded together.  We could do this
692     // xform in more cases, but it is unlikely to be profitable.
693     if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
694         isa<ConstantInt>(TrOp->getOperand(1))) {
695       // Okay, we'll do this xform.  Make the shift of shift.
696       Constant *ShAmt =
697           ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
698       // (shift2 (shift1 & 0x00FF), c2)
699       Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName());
700 
701       // For logical shifts, the truncation has the effect of making the high
702       // part of the register be zeros.  Emulate this by inserting an AND to
703       // clear the top bits as needed.  This 'and' will usually be zapped by
704       // other xforms later if dead.
705       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
706       unsigned DstSize = TI->getType()->getScalarSizeInBits();
707       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
708 
709       // The mask we constructed says what the trunc would do if occurring
710       // between the shifts.  We want to know the effect *after* the second
711       // shift.  We know that it is a logical shift by a constant, so adjust the
712       // mask as appropriate.
713       if (I.getOpcode() == Instruction::Shl)
714         MaskV <<= Op1C->getZExtValue();
715       else {
716         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
717         MaskV.lshrInPlace(Op1C->getZExtValue());
718       }
719 
720       // shift1 & 0x00FF
721       Value *And = Builder.CreateAnd(NSh,
722                                      ConstantInt::get(I.getContext(), MaskV),
723                                      TI->getName());
724 
725       // Return the value truncated to the interesting size.
726       return new TruncInst(And, I.getType());
727     }
728   }
729 
730   if (Op0->hasOneUse()) {
731     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
732       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
733       Value *V1;
734       ConstantInt *CC;
735       switch (Op0BO->getOpcode()) {
736       default: break;
737       case Instruction::Add:
738       case Instruction::And:
739       case Instruction::Or:
740       case Instruction::Xor: {
741         // These operators commute.
742         // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
743         if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
744             match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
745                   m_Specific(Op1)))) {
746           Value *YS =         // (Y << C)
747             Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
748           // (X + (Y << C))
749           Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1,
750                                          Op0BO->getOperand(1)->getName());
751           unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
752 
753           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
754           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
755           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
756             Mask = ConstantVector::getSplat(VT->getElementCount(), Mask);
757           return BinaryOperator::CreateAnd(X, Mask);
758         }
759 
760         // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
761         Value *Op0BOOp1 = Op0BO->getOperand(1);
762         if (isLeftShift && Op0BOOp1->hasOneUse() &&
763             match(Op0BOOp1,
764                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
765                         m_ConstantInt(CC)))) {
766           Value *YS =   // (Y << C)
767             Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
768           // X & (CC << C)
769           Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
770                                         V1->getName()+".mask");
771           return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
772         }
773         LLVM_FALLTHROUGH;
774       }
775 
776       case Instruction::Sub: {
777         // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
778         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
779             match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
780                   m_Specific(Op1)))) {
781           Value *YS =  // (Y << C)
782             Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
783           // (X + (Y << C))
784           Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS,
785                                          Op0BO->getOperand(0)->getName());
786           unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
787 
788           APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
789           Constant *Mask = ConstantInt::get(I.getContext(), Bits);
790           if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
791             Mask = ConstantVector::getSplat(VT->getElementCount(), Mask);
792           return BinaryOperator::CreateAnd(X, Mask);
793         }
794 
795         // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
796         if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
797             match(Op0BO->getOperand(0),
798                   m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
799                         m_ConstantInt(CC)))) {
800           Value *YS = // (Y << C)
801               Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
802           // X & (CC << C)
803           Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
804                                         V1->getName() + ".mask");
805           return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
806         }
807 
808         break;
809       }
810       }
811 
812       // If the operand is a bitwise operator with a constant RHS, and the
813       // shift is the only use, we can pull it out of the shift.
814       const APInt *Op0C;
815       if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
816         if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
817           Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
818                                      cast<Constant>(Op0BO->getOperand(1)), Op1);
819 
820           Value *NewShift =
821             Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
822           NewShift->takeName(Op0BO);
823 
824           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
825                                         NewRHS);
826         }
827       }
828 
829       // If the operand is a subtract with a constant LHS, and the shift
830       // is the only use, we can pull it out of the shift.
831       // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2))
832       if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub &&
833           match(Op0BO->getOperand(0), m_APInt(Op0C))) {
834         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
835                                    cast<Constant>(Op0BO->getOperand(0)), Op1);
836 
837         Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1);
838         NewShift->takeName(Op0BO);
839 
840         return BinaryOperator::CreateSub(NewRHS, NewShift);
841       }
842     }
843 
844     // If we have a select that conditionally executes some binary operator,
845     // see if we can pull it the select and operator through the shift.
846     //
847     // For example, turning:
848     //   shl (select C, (add X, C1), X), C2
849     // Into:
850     //   Y = shl X, C2
851     //   select C, (add Y, C1 << C2), Y
852     Value *Cond;
853     BinaryOperator *TBO;
854     Value *FalseVal;
855     if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
856                             m_Value(FalseVal)))) {
857       const APInt *C;
858       if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
859           match(TBO->getOperand(1), m_APInt(C)) &&
860           canShiftBinOpWithConstantRHS(I, TBO)) {
861         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
862                                        cast<Constant>(TBO->getOperand(1)), Op1);
863 
864         Value *NewShift =
865           Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1);
866         Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift,
867                                            NewRHS);
868         return SelectInst::Create(Cond, NewOp, NewShift);
869       }
870     }
871 
872     BinaryOperator *FBO;
873     Value *TrueVal;
874     if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
875                             m_OneUse(m_BinOp(FBO))))) {
876       const APInt *C;
877       if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
878           match(FBO->getOperand(1), m_APInt(C)) &&
879           canShiftBinOpWithConstantRHS(I, FBO)) {
880         Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
881                                        cast<Constant>(FBO->getOperand(1)), Op1);
882 
883         Value *NewShift =
884           Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1);
885         Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift,
886                                            NewRHS);
887         return SelectInst::Create(Cond, NewShift, NewOp);
888       }
889     }
890   }
891 
892   return nullptr;
893 }
894 
895 Instruction *InstCombinerImpl::visitShl(BinaryOperator &I) {
896   const SimplifyQuery Q = SQ.getWithInstruction(&I);
897 
898   if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
899                                  I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
900     return replaceInstUsesWith(I, V);
901 
902   if (Instruction *X = foldVectorBinop(I))
903     return X;
904 
905   if (Instruction *V = commonShiftTransforms(I))
906     return V;
907 
908   if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder))
909     return V;
910 
911   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
912   Type *Ty = I.getType();
913   unsigned BitWidth = Ty->getScalarSizeInBits();
914 
915   const APInt *ShAmtAPInt;
916   if (match(Op1, m_APInt(ShAmtAPInt))) {
917     unsigned ShAmt = ShAmtAPInt->getZExtValue();
918 
919     // shl (zext X), ShAmt --> zext (shl X, ShAmt)
920     // This is only valid if X would have zeros shifted out.
921     Value *X;
922     if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
923       unsigned SrcWidth = X->getType()->getScalarSizeInBits();
924       if (ShAmt < SrcWidth &&
925           MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
926         return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty);
927     }
928 
929     // (X >> C) << C --> X & (-1 << C)
930     if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
931       APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
932       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
933     }
934 
935     // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine)
936     // needs a few fixes for the rotate pattern recognition first.
937     const APInt *ShOp1;
938     if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) {
939       unsigned ShrAmt = ShOp1->getZExtValue();
940       if (ShrAmt < ShAmt) {
941         // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
942         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt);
943         auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
944         NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
945         NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
946         return NewShl;
947       }
948       if (ShrAmt > ShAmt) {
949         // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2)
950         Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt);
951         auto *NewShr = BinaryOperator::Create(
952             cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
953         NewShr->setIsExact(true);
954         return NewShr;
955       }
956     }
957 
958     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) {
959       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
960       // Oversized shifts are simplified to zero in InstSimplify.
961       if (AmtSum < BitWidth)
962         // (X << C1) << C2 --> X << (C1 + C2)
963         return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
964     }
965 
966     // If the shifted-out value is known-zero, then this is a NUW shift.
967     if (!I.hasNoUnsignedWrap() &&
968         MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
969       I.setHasNoUnsignedWrap();
970       return &I;
971     }
972 
973     // If the shifted-out value is all signbits, then this is a NSW shift.
974     if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
975       I.setHasNoSignedWrap();
976       return &I;
977     }
978   }
979 
980   // Transform  (x >> y) << y  to  x & (-1 << y)
981   // Valid for any type of right-shift.
982   Value *X;
983   if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
984     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
985     Value *Mask = Builder.CreateShl(AllOnes, Op1);
986     return BinaryOperator::CreateAnd(Mask, X);
987   }
988 
989   Constant *C1;
990   if (match(Op1, m_Constant(C1))) {
991     Constant *C2;
992     Value *X;
993     // (C2 << X) << C1 --> (C2 << C1) << X
994     if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X)))))
995       return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X);
996 
997     // (X * C2) << C1 --> X * (C2 << C1)
998     if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
999       return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
1000 
1001     // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1002     if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1003       auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1);
1004       return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty));
1005     }
1006   }
1007 
1008   // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1009   if (match(Op0, m_One()) &&
1010       match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1011     return BinaryOperator::CreateLShr(
1012         ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
1013 
1014   return nullptr;
1015 }
1016 
1017 Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1018   if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1019                                   SQ.getWithInstruction(&I)))
1020     return replaceInstUsesWith(I, V);
1021 
1022   if (Instruction *X = foldVectorBinop(I))
1023     return X;
1024 
1025   if (Instruction *R = commonShiftTransforms(I))
1026     return R;
1027 
1028   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1029   Type *Ty = I.getType();
1030   const APInt *ShAmtAPInt;
1031   if (match(Op1, m_APInt(ShAmtAPInt))) {
1032     unsigned ShAmt = ShAmtAPInt->getZExtValue();
1033     unsigned BitWidth = Ty->getScalarSizeInBits();
1034     auto *II = dyn_cast<IntrinsicInst>(Op0);
1035     if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
1036         (II->getIntrinsicID() == Intrinsic::ctlz ||
1037          II->getIntrinsicID() == Intrinsic::cttz ||
1038          II->getIntrinsicID() == Intrinsic::ctpop)) {
1039       // ctlz.i32(x)>>5  --> zext(x == 0)
1040       // cttz.i32(x)>>5  --> zext(x == 0)
1041       // ctpop.i32(x)>>5 --> zext(x == -1)
1042       bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1043       Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1044       Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1045       return new ZExtInst(Cmp, Ty);
1046     }
1047 
1048     Value *X;
1049     const APInt *ShOp1;
1050     if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) {
1051       if (ShOp1->ult(ShAmt)) {
1052         unsigned ShlAmt = ShOp1->getZExtValue();
1053         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1054         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1055           // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
1056           auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1057           NewLShr->setIsExact(I.isExact());
1058           return NewLShr;
1059         }
1060         // (X << C1) >>u C2  --> (X >>u (C2 - C1)) & (-1 >> C2)
1061         Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1062         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1063         return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1064       }
1065       if (ShOp1->ugt(ShAmt)) {
1066         unsigned ShlAmt = ShOp1->getZExtValue();
1067         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1068         if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1069           // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2)
1070           auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1071           NewShl->setHasNoUnsignedWrap(true);
1072           return NewShl;
1073         }
1074         // (X << C1) >>u C2  --> X << (C1 - C2) & (-1 >> C2)
1075         Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1076         APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1077         return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1078       }
1079       assert(*ShOp1 == ShAmt);
1080       // (X << C) >>u C --> X & (-1 >>u C)
1081       APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
1082       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1083     }
1084 
1085     if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1086         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1087       assert(ShAmt < X->getType()->getScalarSizeInBits() &&
1088              "Big shift not simplified to zero?");
1089       // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1090       Value *NewLShr = Builder.CreateLShr(X, ShAmt);
1091       return new ZExtInst(NewLShr, Ty);
1092     }
1093 
1094     if (match(Op0, m_SExt(m_Value(X))) &&
1095         (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1096       // Are we moving the sign bit to the low bit and widening with high zeros?
1097       unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1098       if (ShAmt == BitWidth - 1) {
1099         // lshr (sext i1 X to iN), N-1 --> zext X to iN
1100         if (SrcTyBitWidth == 1)
1101           return new ZExtInst(X, Ty);
1102 
1103         // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1104         if (Op0->hasOneUse()) {
1105           Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1106           return new ZExtInst(NewLShr, Ty);
1107         }
1108       }
1109 
1110       // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1111       if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) {
1112         // The new shift amount can't be more than the narrow source type.
1113         unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1);
1114         Value *AShr = Builder.CreateAShr(X, NewShAmt);
1115         return new ZExtInst(AShr, Ty);
1116       }
1117     }
1118 
1119     if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) {
1120       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1121       // Oversized shifts are simplified to zero in InstSimplify.
1122       if (AmtSum < BitWidth)
1123         // (X >>u C1) >>u C2 --> X >>u (C1 + C2)
1124         return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
1125     }
1126 
1127     // If the shifted-out value is known-zero, then this is an exact shift.
1128     if (!I.isExact() &&
1129         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1130       I.setIsExact();
1131       return &I;
1132     }
1133   }
1134 
1135   // Transform  (x << y) >> y  to  x & (-1 >> y)
1136   Value *X;
1137   if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1138     Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1139     Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1140     return BinaryOperator::CreateAnd(Mask, X);
1141   }
1142 
1143   return nullptr;
1144 }
1145 
1146 Instruction *
1147 InstCombinerImpl::foldVariableSignZeroExtensionOfVariableHighBitExtract(
1148     BinaryOperator &OldAShr) {
1149   assert(OldAShr.getOpcode() == Instruction::AShr &&
1150          "Must be called with arithmetic right-shift instruction only.");
1151 
1152   // Check that constant C is a splat of the element-wise bitwidth of V.
1153   auto BitWidthSplat = [](Constant *C, Value *V) {
1154     return match(
1155         C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1156                               APInt(C->getType()->getScalarSizeInBits(),
1157                                     V->getType()->getScalarSizeInBits())));
1158   };
1159 
1160   // It should look like variable-length sign-extension on the outside:
1161   //   (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1162   Value *NBits;
1163   Instruction *MaybeTrunc;
1164   Constant *C1, *C2;
1165   if (!match(&OldAShr,
1166              m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1167                           m_ZExtOrSelf(m_Sub(m_Constant(C1),
1168                                              m_ZExtOrSelf(m_Value(NBits))))),
1169                     m_ZExtOrSelf(m_Sub(m_Constant(C2),
1170                                        m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1171       !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1172     return nullptr;
1173 
1174   // There may or may not be a truncation after outer two shifts.
1175   Instruction *HighBitExtract;
1176   match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1177   bool HadTrunc = MaybeTrunc != HighBitExtract;
1178 
1179   // And finally, the innermost part of the pattern must be a right-shift.
1180   Value *X, *NumLowBitsToSkip;
1181   if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1182     return nullptr;
1183 
1184   // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1185   Constant *C0;
1186   if (!match(NumLowBitsToSkip,
1187              m_ZExtOrSelf(
1188                  m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1189       !BitWidthSplat(C0, HighBitExtract))
1190     return nullptr;
1191 
1192   // Since the NBits is identical for all shifts, if the outermost and
1193   // innermost shifts are identical, then outermost shifts are redundant.
1194   // If we had truncation, do keep it though.
1195   if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1196     return replaceInstUsesWith(OldAShr, MaybeTrunc);
1197 
1198   // Else, if there was a truncation, then we need to ensure that one
1199   // instruction will go away.
1200   if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1201     return nullptr;
1202 
1203   // Finally, bypass two innermost shifts, and perform the outermost shift on
1204   // the operands of the innermost shift.
1205   Instruction *NewAShr =
1206       BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1207   NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1208   if (!HadTrunc)
1209     return NewAShr;
1210 
1211   Builder.Insert(NewAShr);
1212   return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1213 }
1214 
1215 Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
1216   if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1217                                   SQ.getWithInstruction(&I)))
1218     return replaceInstUsesWith(I, V);
1219 
1220   if (Instruction *X = foldVectorBinop(I))
1221     return X;
1222 
1223   if (Instruction *R = commonShiftTransforms(I))
1224     return R;
1225 
1226   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1227   Type *Ty = I.getType();
1228   unsigned BitWidth = Ty->getScalarSizeInBits();
1229   const APInt *ShAmtAPInt;
1230   if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1231     unsigned ShAmt = ShAmtAPInt->getZExtValue();
1232 
1233     // If the shift amount equals the difference in width of the destination
1234     // and source scalar types:
1235     // ashr (shl (zext X), C), C --> sext X
1236     Value *X;
1237     if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1238         ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1239       return new SExtInst(X, Ty);
1240 
1241     // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1242     // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1243     const APInt *ShOp1;
1244     if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1245         ShOp1->ult(BitWidth)) {
1246       unsigned ShlAmt = ShOp1->getZExtValue();
1247       if (ShlAmt < ShAmt) {
1248         // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1249         Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1250         auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1251         NewAShr->setIsExact(I.isExact());
1252         return NewAShr;
1253       }
1254       if (ShlAmt > ShAmt) {
1255         // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1256         Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1257         auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1258         NewShl->setHasNoSignedWrap(true);
1259         return NewShl;
1260       }
1261     }
1262 
1263     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1264         ShOp1->ult(BitWidth)) {
1265       unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1266       // Oversized arithmetic shifts replicate the sign bit.
1267       AmtSum = std::min(AmtSum, BitWidth - 1);
1268       // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1269       return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1270     }
1271 
1272     if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1273         (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1274       // ashr (sext X), C --> sext (ashr X, C')
1275       Type *SrcTy = X->getType();
1276       ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1277       Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1278       return new SExtInst(NewSh, Ty);
1279     }
1280 
1281     // If the shifted-out value is known-zero, then this is an exact shift.
1282     if (!I.isExact() &&
1283         MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1284       I.setIsExact();
1285       return &I;
1286     }
1287   }
1288 
1289   if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I))
1290     return R;
1291 
1292   // See if we can turn a signed shr into an unsigned shr.
1293   if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1294     return BinaryOperator::CreateLShr(Op0, Op1);
1295 
1296   return nullptr;
1297 }
1298