[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-core.git] / lib / Transforms / InstCombine / InstCombineShifts.cpp
blobb451beebd0f35d208f73dab98c944425bead3792
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.
11 //===----------------------------------------------------------------------===//
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/ConstantFolding.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/IntrinsicInst.h"
17 #include "llvm/IR/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
21 #define DEBUG_TYPE "instcombine"
23 // Given pattern:
24 // (x shiftopcode Q) shiftopcode K
25 // we should rewrite it as
26 // x shiftopcode (Q+K) iff (Q+K) u< bitwidth(x)
27 // This is valid for any shift, but they must be identical.
28 static Instruction *
29 reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0,
30 const SimplifyQuery &SQ,
31 InstCombiner::BuilderTy &Builder) {
32 // Look for a shift of some instruction, ignore zext of shift amount if any.
33 Instruction *Sh0Op0;
34 Value *ShAmt0;
35 if (!match(Sh0,
36 m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0)))))
37 return nullptr;
39 // If there is a truncation between the two shifts, we must make note of it
40 // and look through it. The truncation imposes additional constraints on the
41 // transform.
42 Instruction *Sh1;
43 Value *Trunc = nullptr;
44 match(Sh0Op0,
45 m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)),
46 m_Instruction(Sh1)));
48 // Inner shift: (x shiftopcode ShAmt1)
49 // Like with other shift, ignore zext of shift amount if any.
50 Value *X, *ShAmt1;
51 if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1)))))
52 return nullptr;
54 // We have two shift amounts from two different shifts. The types of those
55 // shift amounts may not match. If that's the case let's bailout now..
56 if (ShAmt0->getType() != ShAmt1->getType())
57 return nullptr;
59 // The shift opcodes must be identical.
60 Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
61 if (ShiftOpcode != Sh1->getOpcode())
62 return nullptr;
64 // Did we match a pattern with truncation ?
65 if (Trunc) {
66 // For right-shifts we can't do any such simplifications. Leave as-is.
67 if (ShiftOpcode != Instruction::BinaryOps::Shl)
68 return nullptr; // FIXME: still could perform constant-folding.
69 // If we saw truncation, we'll need to produce extra instruction,
70 // and for that one of the operands of the shift must be one-use.
71 if (!match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
72 return nullptr;
75 // Can we fold (ShAmt0+ShAmt1) ?
76 auto *NewShAmt = dyn_cast_or_null<Constant>(
77 SimplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
78 SQ.getWithInstruction(Sh0)));
79 if (!NewShAmt)
80 return nullptr; // Did not simplify.
81 // Is the new shift amount smaller than the bit width of inner shift?
82 if (!match(NewShAmt, m_SpecificInt_ICMP(
83 ICmpInst::Predicate::ICMP_ULT,
84 APInt(NewShAmt->getType()->getScalarSizeInBits(),
85 X->getType()->getScalarSizeInBits()))))
86 return nullptr; // FIXME: could perform constant-folding.
88 // All good, we can do this fold.
89 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
91 BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
93 // The flags can only be propagated if there wasn't a trunc.
94 if (!Trunc) {
95 // If the pattern did not involve trunc, and both of the original shifts
96 // had the same flag set, preserve the flag.
97 if (ShiftOpcode == Instruction::BinaryOps::Shl) {
98 NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
99 Sh1->hasNoUnsignedWrap());
100 NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
101 Sh1->hasNoSignedWrap());
102 } else {
103 NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
107 Instruction *Ret = NewShift;
108 if (Trunc) {
109 Builder.Insert(NewShift);
110 Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
113 return Ret;
116 // If we have some pattern that leaves only some low bits set, and then performs
117 // left-shift of those bits, if none of the bits that are left after the final
118 // shift are modified by the mask, we can omit the mask.
120 // There are many variants to this pattern:
121 // a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
122 // b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt
123 // c) (x & (-1 >> MaskShAmt)) << ShiftShAmt
124 // d) (x & ((-1 << MaskShAmt) >> MaskShAmt)) << ShiftShAmt
125 // e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
126 // f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
127 // All these patterns can be simplified to just:
128 // x << ShiftShAmt
129 // iff:
130 // a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
131 // c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
132 static Instruction *
133 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
134 const SimplifyQuery &SQ) {
135 assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
136 "The input must be 'shl'!");
138 Value *Masked = OuterShift->getOperand(0);
139 Value *ShiftShAmt = OuterShift->getOperand(1);
141 Value *MaskShAmt;
143 // ((1 << MaskShAmt) - 1)
144 auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
145 // (~(-1 << maskNbits))
146 auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
147 // (-1 >> MaskShAmt)
148 auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt));
149 // ((-1 << MaskShAmt) >> MaskShAmt)
150 auto MaskD =
151 m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
153 Value *X;
154 if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
155 // Can we simplify (MaskShAmt+ShiftShAmt) ?
156 Value *SumOfShAmts =
157 SimplifyAddInst(MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
158 SQ.getWithInstruction(OuterShift));
159 if (!SumOfShAmts)
160 return nullptr; // Did not simplify.
161 // Is the total shift amount *not* smaller than the bit width?
162 // FIXME: could also rely on ConstantRange.
163 unsigned BitWidth = X->getType()->getScalarSizeInBits();
164 if (!match(SumOfShAmts, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_UGE,
165 APInt(BitWidth, BitWidth))))
166 return nullptr;
167 // All good, we can do this fold.
168 } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
169 match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
170 m_Deferred(MaskShAmt)))) {
171 // Can we simplify (ShiftShAmt-MaskShAmt) ?
172 Value *ShAmtsDiff =
173 SimplifySubInst(ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false,
174 SQ.getWithInstruction(OuterShift));
175 if (!ShAmtsDiff)
176 return nullptr; // Did not simplify.
177 // Is the difference non-negative? (is ShiftShAmt u>= MaskShAmt ?)
178 // FIXME: could also rely on ConstantRange.
179 if (!match(ShAmtsDiff, m_NonNegative()))
180 return nullptr;
181 // All good, we can do this fold.
182 } else
183 return nullptr; // Don't know anything about this pattern.
185 // No 'NUW'/'NSW'!
186 // We no longer know that we won't shift-out non-0 bits.
187 return BinaryOperator::Create(OuterShift->getOpcode(), X, ShiftShAmt);
190 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
191 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
192 assert(Op0->getType() == Op1->getType());
194 // See if we can fold away this shift.
195 if (SimplifyDemandedInstructionBits(I))
196 return &I;
198 // Try to fold constant and into select arguments.
199 if (isa<Constant>(Op0))
200 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
201 if (Instruction *R = FoldOpIntoSelect(I, SI))
202 return R;
204 if (Constant *CUI = dyn_cast<Constant>(Op1))
205 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
206 return Res;
208 if (Instruction *NewShift =
209 reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ, Builder))
210 return NewShift;
212 // (C1 shift (A add C2)) -> (C1 shift C2) shift A)
213 // iff A and C2 are both positive.
214 Value *A;
215 Constant *C;
216 if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C))))
217 if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) &&
218 isKnownNonNegative(C, DL, 0, &AC, &I, &DT))
219 return BinaryOperator::Create(
220 I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A);
222 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2.
223 // Because shifts by negative values (which could occur if A were negative)
224 // are undefined.
225 const APInt *B;
226 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) {
227 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
228 // demand the sign bit (and many others) here??
229 Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1),
230 Op1->getName());
231 I.setOperand(1, Rem);
232 return &I;
235 return nullptr;
238 /// Return true if we can simplify two logical (either left or right) shifts
239 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
240 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
241 Instruction *InnerShift, InstCombiner &IC,
242 Instruction *CxtI) {
243 assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
245 // We need constant scalar or constant splat shifts.
246 const APInt *InnerShiftConst;
247 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
248 return false;
250 // Two logical shifts in the same direction:
251 // shl (shl X, C1), C2 --> shl X, C1 + C2
252 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
253 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
254 if (IsInnerShl == IsOuterShl)
255 return true;
257 // Equal shift amounts in opposite directions become bitwise 'and':
258 // lshr (shl X, C), C --> and X, C'
259 // shl (lshr X, C), C --> and X, C'
260 if (*InnerShiftConst == OuterShAmt)
261 return true;
263 // If the 2nd shift is bigger than the 1st, we can fold:
264 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
265 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
266 // but it isn't profitable unless we know the and'd out bits are already zero.
267 // Also, check that the inner shift is valid (less than the type width) or
268 // we'll crash trying to produce the bit mask for the 'and'.
269 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
270 if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
271 unsigned InnerShAmt = InnerShiftConst->getZExtValue();
272 unsigned MaskShift =
273 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
274 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
275 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
276 return true;
279 return false;
282 /// See if we can compute the specified value, but shifted logically to the left
283 /// or right by some number of bits. This should return true if the expression
284 /// can be computed for the same cost as the current expression tree. This is
285 /// used to eliminate extraneous shifting from things like:
286 /// %C = shl i128 %A, 64
287 /// %D = shl i128 %B, 96
288 /// %E = or i128 %C, %D
289 /// %F = lshr i128 %E, 64
290 /// where the client will ask if E can be computed shifted right by 64-bits. If
291 /// this succeeds, getShiftedValue() will be called to produce the value.
292 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
293 InstCombiner &IC, Instruction *CxtI) {
294 // We can always evaluate constants shifted.
295 if (isa<Constant>(V))
296 return true;
298 Instruction *I = dyn_cast<Instruction>(V);
299 if (!I) return false;
301 // If this is the opposite shift, we can directly reuse the input of the shift
302 // if the needed bits are already zero in the input. This allows us to reuse
303 // the value which means that we don't care if the shift has multiple uses.
304 // TODO: Handle opposite shift by exact value.
305 ConstantInt *CI = nullptr;
306 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) ||
307 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) {
308 if (CI->getValue() == NumBits) {
309 // TODO: Check that the input bits are already zero with MaskedValueIsZero
310 #if 0
311 // If this is a truncate of a logical shr, we can truncate it to a smaller
312 // lshr iff we know that the bits we would otherwise be shifting in are
313 // already zeros.
314 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
315 uint32_t BitWidth = Ty->getScalarSizeInBits();
316 if (MaskedValueIsZero(I->getOperand(0),
317 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
318 CI->getLimitedValue(BitWidth) < BitWidth) {
319 return CanEvaluateTruncated(I->getOperand(0), Ty);
321 #endif
326 // We can't mutate something that has multiple uses: doing so would
327 // require duplicating the instruction in general, which isn't profitable.
328 if (!I->hasOneUse()) return false;
330 switch (I->getOpcode()) {
331 default: return false;
332 case Instruction::And:
333 case Instruction::Or:
334 case Instruction::Xor:
335 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
336 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
337 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
339 case Instruction::Shl:
340 case Instruction::LShr:
341 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
343 case Instruction::Select: {
344 SelectInst *SI = cast<SelectInst>(I);
345 Value *TrueVal = SI->getTrueValue();
346 Value *FalseVal = SI->getFalseValue();
347 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
348 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
350 case Instruction::PHI: {
351 // We can change a phi if we can change all operands. Note that we never
352 // get into trouble with cyclic PHIs here because we only consider
353 // instructions with a single use.
354 PHINode *PN = cast<PHINode>(I);
355 for (Value *IncValue : PN->incoming_values())
356 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
357 return false;
358 return true;
363 /// Fold OuterShift (InnerShift X, C1), C2.
364 /// See canEvaluateShiftedShift() for the constraints on these instructions.
365 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
366 bool IsOuterShl,
367 InstCombiner::BuilderTy &Builder) {
368 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
369 Type *ShType = InnerShift->getType();
370 unsigned TypeWidth = ShType->getScalarSizeInBits();
372 // We only accept shifts-by-a-constant in canEvaluateShifted().
373 const APInt *C1;
374 match(InnerShift->getOperand(1), m_APInt(C1));
375 unsigned InnerShAmt = C1->getZExtValue();
377 // Change the shift amount and clear the appropriate IR flags.
378 auto NewInnerShift = [&](unsigned ShAmt) {
379 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
380 if (IsInnerShl) {
381 InnerShift->setHasNoUnsignedWrap(false);
382 InnerShift->setHasNoSignedWrap(false);
383 } else {
384 InnerShift->setIsExact(false);
386 return InnerShift;
389 // Two logical shifts in the same direction:
390 // shl (shl X, C1), C2 --> shl X, C1 + C2
391 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
392 if (IsInnerShl == IsOuterShl) {
393 // If this is an oversized composite shift, then unsigned shifts get 0.
394 if (InnerShAmt + OuterShAmt >= TypeWidth)
395 return Constant::getNullValue(ShType);
397 return NewInnerShift(InnerShAmt + OuterShAmt);
400 // Equal shift amounts in opposite directions become bitwise 'and':
401 // lshr (shl X, C), C --> and X, C'
402 // shl (lshr X, C), C --> and X, C'
403 if (InnerShAmt == OuterShAmt) {
404 APInt Mask = IsInnerShl
405 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
406 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
407 Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
408 ConstantInt::get(ShType, Mask));
409 if (auto *AndI = dyn_cast<Instruction>(And)) {
410 AndI->moveBefore(InnerShift);
411 AndI->takeName(InnerShift);
413 return And;
416 assert(InnerShAmt > OuterShAmt &&
417 "Unexpected opposite direction logical shift pair");
419 // In general, we would need an 'and' for this transform, but
420 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
421 // lshr (shl X, C1), C2 --> shl X, C1 - C2
422 // shl (lshr X, C1), C2 --> lshr X, C1 - C2
423 return NewInnerShift(InnerShAmt - OuterShAmt);
426 /// When canEvaluateShifted() returns true for an expression, this function
427 /// inserts the new computation that produces the shifted value.
428 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
429 InstCombiner &IC, const DataLayout &DL) {
430 // We can always evaluate constants shifted.
431 if (Constant *C = dyn_cast<Constant>(V)) {
432 if (isLeftShift)
433 V = IC.Builder.CreateShl(C, NumBits);
434 else
435 V = IC.Builder.CreateLShr(C, NumBits);
436 // If we got a constantexpr back, try to simplify it with TD info.
437 if (auto *C = dyn_cast<Constant>(V))
438 if (auto *FoldedC =
439 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo()))
440 V = FoldedC;
441 return V;
444 Instruction *I = cast<Instruction>(V);
445 IC.Worklist.Add(I);
447 switch (I->getOpcode()) {
448 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
449 case Instruction::And:
450 case Instruction::Or:
451 case Instruction::Xor:
452 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
453 I->setOperand(
454 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
455 I->setOperand(
456 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
457 return I;
459 case Instruction::Shl:
460 case Instruction::LShr:
461 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
462 IC.Builder);
464 case Instruction::Select:
465 I->setOperand(
466 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
467 I->setOperand(
468 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
469 return I;
470 case Instruction::PHI: {
471 // We can change a phi if we can change all operands. Note that we never
472 // get into trouble with cyclic PHIs here because we only consider
473 // instructions with a single use.
474 PHINode *PN = cast<PHINode>(I);
475 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
476 PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits,
477 isLeftShift, IC, DL));
478 return PN;
483 // If this is a bitwise operator or add with a constant RHS we might be able
484 // to pull it through a shift.
485 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
486 BinaryOperator *BO) {
487 switch (BO->getOpcode()) {
488 default:
489 return false; // Do not perform transform!
490 case Instruction::Add:
491 return Shift.getOpcode() == Instruction::Shl;
492 case Instruction::Or:
493 case Instruction::Xor:
494 case Instruction::And:
495 return true;
499 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1,
500 BinaryOperator &I) {
501 bool isLeftShift = I.getOpcode() == Instruction::Shl;
503 const APInt *Op1C;
504 if (!match(Op1, m_APInt(Op1C)))
505 return nullptr;
507 // See if we can propagate this shift into the input, this covers the trivial
508 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
509 if (I.getOpcode() != Instruction::AShr &&
510 canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) {
511 LLVM_DEBUG(
512 dbgs() << "ICE: GetShiftedValue propagating shift through expression"
513 " to eliminate shift:\n IN: "
514 << *Op0 << "\n SH: " << I << "\n");
516 return replaceInstUsesWith(
517 I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL));
520 // See if we can simplify any instructions used by the instruction whose sole
521 // purpose is to compute bits we don't care about.
522 unsigned TypeBits = Op0->getType()->getScalarSizeInBits();
524 assert(!Op1C->uge(TypeBits) &&
525 "Shift over the type width should have been removed already");
527 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
528 return FoldedShift;
530 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
531 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
532 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
533 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
534 // place. Don't try to do this transformation in this case. Also, we
535 // require that the input operand is a shift-by-constant so that we have
536 // confidence that the shifts will get folded together. We could do this
537 // xform in more cases, but it is unlikely to be profitable.
538 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
539 isa<ConstantInt>(TrOp->getOperand(1))) {
540 // Okay, we'll do this xform. Make the shift of shift.
541 Constant *ShAmt =
542 ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType());
543 // (shift2 (shift1 & 0x00FF), c2)
544 Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName());
546 // For logical shifts, the truncation has the effect of making the high
547 // part of the register be zeros. Emulate this by inserting an AND to
548 // clear the top bits as needed. This 'and' will usually be zapped by
549 // other xforms later if dead.
550 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
551 unsigned DstSize = TI->getType()->getScalarSizeInBits();
552 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
554 // The mask we constructed says what the trunc would do if occurring
555 // between the shifts. We want to know the effect *after* the second
556 // shift. We know that it is a logical shift by a constant, so adjust the
557 // mask as appropriate.
558 if (I.getOpcode() == Instruction::Shl)
559 MaskV <<= Op1C->getZExtValue();
560 else {
561 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
562 MaskV.lshrInPlace(Op1C->getZExtValue());
565 // shift1 & 0x00FF
566 Value *And = Builder.CreateAnd(NSh,
567 ConstantInt::get(I.getContext(), MaskV),
568 TI->getName());
570 // Return the value truncated to the interesting size.
571 return new TruncInst(And, I.getType());
575 if (Op0->hasOneUse()) {
576 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
577 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
578 Value *V1, *V2;
579 ConstantInt *CC;
580 switch (Op0BO->getOpcode()) {
581 default: break;
582 case Instruction::Add:
583 case Instruction::And:
584 case Instruction::Or:
585 case Instruction::Xor: {
586 // These operators commute.
587 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
588 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
589 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
590 m_Specific(Op1)))) {
591 Value *YS = // (Y << C)
592 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
593 // (X + (Y << C))
594 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1,
595 Op0BO->getOperand(1)->getName());
596 unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
598 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
599 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
600 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
601 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
602 return BinaryOperator::CreateAnd(X, Mask);
605 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
606 Value *Op0BOOp1 = Op0BO->getOperand(1);
607 if (isLeftShift && Op0BOOp1->hasOneUse() &&
608 match(Op0BOOp1,
609 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))),
610 m_ConstantInt(CC)))) {
611 Value *YS = // (Y << C)
612 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
613 // X & (CC << C)
614 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
615 V1->getName()+".mask");
616 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
618 LLVM_FALLTHROUGH;
621 case Instruction::Sub: {
622 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
623 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
624 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
625 m_Specific(Op1)))) {
626 Value *YS = // (Y << C)
627 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
628 // (X + (Y << C))
629 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS,
630 Op0BO->getOperand(0)->getName());
631 unsigned Op1Val = Op1C->getLimitedValue(TypeBits);
633 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val);
634 Constant *Mask = ConstantInt::get(I.getContext(), Bits);
635 if (VectorType *VT = dyn_cast<VectorType>(X->getType()))
636 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask);
637 return BinaryOperator::CreateAnd(X, Mask);
640 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
641 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
642 match(Op0BO->getOperand(0),
643 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))),
644 m_ConstantInt(CC))) && V2 == Op1) {
645 Value *YS = // (Y << C)
646 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
647 // X & (CC << C)
648 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
649 V1->getName()+".mask");
651 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
654 break;
659 // If the operand is a bitwise operator with a constant RHS, and the
660 // shift is the only use, we can pull it out of the shift.
661 const APInt *Op0C;
662 if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
663 if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
664 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
665 cast<Constant>(Op0BO->getOperand(1)), Op1);
667 Value *NewShift =
668 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
669 NewShift->takeName(Op0BO);
671 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
672 NewRHS);
676 // If the operand is a subtract with a constant LHS, and the shift
677 // is the only use, we can pull it out of the shift.
678 // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2))
679 if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub &&
680 match(Op0BO->getOperand(0), m_APInt(Op0C))) {
681 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
682 cast<Constant>(Op0BO->getOperand(0)), Op1);
684 Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1);
685 NewShift->takeName(Op0BO);
687 return BinaryOperator::CreateSub(NewRHS, NewShift);
691 // If we have a select that conditionally executes some binary operator,
692 // see if we can pull it the select and operator through the shift.
694 // For example, turning:
695 // shl (select C, (add X, C1), X), C2
696 // Into:
697 // Y = shl X, C2
698 // select C, (add Y, C1 << C2), Y
699 Value *Cond;
700 BinaryOperator *TBO;
701 Value *FalseVal;
702 if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
703 m_Value(FalseVal)))) {
704 const APInt *C;
705 if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
706 match(TBO->getOperand(1), m_APInt(C)) &&
707 canShiftBinOpWithConstantRHS(I, TBO)) {
708 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
709 cast<Constant>(TBO->getOperand(1)), Op1);
711 Value *NewShift =
712 Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1);
713 Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift,
714 NewRHS);
715 return SelectInst::Create(Cond, NewOp, NewShift);
719 BinaryOperator *FBO;
720 Value *TrueVal;
721 if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
722 m_OneUse(m_BinOp(FBO))))) {
723 const APInt *C;
724 if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
725 match(FBO->getOperand(1), m_APInt(C)) &&
726 canShiftBinOpWithConstantRHS(I, FBO)) {
727 Constant *NewRHS = ConstantExpr::get(I.getOpcode(),
728 cast<Constant>(FBO->getOperand(1)), Op1);
730 Value *NewShift =
731 Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1);
732 Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift,
733 NewRHS);
734 return SelectInst::Create(Cond, NewShift, NewOp);
739 return nullptr;
742 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
743 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1),
744 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
745 SQ.getWithInstruction(&I)))
746 return replaceInstUsesWith(I, V);
748 if (Instruction *X = foldVectorBinop(I))
749 return X;
751 if (Instruction *V = commonShiftTransforms(I))
752 return V;
754 if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, SQ))
755 return V;
757 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
758 Type *Ty = I.getType();
759 unsigned BitWidth = Ty->getScalarSizeInBits();
761 const APInt *ShAmtAPInt;
762 if (match(Op1, m_APInt(ShAmtAPInt))) {
763 unsigned ShAmt = ShAmtAPInt->getZExtValue();
765 // shl (zext X), ShAmt --> zext (shl X, ShAmt)
766 // This is only valid if X would have zeros shifted out.
767 Value *X;
768 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
769 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
770 if (ShAmt < SrcWidth &&
771 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I))
772 return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty);
775 // (X >> C) << C --> X & (-1 << C)
776 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
777 APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt));
778 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
781 // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine)
782 // needs a few fixes for the rotate pattern recognition first.
783 const APInt *ShOp1;
784 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) {
785 unsigned ShrAmt = ShOp1->getZExtValue();
786 if (ShrAmt < ShAmt) {
787 // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1)
788 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt);
789 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
790 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
791 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
792 return NewShl;
794 if (ShrAmt > ShAmt) {
795 // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2)
796 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt);
797 auto *NewShr = BinaryOperator::Create(
798 cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
799 NewShr->setIsExact(true);
800 return NewShr;
804 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) {
805 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
806 // Oversized shifts are simplified to zero in InstSimplify.
807 if (AmtSum < BitWidth)
808 // (X << C1) << C2 --> X << (C1 + C2)
809 return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
812 // If the shifted-out value is known-zero, then this is a NUW shift.
813 if (!I.hasNoUnsignedWrap() &&
814 MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) {
815 I.setHasNoUnsignedWrap();
816 return &I;
819 // If the shifted-out value is all signbits, then this is a NSW shift.
820 if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) {
821 I.setHasNoSignedWrap();
822 return &I;
826 // Transform (x >> y) << y to x & (-1 << y)
827 // Valid for any type of right-shift.
828 Value *X;
829 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
830 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
831 Value *Mask = Builder.CreateShl(AllOnes, Op1);
832 return BinaryOperator::CreateAnd(Mask, X);
835 Constant *C1;
836 if (match(Op1, m_Constant(C1))) {
837 Constant *C2;
838 Value *X;
839 // (C2 << X) << C1 --> (C2 << C1) << X
840 if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X)))))
841 return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X);
843 // (X * C2) << C1 --> X * (C2 << C1)
844 if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
845 return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
848 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
849 if (match(Op0, m_One()) &&
850 match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
851 return BinaryOperator::CreateLShr(
852 ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
854 return nullptr;
857 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
858 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
859 SQ.getWithInstruction(&I)))
860 return replaceInstUsesWith(I, V);
862 if (Instruction *X = foldVectorBinop(I))
863 return X;
865 if (Instruction *R = commonShiftTransforms(I))
866 return R;
868 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
869 Type *Ty = I.getType();
870 const APInt *ShAmtAPInt;
871 if (match(Op1, m_APInt(ShAmtAPInt))) {
872 unsigned ShAmt = ShAmtAPInt->getZExtValue();
873 unsigned BitWidth = Ty->getScalarSizeInBits();
874 auto *II = dyn_cast<IntrinsicInst>(Op0);
875 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt &&
876 (II->getIntrinsicID() == Intrinsic::ctlz ||
877 II->getIntrinsicID() == Intrinsic::cttz ||
878 II->getIntrinsicID() == Intrinsic::ctpop)) {
879 // ctlz.i32(x)>>5 --> zext(x == 0)
880 // cttz.i32(x)>>5 --> zext(x == 0)
881 // ctpop.i32(x)>>5 --> zext(x == -1)
882 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
883 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
884 Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
885 return new ZExtInst(Cmp, Ty);
888 Value *X;
889 const APInt *ShOp1;
890 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) {
891 if (ShOp1->ult(ShAmt)) {
892 unsigned ShlAmt = ShOp1->getZExtValue();
893 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
894 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
895 // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1)
896 auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
897 NewLShr->setIsExact(I.isExact());
898 return NewLShr;
900 // (X << C1) >>u C2 --> (X >>u (C2 - C1)) & (-1 >> C2)
901 Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
902 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
903 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
905 if (ShOp1->ugt(ShAmt)) {
906 unsigned ShlAmt = ShOp1->getZExtValue();
907 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
908 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
909 // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2)
910 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
911 NewShl->setHasNoUnsignedWrap(true);
912 return NewShl;
914 // (X << C1) >>u C2 --> X << (C1 - C2) & (-1 >> C2)
915 Value *NewShl = Builder.CreateShl(X, ShiftDiff);
916 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
917 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
919 assert(*ShOp1 == ShAmt);
920 // (X << C) >>u C --> X & (-1 >>u C)
921 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt));
922 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
925 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
926 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
927 assert(ShAmt < X->getType()->getScalarSizeInBits() &&
928 "Big shift not simplified to zero?");
929 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
930 Value *NewLShr = Builder.CreateLShr(X, ShAmt);
931 return new ZExtInst(NewLShr, Ty);
934 if (match(Op0, m_SExt(m_Value(X))) &&
935 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
936 // Are we moving the sign bit to the low bit and widening with high zeros?
937 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
938 if (ShAmt == BitWidth - 1) {
939 // lshr (sext i1 X to iN), N-1 --> zext X to iN
940 if (SrcTyBitWidth == 1)
941 return new ZExtInst(X, Ty);
943 // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
944 if (Op0->hasOneUse()) {
945 Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
946 return new ZExtInst(NewLShr, Ty);
950 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
951 if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) {
952 // The new shift amount can't be more than the narrow source type.
953 unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1);
954 Value *AShr = Builder.CreateAShr(X, NewShAmt);
955 return new ZExtInst(AShr, Ty);
959 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) {
960 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
961 // Oversized shifts are simplified to zero in InstSimplify.
962 if (AmtSum < BitWidth)
963 // (X >>u C1) >>u C2 --> X >>u (C1 + C2)
964 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
967 // If the shifted-out value is known-zero, then this is an exact shift.
968 if (!I.isExact() &&
969 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
970 I.setIsExact();
971 return &I;
975 // Transform (x << y) >> y to x & (-1 >> y)
976 Value *X;
977 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
978 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
979 Value *Mask = Builder.CreateLShr(AllOnes, Op1);
980 return BinaryOperator::CreateAnd(Mask, X);
983 return nullptr;
986 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
987 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
988 SQ.getWithInstruction(&I)))
989 return replaceInstUsesWith(I, V);
991 if (Instruction *X = foldVectorBinop(I))
992 return X;
994 if (Instruction *R = commonShiftTransforms(I))
995 return R;
997 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
998 Type *Ty = I.getType();
999 unsigned BitWidth = Ty->getScalarSizeInBits();
1000 const APInt *ShAmtAPInt;
1001 if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1002 unsigned ShAmt = ShAmtAPInt->getZExtValue();
1004 // If the shift amount equals the difference in width of the destination
1005 // and source scalar types:
1006 // ashr (shl (zext X), C), C --> sext X
1007 Value *X;
1008 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1009 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1010 return new SExtInst(X, Ty);
1012 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1013 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1014 const APInt *ShOp1;
1015 if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1016 ShOp1->ult(BitWidth)) {
1017 unsigned ShlAmt = ShOp1->getZExtValue();
1018 if (ShlAmt < ShAmt) {
1019 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1020 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1021 auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1022 NewAShr->setIsExact(I.isExact());
1023 return NewAShr;
1025 if (ShlAmt > ShAmt) {
1026 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1027 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1028 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1029 NewShl->setHasNoSignedWrap(true);
1030 return NewShl;
1034 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1035 ShOp1->ult(BitWidth)) {
1036 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1037 // Oversized arithmetic shifts replicate the sign bit.
1038 AmtSum = std::min(AmtSum, BitWidth - 1);
1039 // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1040 return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1043 if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1044 (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1045 // ashr (sext X), C --> sext (ashr X, C')
1046 Type *SrcTy = X->getType();
1047 ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1048 Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1049 return new SExtInst(NewSh, Ty);
1052 // If the shifted-out value is known-zero, then this is an exact shift.
1053 if (!I.isExact() &&
1054 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1055 I.setIsExact();
1056 return &I;
1060 // See if we can turn a signed shr into an unsigned shr.
1061 if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I))
1062 return BinaryOperator::CreateLShr(Op0, Op1);
1064 return nullptr;