1//===- InstCombineShifts.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visitShl, visitLShr, and visitAShr functions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/Analysis/InstructionSimplify.h"
15#include "llvm/IR/IntrinsicInst.h"
16#include "llvm/IR/PatternMatch.h"
17#include "llvm/Transforms/InstCombine/InstCombiner.h"
18using namespace llvm;
19using namespace PatternMatch;
20
21#define DEBUG_TYPE "instcombine"
22
23bool canTryToConstantAddTwoShiftAmounts(Value *Sh0, Value *ShAmt0, Value *Sh1,
24 Value *ShAmt1) {
25 // We have two shift amounts from two different shifts. The types of those
26 // shift amounts may not match. If that's the case let's bailout now..
27 if (ShAmt0->getType() != ShAmt1->getType())
28 return false;
29
30 // As input, we have the following pattern:
31 // Sh0 (Sh1 X, Q), K
32 // We want to rewrite that as:
33 // Sh x, (Q+K) iff (Q+K) u< bitwidth(x)
34 // While we know that originally (Q+K) would not overflow
35 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
36 // shift amounts. so it may now overflow in smaller bitwidth.
37 // To ensure that does not happen, we need to ensure that the total maximal
38 // shift amount is still representable in that smaller bit width.
39 unsigned MaximalPossibleTotalShiftAmount =
40 (Sh0->getType()->getScalarSizeInBits() - 1) +
41 (Sh1->getType()->getScalarSizeInBits() - 1);
42 APInt MaximalRepresentableShiftAmount =
43 APInt::getAllOnes(numBits: ShAmt0->getType()->getScalarSizeInBits());
44 return MaximalRepresentableShiftAmount.uge(RHS: MaximalPossibleTotalShiftAmount);
45}
46
47// Given pattern:
48// (x shiftopcode Q) shiftopcode K
49// we should rewrite it as
50// x shiftopcode (Q+K) iff (Q+K) u< bitwidth(x) and
51//
52// This is valid for any shift, but they must be identical, and we must be
53// careful in case we have (zext(Q)+zext(K)) and look past extensions,
54// (Q+K) must not overflow or else (Q+K) u< bitwidth(x) is bogus.
55//
56// AnalyzeForSignBitExtraction indicates that we will only analyze whether this
57// pattern has any 2 right-shifts that sum to 1 less than original bit width.
58Value *InstCombinerImpl::reassociateShiftAmtsOfTwoSameDirectionShifts(
59 BinaryOperator *Sh0, const SimplifyQuery &SQ,
60 bool AnalyzeForSignBitExtraction) {
61 // Look for a shift of some instruction, ignore zext of shift amount if any.
62 Instruction *Sh0Op0;
63 Value *ShAmt0;
64 if (!match(V: Sh0,
65 P: m_Shift(L: m_Instruction(I&: Sh0Op0), R: m_ZExtOrSelf(Op: m_Value(V&: ShAmt0)))))
66 return nullptr;
67
68 // If there is a truncation between the two shifts, we must make note of it
69 // and look through it. The truncation imposes additional constraints on the
70 // transform.
71 Instruction *Sh1;
72 Value *Trunc = nullptr;
73 match(V: Sh0Op0,
74 P: m_CombineOr(Ps: m_CombineAnd(Ps: m_Trunc(Op: m_Instruction(I&: Sh1)), Ps: m_Value(V&: Trunc)),
75 Ps: m_Instruction(I&: Sh1)));
76
77 // Inner shift: (x shiftopcode ShAmt1)
78 // Like with other shift, ignore zext of shift amount if any.
79 Value *X, *ShAmt1;
80 if (!match(V: Sh1, P: m_Shift(L: m_Value(V&: X), R: m_ZExtOrSelf(Op: m_Value(V&: ShAmt1)))))
81 return nullptr;
82
83 // Verify that it would be safe to try to add those two shift amounts.
84 if (!canTryToConstantAddTwoShiftAmounts(Sh0, ShAmt0, Sh1, ShAmt1))
85 return nullptr;
86
87 // We are only looking for signbit extraction if we have two right shifts.
88 bool HadTwoRightShifts = match(V: Sh0, P: m_Shr(L: m_Value(), R: m_Value())) &&
89 match(V: Sh1, P: m_Shr(L: m_Value(), R: m_Value()));
90 // ... and if it's not two right-shifts, we know the answer already.
91 if (AnalyzeForSignBitExtraction && !HadTwoRightShifts)
92 return nullptr;
93
94 // The shift opcodes must be identical, unless we are just checking whether
95 // this pattern can be interpreted as a sign-bit-extraction.
96 Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode();
97 bool IdenticalShOpcodes = Sh0->getOpcode() == Sh1->getOpcode();
98 if (!IdenticalShOpcodes && !AnalyzeForSignBitExtraction)
99 return nullptr;
100
101 // If we saw truncation, we'll need to produce extra instruction,
102 // and for that one of the operands of the shift must be one-use,
103 // unless of course we don't actually plan to produce any instructions here.
104 if (Trunc && !AnalyzeForSignBitExtraction &&
105 !match(V: Sh0, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Value()), R: m_Value())))
106 return nullptr;
107
108 // Can we fold (ShAmt0+ShAmt1) ?
109 auto *NewShAmt = dyn_cast_or_null<Constant>(
110 Val: simplifyAddInst(LHS: ShAmt0, RHS: ShAmt1, /*isNSW=*/IsNSW: false, /*isNUW=*/IsNUW: false,
111 Q: SQ.getWithInstruction(I: Sh0)));
112 if (!NewShAmt)
113 return nullptr; // Did not simplify.
114 unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits();
115 unsigned XBitWidth = X->getType()->getScalarSizeInBits();
116 // Is the new shift amount smaller than the bit width of inner/new shift?
117 if (!match(V: NewShAmt, P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_ULT,
118 Threshold: APInt(NewShAmtBitWidth, XBitWidth))))
119 return nullptr; // FIXME: could perform constant-folding.
120
121 // If there was a truncation, and we have a right-shift, we can only fold if
122 // we are left with the original sign bit. Likewise, if we were just checking
123 // that this is a sighbit extraction, this is the place to check it.
124 // FIXME: zero shift amount is also legal here, but we can't *easily* check
125 // more than one predicate so it's not really worth it.
126 if (HadTwoRightShifts && (Trunc || AnalyzeForSignBitExtraction)) {
127 // If it's not a sign bit extraction, then we're done.
128 if (!match(V: NewShAmt,
129 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_EQ,
130 Threshold: APInt(NewShAmtBitWidth, XBitWidth - 1))))
131 return nullptr;
132 // If it is, and that was the question, return the base value.
133 if (AnalyzeForSignBitExtraction)
134 return X;
135 }
136
137 assert(IdenticalShOpcodes && "Should not get here with different shifts.");
138
139 if (NewShAmt->getType() != X->getType()) {
140 NewShAmt = ConstantFoldCastOperand(Opcode: Instruction::ZExt, C: NewShAmt,
141 DestTy: X->getType(), DL: SQ.DL);
142 if (!NewShAmt)
143 return nullptr;
144 }
145
146 // All good, we can do this fold.
147 BinaryOperator *NewShift = BinaryOperator::Create(Op: ShiftOpcode, S1: X, S2: NewShAmt);
148
149 // The flags can only be propagated if there wasn't a trunc.
150 if (!Trunc) {
151 // If the pattern did not involve trunc, and both of the original shifts
152 // had the same flag set, preserve the flag.
153 if (ShiftOpcode == Instruction::BinaryOps::Shl) {
154 NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
155 Sh1->hasNoUnsignedWrap());
156 NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
157 Sh1->hasNoSignedWrap());
158 } else {
159 NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
160 }
161 }
162
163 Instruction *Ret = NewShift;
164 if (Trunc) {
165 Builder.Insert(I: NewShift);
166 Ret = CastInst::Create(Instruction::Trunc, S: NewShift, Ty: Sh0->getType());
167 }
168
169 return Ret;
170}
171
172// If we have some pattern that leaves only some low bits set, and then performs
173// left-shift of those bits, if none of the bits that are left after the final
174// shift are modified by the mask, we can omit the mask.
175//
176// There are many variants to this pattern:
177// a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
178// b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt
179// c) (x & (-1 l>> MaskShAmt)) << ShiftShAmt
180// d) (x & ((-1 << MaskShAmt) l>> MaskShAmt)) << ShiftShAmt
181// e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
182// f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
183// All these patterns can be simplified to just:
184// x << ShiftShAmt
185// iff:
186// a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
187// c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
188static Instruction *
189dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift,
190 const SimplifyQuery &Q,
191 InstCombiner::BuilderTy &Builder) {
192 assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
193 "The input must be 'shl'!");
194
195 Value *Masked, *ShiftShAmt;
196 match(V: OuterShift,
197 P: m_Shift(L: m_Value(V&: Masked), R: m_ZExtOrSelf(Op: m_Value(V&: ShiftShAmt))));
198
199 // *If* there is a truncation between an outer shift and a possibly-mask,
200 // then said truncation *must* be one-use, else we can't perform the fold.
201 Value *Trunc;
202 if (match(V: Masked, P: m_CombineAnd(Ps: m_Trunc(Op: m_Value(V&: Masked)), Ps: m_Value(V&: Trunc))) &&
203 !Trunc->hasOneUse())
204 return nullptr;
205
206 Type *NarrowestTy = OuterShift->getType();
207 Type *WidestTy = Masked->getType();
208 bool HadTrunc = WidestTy != NarrowestTy;
209
210 // Check if the type can be extended.
211 if ((WidestTy->getScalarSizeInBits() * 2) > IntegerType::MAX_INT_BITS)
212 return nullptr;
213
214 // The mask must be computed in a type twice as wide to ensure
215 // that no bits are lost if the sum-of-shifts is wider than the base type.
216 Type *ExtendedTy = WidestTy->getExtendedType();
217
218 Value *MaskShAmt;
219
220 // ((1 << MaskShAmt) - 1)
221 auto MaskA = m_Add(L: m_Shl(L: m_One(), R: m_Value(V&: MaskShAmt)), R: m_AllOnes());
222 // (~(-1 << maskNbits))
223 auto MaskB = m_Not(V: m_Shl(L: m_AllOnes(), R: m_Value(V&: MaskShAmt)));
224 // (-1 l>> MaskShAmt)
225 auto MaskC = m_LShr(L: m_AllOnes(), R: m_Value(V&: MaskShAmt));
226 // ((-1 << MaskShAmt) l>> MaskShAmt)
227 auto MaskD =
228 m_LShr(L: m_Shl(L: m_AllOnes(), R: m_Value(V&: MaskShAmt)), R: m_Deferred(V: MaskShAmt));
229
230 Value *X;
231 Constant *NewMask;
232
233 if (match(V: Masked, P: m_c_And(L: m_CombineOr(Ps: MaskA, Ps: MaskB), R: m_Value(V&: X)))) {
234 // Peek through an optional zext of the shift amount.
235 match(V: MaskShAmt, P: m_ZExtOrSelf(Op: m_Value(V&: MaskShAmt)));
236
237 // Verify that it would be safe to try to add those two shift amounts.
238 if (!canTryToConstantAddTwoShiftAmounts(Sh0: OuterShift, ShAmt0: ShiftShAmt, Sh1: Masked,
239 ShAmt1: MaskShAmt))
240 return nullptr;
241
242 // Can we simplify (MaskShAmt+ShiftShAmt) ?
243 auto *SumOfShAmts = dyn_cast_or_null<Constant>(Val: simplifyAddInst(
244 LHS: MaskShAmt, RHS: ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
245 if (!SumOfShAmts)
246 return nullptr; // Did not simplify.
247 // In this pattern SumOfShAmts correlates with the number of low bits
248 // that shall remain in the root value (OuterShift).
249
250 // An extend of an undef value becomes zero because the high bits are never
251 // completely unknown. Replace the `undef` shift amounts with final
252 // shift bitwidth to ensure that the value remains undef when creating the
253 // subsequent shift op.
254 SumOfShAmts = Constant::replaceUndefsWith(
255 C: SumOfShAmts, Replacement: ConstantInt::get(Ty: SumOfShAmts->getType()->getScalarType(),
256 V: ExtendedTy->getScalarSizeInBits()));
257 auto *ExtendedSumOfShAmts = ConstantFoldCastOperand(
258 Opcode: Instruction::ZExt, C: SumOfShAmts, DestTy: ExtendedTy, DL: Q.DL);
259 if (!ExtendedSumOfShAmts)
260 return nullptr;
261
262 // And compute the mask as usual: ~(-1 << (SumOfShAmts))
263 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(Ty: ExtendedTy);
264 Constant *ExtendedInvertedMask = ConstantFoldBinaryOpOperands(
265 Opcode: Instruction::Shl, LHS: ExtendedAllOnes, RHS: ExtendedSumOfShAmts, DL: Q.DL);
266 if (!ExtendedInvertedMask)
267 return nullptr;
268
269 NewMask = ConstantExpr::getNot(C: ExtendedInvertedMask);
270 } else if (match(V: Masked, P: m_c_And(L: m_CombineOr(Ps: MaskC, Ps: MaskD), R: m_Value(V&: X))) ||
271 match(V: Masked, P: m_Shr(L: m_Shl(L: m_Value(V&: X), R: m_Value(V&: MaskShAmt)),
272 R: m_Deferred(V: MaskShAmt)))) {
273 // Peek through an optional zext of the shift amount.
274 match(V: MaskShAmt, P: m_ZExtOrSelf(Op: m_Value(V&: MaskShAmt)));
275
276 // Verify that it would be safe to try to add those two shift amounts.
277 if (!canTryToConstantAddTwoShiftAmounts(Sh0: OuterShift, ShAmt0: ShiftShAmt, Sh1: Masked,
278 ShAmt1: MaskShAmt))
279 return nullptr;
280
281 // Can we simplify (ShiftShAmt-MaskShAmt) ?
282 auto *ShAmtsDiff = dyn_cast_or_null<Constant>(Val: simplifySubInst(
283 LHS: ShiftShAmt, RHS: MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
284 if (!ShAmtsDiff)
285 return nullptr; // Did not simplify.
286 // In this pattern ShAmtsDiff correlates with the number of high bits that
287 // shall be unset in the root value (OuterShift).
288
289 // An extend of an undef value becomes zero because the high bits are never
290 // completely unknown. Replace the `undef` shift amounts with negated
291 // bitwidth of innermost shift to ensure that the value remains undef when
292 // creating the subsequent shift op.
293 unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
294 ShAmtsDiff = Constant::replaceUndefsWith(
295 C: ShAmtsDiff,
296 Replacement: ConstantInt::getSigned(Ty: ShAmtsDiff->getType()->getScalarType(),
297 V: -(int)WidestTyBitWidth));
298 auto *ExtendedNumHighBitsToClear = ConstantFoldCastOperand(
299 Opcode: Instruction::ZExt,
300 C: ConstantExpr::getSub(C1: ConstantInt::get(Ty: ShAmtsDiff->getType(),
301 V: WidestTyBitWidth,
302 /*isSigned=*/IsSigned: false),
303 C2: ShAmtsDiff),
304 DestTy: ExtendedTy, DL: Q.DL);
305 if (!ExtendedNumHighBitsToClear)
306 return nullptr;
307
308 // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
309 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(Ty: ExtendedTy);
310 NewMask = ConstantFoldBinaryOpOperands(Opcode: Instruction::LShr, LHS: ExtendedAllOnes,
311 RHS: ExtendedNumHighBitsToClear, DL: Q.DL);
312 if (!NewMask)
313 return nullptr;
314 } else
315 return nullptr; // Don't know anything about this pattern.
316
317 NewMask = ConstantExpr::getTrunc(C: NewMask, Ty: NarrowestTy);
318
319 // Does this mask has any unset bits? If not then we can just not apply it.
320 bool NeedMask = !match(V: NewMask, P: m_AllOnes());
321
322 // If we need to apply a mask, there are several more restrictions we have.
323 if (NeedMask) {
324 // The old masking instruction must go away.
325 if (!Masked->hasOneUse())
326 return nullptr;
327 // The original "masking" instruction must not have been`ashr`.
328 if (match(V: Masked, P: m_AShr(L: m_Value(), R: m_Value())))
329 return nullptr;
330 }
331
332 // If we need to apply truncation, let's do it first, since we can.
333 // We have already ensured that the old truncation will go away.
334 if (HadTrunc)
335 X = Builder.CreateTrunc(V: X, DestTy: NarrowestTy);
336
337 // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
338 // We didn't change the Type of this outermost shift, so we can just do it.
339 auto *NewShift = BinaryOperator::Create(Op: OuterShift->getOpcode(), S1: X,
340 S2: OuterShift->getOperand(i_nocapture: 1));
341 if (!NeedMask)
342 return NewShift;
343
344 Builder.Insert(I: NewShift);
345 return BinaryOperator::Create(Op: Instruction::And, S1: NewShift, S2: NewMask);
346}
347
348/// If we have a shift-by-constant of a bin op (bitwise logic op or add/sub w/
349/// shl) that itself has a shift-by-constant operand with identical opcode, we
350/// may be able to convert that into 2 independent shifts followed by the logic
351/// op. This eliminates a use of an intermediate value (reduces dependency
352/// chain).
353static Instruction *foldShiftOfShiftedBinOp(BinaryOperator &I,
354 InstCombiner::BuilderTy &Builder) {
355 assert(I.isShift() && "Expected a shift as input");
356 auto *BinInst = dyn_cast<BinaryOperator>(Val: I.getOperand(i_nocapture: 0));
357 if (!BinInst ||
358 (!BinInst->isBitwiseLogicOp() &&
359 BinInst->getOpcode() != Instruction::Add &&
360 BinInst->getOpcode() != Instruction::Sub) ||
361 !BinInst->hasOneUse())
362 return nullptr;
363
364 Constant *C0, *C1;
365 if (!match(V: I.getOperand(i_nocapture: 1), P: m_Constant(C&: C1)))
366 return nullptr;
367
368 Instruction::BinaryOps ShiftOpcode = I.getOpcode();
369 // Transform for add/sub only works with shl.
370 if ((BinInst->getOpcode() == Instruction::Add ||
371 BinInst->getOpcode() == Instruction::Sub) &&
372 ShiftOpcode != Instruction::Shl)
373 return nullptr;
374
375 Type *Ty = I.getType();
376
377 // Find a matching shift by constant. The fold is not valid if the sum
378 // of the shift values equals or exceeds bitwidth.
379 Value *X, *Y;
380 auto matchFirstShift = [&](Value *V, Value *W) {
381 unsigned Size = Ty->getScalarSizeInBits();
382 APInt Threshold(Size, Size);
383 return match(V, P: m_BinOp(Opcode: ShiftOpcode, L: m_Value(V&: X), R: m_Constant(C&: C0))) &&
384 (V->hasOneUse() || match(V: W, P: m_ImmConstant())) &&
385 match(V: ConstantExpr::getAdd(C1: C0, C2: C1),
386 P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_ULT, Threshold));
387 };
388
389 // Logic ops and Add are commutative, so check each operand for a match. Sub
390 // is not so we cannot reoder if we match operand(1) and need to keep the
391 // operands in their original positions.
392 bool FirstShiftIsOp1 = false;
393 if (matchFirstShift(BinInst->getOperand(i_nocapture: 0), BinInst->getOperand(i_nocapture: 1)))
394 Y = BinInst->getOperand(i_nocapture: 1);
395 else if (matchFirstShift(BinInst->getOperand(i_nocapture: 1), BinInst->getOperand(i_nocapture: 0))) {
396 Y = BinInst->getOperand(i_nocapture: 0);
397 FirstShiftIsOp1 = BinInst->getOpcode() == Instruction::Sub;
398 } else
399 return nullptr;
400
401 // shift (binop (shift X, C0), Y), C1 -> binop (shift X, C0+C1), (shift Y, C1)
402 Constant *ShiftSumC = ConstantExpr::getAdd(C1: C0, C2: C1);
403 Value *NewShift1 = Builder.CreateBinOp(Opc: ShiftOpcode, LHS: X, RHS: ShiftSumC);
404 Value *NewShift2 = Builder.CreateBinOp(Opc: ShiftOpcode, LHS: Y, RHS: C1);
405 Value *Op1 = FirstShiftIsOp1 ? NewShift2 : NewShift1;
406 Value *Op2 = FirstShiftIsOp1 ? NewShift1 : NewShift2;
407 return BinaryOperator::Create(Op: BinInst->getOpcode(), S1: Op1, S2: Op2);
408}
409
410Instruction *InstCombinerImpl::commonShiftTransforms(BinaryOperator &I) {
411 if (Instruction *Phi = foldBinopWithPhiOperands(BO&: I))
412 return Phi;
413
414 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
415 assert(Op0->getType() == Op1->getType());
416 Type *Ty = I.getType();
417
418 // If the shift amount is a one-use `sext`, we can demote it to `zext`.
419 Value *Y;
420 if (match(V: Op1, P: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: Y))))) {
421 Value *NewExt = Builder.CreateZExt(V: Y, DestTy: Ty, Name: Op1->getName());
422 return BinaryOperator::Create(Op: I.getOpcode(), S1: Op0, S2: NewExt);
423 }
424
425 // See if we can fold away this shift.
426 if (SimplifyDemandedInstructionBits(Inst&: I))
427 return &I;
428
429 // Try to fold constant and into select arguments.
430 if (isa<Constant>(Val: Op0))
431 if (SelectInst *SI = dyn_cast<SelectInst>(Val: Op1))
432 if (Instruction *R = FoldOpIntoSelect(Op&: I, SI))
433 return R;
434
435 Constant *CUI;
436 if (match(V: Op1, P: m_ImmConstant(C&: CUI)))
437 if (Instruction *Res = FoldShiftByConstant(Op0, Op1: CUI, I))
438 return Res;
439
440 if (auto *NewShift = cast_or_null<Instruction>(
441 Val: reassociateShiftAmtsOfTwoSameDirectionShifts(Sh0: &I, SQ)))
442 return NewShift;
443
444 // Pre-shift a constant shifted by a variable amount with constant offset:
445 // C shift (A add nuw C1) --> (C shift C1) shift A
446 Value *A;
447 Constant *C, *C1;
448 if (match(V: Op0, P: m_Constant(C)) &&
449 match(V: Op1, P: m_NUWAddLike(L: m_Value(V&: A), R: m_Constant(C&: C1)))) {
450 Value *NewC = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: C, RHS: C1);
451 BinaryOperator *NewShiftOp = BinaryOperator::Create(Op: I.getOpcode(), S1: NewC, S2: A);
452 if (I.getOpcode() == Instruction::Shl) {
453 NewShiftOp->setHasNoSignedWrap(I.hasNoSignedWrap());
454 NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
455 } else {
456 NewShiftOp->setIsExact(I.isExact());
457 }
458 return NewShiftOp;
459 }
460
461 unsigned BitWidth = Ty->getScalarSizeInBits();
462
463 const APInt *AC;
464 if (match(V: Op0, P: m_APInt(Res&: AC))) {
465 assert(!AC->isZero() && "Expected simplify of shifted zero");
466
467 // Try to pre-shift a constant shifted by a variable amount added with a
468 // negative number:
469 // C << (X - AddC) --> (C >> AddC) << X
470 // and
471 // C >> (X - AddC) --> (C << AddC) >> X
472 const APInt *AddC;
473 if (match(V: Op1, P: m_Add(L: m_Value(V&: A), R: m_APInt(Res&: AddC))) && AddC->isNegative() &&
474 (-*AddC).ult(RHS: BitWidth)) {
475 unsigned PosOffset = (-*AddC).getZExtValue();
476
477 auto isSuitableForPreShift = [PosOffset, &I, AC]() {
478 switch (I.getOpcode()) {
479 default:
480 return false;
481 case Instruction::Shl:
482 return (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) &&
483 AC->eq(RHS: AC->lshr(shiftAmt: PosOffset).shl(shiftAmt: PosOffset));
484 case Instruction::LShr:
485 return I.isExact() && AC->eq(RHS: AC->shl(shiftAmt: PosOffset).lshr(shiftAmt: PosOffset));
486 case Instruction::AShr:
487 return I.isExact() && AC->eq(RHS: AC->shl(shiftAmt: PosOffset).ashr(ShiftAmt: PosOffset));
488 }
489 };
490 if (isSuitableForPreShift()) {
491 Constant *NewC = ConstantInt::get(Ty, V: I.getOpcode() == Instruction::Shl
492 ? AC->lshr(shiftAmt: PosOffset)
493 : AC->shl(shiftAmt: PosOffset));
494 BinaryOperator *NewShiftOp =
495 BinaryOperator::Create(Op: I.getOpcode(), S1: NewC, S2: A);
496 if (I.getOpcode() == Instruction::Shl) {
497 NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
498 } else {
499 NewShiftOp->setIsExact();
500 }
501 return NewShiftOp;
502 }
503 }
504
505 // C1 << (C2 - X) -> (C1 << C2) >> X
506 // C1 >> (C2 - X) -> (C1 >> C2) << X
507 // X must be u<= C2 (checked by NUWSub).
508 // Also match (X ^ C2) if equivalent to (C2 - X).
509 uint64_t C2;
510 Value *X;
511 if (match(V: Op1, P: m_NUWSub(L: m_ConstantInt(V&: C2), R: m_Value(V&: X))) ||
512 (match(V: Op1, P: m_Xor(L: m_Value(V&: X), R: m_ConstantInt(V&: C2))) &&
513 (C2 | computeKnownBits(V: X, CxtI: &I).Zero).isAllOnes())) {
514 if (I.getOpcode() == Instruction::Shl) {
515 if (AC->countl_zero() >= C2)
516 return BinaryOperator::CreateExactLShr(
517 V1: ConstantInt::get(Ty, V: AC->shl(shiftAmt: C2)), V2: X);
518 if (AC->countl_one() > C2)
519 return BinaryOperator::CreateExactAShr(
520 V1: ConstantInt::get(Ty, V: AC->shl(shiftAmt: C2)), V2: X);
521 } else if (AC->countr_zero() >= C2) {
522 if (AC->isSignBitClear()) {
523 auto *Shl = BinaryOperator::CreateNUWShl(
524 V1: ConstantInt::get(Ty, V: AC->lshr(shiftAmt: C2)), V2: X);
525 Shl->setHasNoSignedWrap();
526 return Shl;
527 }
528 if (I.getOpcode() == Instruction::LShr)
529 return BinaryOperator::CreateNUWShl(
530 V1: ConstantInt::get(Ty, V: AC->lshr(shiftAmt: C2)), V2: X);
531 return BinaryOperator::CreateNSWShl(V1: ConstantInt::get(Ty, V: AC->ashr(ShiftAmt: C2)),
532 V2: X);
533 }
534 }
535 }
536
537 // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2.
538 // Because shifts by negative values (which could occur if A were negative)
539 // are undefined.
540 if (Op1->hasOneUse() && match(V: Op1, P: m_SRem(L: m_Value(V&: A), R: m_Constant(C))) &&
541 match(V: C, P: m_Power2())) {
542 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
543 // demand the sign bit (and many others) here??
544 Constant *Mask = ConstantExpr::getSub(C1: C, C2: ConstantInt::get(Ty, V: 1));
545 Value *Rem = Builder.CreateAnd(LHS: A, RHS: Mask, Name: Op1->getName());
546 return replaceOperand(I, OpNum: 1, V: Rem);
547 }
548
549 if (Instruction *Logic = foldShiftOfShiftedBinOp(I, Builder))
550 return Logic;
551
552 if (match(V: Op1, P: m_Or(L: m_Value(), R: m_SpecificInt(V: BitWidth - 1))))
553 return replaceOperand(I, OpNum: 1, V: ConstantInt::get(Ty, V: BitWidth - 1));
554
555 Instruction *CmpIntr;
556 if ((I.getOpcode() == Instruction::LShr ||
557 I.getOpcode() == Instruction::AShr) &&
558 match(V: Op0, P: m_OneUse(SubPattern: m_Instruction(I&: CmpIntr))) &&
559 isa<CmpIntrinsic>(Val: CmpIntr) &&
560 match(V: Op1, P: m_SpecificInt(V: Ty->getScalarSizeInBits() - 1))) {
561 Value *Cmp =
562 Builder.CreateICmp(P: cast<CmpIntrinsic>(Val: CmpIntr)->getLTPredicate(),
563 LHS: CmpIntr->getOperand(i: 0), RHS: CmpIntr->getOperand(i: 1));
564 return CastInst::Create(I.getOpcode() == Instruction::LShr
565 ? Instruction::ZExt
566 : Instruction::SExt,
567 S: Cmp, Ty);
568 }
569
570 return nullptr;
571}
572
573/// Return true if we can simplify two logical (either left or right) shifts
574/// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
575static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
576 ShiftSemantics Semantics,
577 Instruction *InnerShift,
578 InstCombinerImpl &IC, Instruction *CxtI) {
579 assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
580
581 // We need constant scalar or constant splat shifts.
582 const APInt *InnerShiftConst;
583 if (!match(V: InnerShift->getOperand(i: 1), P: m_APInt(Res&: InnerShiftConst)))
584 return false;
585
586 // Two logical shifts in the same direction:
587 // shl (shl X, C1), C2 --> shl X, C1 + C2
588 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
589 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
590
591 if (!IsOuterShl && Semantics == ShiftSemantics::Signed)
592 return IsInnerShl && cast<BinaryOperator>(Val: InnerShift)->hasNoSignedWrap() &&
593 *InnerShiftConst == OuterShAmt;
594 if (IsInnerShl == IsOuterShl)
595 return Semantics == ShiftSemantics::Lossy;
596
597 // Equal shift amounts in opposite directions become bitwise 'and':
598 // lshr (shl X, C), C --> and X, C'
599 // shl (lshr X, C), C --> and X, C'
600 if (*InnerShiftConst == OuterShAmt)
601 return true;
602
603 // If the 2nd shift is bigger than the 1st, we can fold:
604 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
605 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
606 // but it isn't profitable unless we know the and'd out bits are already zero.
607 // Also, check that the inner shift is valid (less than the type width) or
608 // we'll crash trying to produce the bit mask for the 'and'.
609 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
610 if (InnerShiftConst->ugt(RHS: OuterShAmt) && InnerShiftConst->ult(RHS: TypeWidth)) {
611 unsigned InnerShAmt = InnerShiftConst->getZExtValue();
612 unsigned MaskShift =
613 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
614 APInt Mask = APInt::getLowBitsSet(numBits: TypeWidth, loBitsSet: OuterShAmt) << MaskShift;
615 if (IC.MaskedValueIsZero(V: InnerShift->getOperand(i: 0), Mask, CxtI))
616 return true;
617 }
618
619 return false;
620}
621
622/// See if we can compute the specified value, but shifted logically to the left
623/// or right by some number of bits. This should return true if the
624/// transformation is valid. If the Semantics is not lossy,
625/// we must get the same value when we shift this value and then shift back.
626/// This is used to eliminate extraneous shifting from things like:
627/// %C = shl i128 %A, 64
628/// %D = shl i128 %B, 96
629/// %E = or i128 %C, %D
630/// %F = lshr i128 %E, 64
631/// where the client will ask if E can be computed shifted right by 64-bits. If
632/// this succeeds, getShiftedValue() will be called to produce the value.
633bool InstCombinerImpl::canEvaluateShifted(Value *V, unsigned NumBits,
634 bool IsLeftShift,
635 ShiftSemantics Semantics,
636 Instruction *CxtI) {
637 // We can always evaluate immediate constants shifted left. For right shifts,
638 // the constant must be a multiple of 2^NumBits to avoid losing information.
639 if (match(V, P: m_ImmConstant())) {
640 if (Semantics == ShiftSemantics::Lossy)
641 return true;
642 const APInt *C;
643 if (match(V, P: m_APIntAllowPoison(Res&: C)) && !IsLeftShift)
644 return C->countr_zero() >= NumBits;
645 return false;
646 }
647
648 Instruction *I = dyn_cast<Instruction>(Val: V);
649 if (!I) return false;
650
651 // We can't mutate something that has multiple uses: doing so would
652 // require duplicating the instruction in general, which isn't profitable.
653 if (!I->hasOneUse()) return false;
654
655 switch (I->getOpcode()) {
656 default: return false;
657 case Instruction::And:
658 case Instruction::Or:
659 case Instruction::Xor:
660 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
661 return canEvaluateShifted(V: I->getOperand(i: 0), NumBits, IsLeftShift, Semantics,
662 CxtI: I) &&
663 canEvaluateShifted(V: I->getOperand(i: 1), NumBits, IsLeftShift, Semantics,
664 CxtI: I);
665
666 case Instruction::Shl:
667 case Instruction::LShr:
668 return canEvaluateShiftedShift(OuterShAmt: NumBits, IsOuterShl: IsLeftShift, Semantics, InnerShift: I, IC&: *this,
669 CxtI);
670
671 case Instruction::Select: {
672 SelectInst *SI = cast<SelectInst>(Val: I);
673 Value *TrueVal = SI->getTrueValue();
674 Value *FalseVal = SI->getFalseValue();
675 return canEvaluateShifted(V: TrueVal, NumBits, IsLeftShift, Semantics, CxtI: SI) &&
676 canEvaluateShifted(V: FalseVal, NumBits, IsLeftShift, Semantics, CxtI: SI);
677 }
678 case Instruction::PHI: {
679 // We can change a phi if we can change all operands. Note that we never
680 // get into trouble with cyclic PHIs here because we only consider
681 // instructions with a single use.
682 PHINode *PN = cast<PHINode>(Val: I);
683 for (Value *IncValue : PN->incoming_values())
684 if (!canEvaluateShifted(V: IncValue, NumBits, IsLeftShift, Semantics, CxtI: PN))
685 return false;
686 return true;
687 }
688 case Instruction::Mul: {
689 const APInt *MulConst;
690 // We can fold (shr (mul X, -(1 << C)), C) -> (and (neg X), C`)
691 return !IsLeftShift && Semantics == ShiftSemantics::Unsigned &&
692 match(V: I->getOperand(i: 1), P: m_APInt(Res&: MulConst)) &&
693 MulConst->isNegatedPowerOf2() && MulConst->countr_zero() == NumBits;
694 }
695 case Instruction::Add: {
696 auto *BinOp = cast<BinaryOperator>(Val: I);
697 // Left shift case
698 if (IsLeftShift) {
699 if (Semantics == ShiftSemantics::Lossy)
700 return canEvaluateShifted(V: I->getOperand(i: 0), NumBits, IsLeftShift,
701 Semantics, CxtI: I) &&
702 canEvaluateShifted(V: I->getOperand(i: 1), NumBits, IsLeftShift,
703 Semantics, CxtI: I);
704
705 return false;
706 }
707
708 if (Semantics == ShiftSemantics::Lossy)
709 return false;
710 bool WrapRequired =
711 (Semantics == ShiftSemantics::Signed && BinOp->hasNoSignedWrap()) ||
712 (Semantics == ShiftSemantics::Unsigned && BinOp->hasNoUnsignedWrap());
713 return WrapRequired &&
714 canEvaluateShifted(V: I->getOperand(i: 0), NumBits, IsLeftShift, Semantics,
715 CxtI: I) &&
716 canEvaluateShifted(V: I->getOperand(i: 1), NumBits, IsLeftShift, Semantics,
717 CxtI: I);
718 }
719 }
720}
721
722/// Fold OuterShift (InnerShift X, C1), C2.
723/// See canEvaluateShiftedShift() for the constraints on these instructions.
724static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
725 bool IsOuterShl, ShiftSemantics Semantics,
726 InstCombiner::BuilderTy &Builder) {
727 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
728 Type *ShType = InnerShift->getType();
729 unsigned TypeWidth = ShType->getScalarSizeInBits();
730
731 // We only accept shifts-by-a-constant in canEvaluateShifted().
732 const APInt *C1;
733 match(V: InnerShift->getOperand(i_nocapture: 1), P: m_APInt(Res&: C1));
734 unsigned InnerShAmt = C1->getZExtValue();
735
736 // Change the shift amount and clear the appropriate IR flags.
737 auto NewInnerShift = [&](unsigned ShAmt) {
738 InnerShift->setOperand(i_nocapture: 1, Val_nocapture: ConstantInt::get(Ty: ShType, V: ShAmt));
739 if (IsInnerShl) {
740 InnerShift->setHasNoUnsignedWrap(false);
741 InnerShift->setHasNoSignedWrap(false);
742 } else {
743 InnerShift->setIsExact(false);
744 }
745 return InnerShift;
746 };
747
748 // Two logical shifts in the same direction:
749 // shl (shl X, C1), C2 --> shl X, C1 + C2
750 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
751 if (IsInnerShl == IsOuterShl) {
752 // If this is an oversized composite shift, then unsigned shifts get 0.
753 if (InnerShAmt + OuterShAmt >= TypeWidth)
754 return Constant::getNullValue(Ty: ShType);
755
756 return NewInnerShift(InnerShAmt + OuterShAmt);
757 }
758
759 // Equal shift amounts in opposite directions become bitwise 'and':
760 // lshr (shl X, C), C --> and X, C'
761 // shl (lshr X, C), C --> and X, C'
762 if (InnerShAmt == OuterShAmt) {
763 if (!IsOuterShl && Semantics == ShiftSemantics::Signed) {
764 assert(IsInnerShl && InnerShift->hasNoSignedWrap() &&
765 "Signed Semantics should have nsw and inner shl per "
766 "canEvaluateShiftedShift");
767 return InnerShift->getOperand(i_nocapture: 0);
768 }
769 if (!IsOuterShl && Semantics == ShiftSemantics::Unsigned && IsInnerShl &&
770 InnerShift->hasNoUnsignedWrap())
771 return InnerShift->getOperand(i_nocapture: 0);
772
773 APInt Mask = IsInnerShl
774 ? APInt::getLowBitsSet(numBits: TypeWidth, loBitsSet: TypeWidth - OuterShAmt)
775 : APInt::getHighBitsSet(numBits: TypeWidth, hiBitsSet: TypeWidth - OuterShAmt);
776 Value *And = Builder.CreateAnd(LHS: InnerShift->getOperand(i_nocapture: 0),
777 RHS: ConstantInt::get(Ty: ShType, V: Mask));
778 if (auto *AndI = dyn_cast<Instruction>(Val: And)) {
779 AndI->moveBefore(InsertPos: InnerShift->getIterator());
780 AndI->takeName(V: InnerShift);
781 }
782 return And;
783 }
784
785 assert(InnerShAmt > OuterShAmt &&
786 "Unexpected opposite direction logical shift pair");
787
788 // In general, we would need an 'and' for this transform, but
789 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
790 // lshr (shl X, C1), C2 --> shl X, C1 - C2
791 // shl (lshr X, C1), C2 --> lshr X, C1 - C2
792 return NewInnerShift(InnerShAmt - OuterShAmt);
793}
794
795/// When canEvaluateShifted() returns true for an expression, this function
796/// inserts the new computation that produces the shifted value.
797Value *InstCombinerImpl::getShiftedValue(Value *V, unsigned NumBits,
798 bool IsLeftShift,
799 ShiftSemantics Semantics) {
800 // We can always evaluate constants shifted.
801 if (Constant *C = dyn_cast<Constant>(Val: V)) {
802 Instruction::BinaryOps ShiftOp =
803 IsLeftShift ? Instruction::Shl
804 : (Semantics == ShiftSemantics::Signed ? Instruction::AShr
805 : Instruction::LShr);
806 return Builder.CreateBinOp(Opc: ShiftOp, LHS: C,
807 RHS: ConstantInt::get(Ty: C->getType(), V: NumBits));
808 }
809
810 Instruction *I = cast<Instruction>(Val: V);
811 addToWorklist(I);
812
813 switch (I->getOpcode()) {
814 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
815 case Instruction::And:
816 case Instruction::Or:
817 case Instruction::Xor:
818 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
819 I->setOperand(
820 i: 0, Val: getShiftedValue(V: I->getOperand(i: 0), NumBits, IsLeftShift, Semantics));
821 I->setOperand(
822 i: 1, Val: getShiftedValue(V: I->getOperand(i: 1), NumBits, IsLeftShift, Semantics));
823 return I;
824
825 case Instruction::Shl:
826 case Instruction::LShr:
827 return foldShiftedShift(InnerShift: cast<BinaryOperator>(Val: I), OuterShAmt: NumBits, IsOuterShl: IsLeftShift,
828 Semantics, Builder);
829
830 case Instruction::Select:
831 I->setOperand(
832 i: 1, Val: getShiftedValue(V: I->getOperand(i: 1), NumBits, IsLeftShift, Semantics));
833 I->setOperand(
834 i: 2, Val: getShiftedValue(V: I->getOperand(i: 2), NumBits, IsLeftShift, Semantics));
835 return I;
836 case Instruction::PHI: {
837 // We can change a phi if we can change all operands. Note that we never
838 // get into trouble with cyclic PHIs here because we only consider
839 // instructions with a single use.
840 PHINode *PN = cast<PHINode>(Val: I);
841 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
842 PN->setIncomingValue(i, V: getShiftedValue(V: PN->getIncomingValue(i), NumBits,
843 IsLeftShift, Semantics));
844 return PN;
845 }
846 case Instruction::Mul: {
847 assert(!IsLeftShift && "Unexpected shift direction!");
848 auto *Neg = BinaryOperator::CreateNeg(Op: I->getOperand(i: 0));
849 InsertNewInstWith(New: Neg, Old: I->getIterator());
850 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
851 APInt Mask = APInt::getLowBitsSet(numBits: TypeWidth, loBitsSet: TypeWidth - NumBits);
852 auto *And = BinaryOperator::CreateAnd(V1: Neg,
853 V2: ConstantInt::get(Ty: I->getType(), V: Mask));
854 And->takeName(V: I);
855 return InsertNewInstWith(New: And, Old: I->getIterator());
856 }
857 case Instruction::Add: {
858 if (IsLeftShift)
859 I->dropPoisonGeneratingFlags();
860 I->setOperand(
861 i: 0, Val: getShiftedValue(V: I->getOperand(i: 0), NumBits, IsLeftShift, Semantics));
862 I->setOperand(
863 i: 1, Val: getShiftedValue(V: I->getOperand(i: 1), NumBits, IsLeftShift, Semantics));
864 return I;
865 }
866 }
867}
868
869// If this is a bitwise operator or add with a constant RHS we might be able
870// to pull it through a shift.
871static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift,
872 BinaryOperator *BO) {
873 switch (BO->getOpcode()) {
874 default:
875 return false; // Do not perform transform!
876 case Instruction::Add:
877 return Shift.getOpcode() == Instruction::Shl;
878 case Instruction::Or:
879 case Instruction::And:
880 return true;
881 case Instruction::Xor:
882 // Do not change a 'not' of logical shift because that would create a normal
883 // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
884 return !(Shift.isLogicalShift() && match(V: BO, P: m_Not(V: m_Value())));
885 }
886}
887
888Instruction *InstCombinerImpl::FoldShiftByConstant(Value *Op0, Constant *C1,
889 BinaryOperator &I) {
890 // (C2 << X) << C1 --> (C2 << C1) << X
891 // (C2 >> X) >> C1 --> (C2 >> C1) >> X
892 Constant *C2;
893 Value *X;
894 bool IsLeftShift = I.getOpcode() == Instruction::Shl;
895 if (match(V: Op0, P: m_BinOp(Opcode: I.getOpcode(), L: m_ImmConstant(C&: C2), R: m_Value(V&: X)))) {
896 Instruction *R = BinaryOperator::Create(
897 Op: I.getOpcode(), S1: Builder.CreateBinOp(Opc: I.getOpcode(), LHS: C2, RHS: C1), S2: X);
898 BinaryOperator *BO0 = cast<BinaryOperator>(Val: Op0);
899 if (IsLeftShift) {
900 R->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() &&
901 BO0->hasNoUnsignedWrap());
902 R->setHasNoSignedWrap(I.hasNoSignedWrap() && BO0->hasNoSignedWrap());
903 } else
904 R->setIsExact(I.isExact() && BO0->isExact());
905 return R;
906 }
907
908 Type *Ty = I.getType();
909 unsigned TypeBits = Ty->getScalarSizeInBits();
910
911 // (X / +DivC) >> (Width - 1) --> ext (X <= -DivC)
912 // (X / -DivC) >> (Width - 1) --> ext (X >= +DivC)
913 const APInt *DivC;
914 if (!IsLeftShift && match(V: C1, P: m_SpecificIntAllowPoison(V: TypeBits - 1)) &&
915 match(V: Op0, P: m_SDiv(L: m_Value(V&: X), R: m_APInt(Res&: DivC))) && !DivC->isZero() &&
916 !DivC->isMinSignedValue()) {
917 Constant *NegDivC = ConstantInt::get(Ty, V: -(*DivC));
918 ICmpInst::Predicate Pred =
919 DivC->isNegative() ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SLE;
920 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: X, RHS: NegDivC);
921 auto ExtOpcode = (I.getOpcode() == Instruction::AShr) ? Instruction::SExt
922 : Instruction::ZExt;
923 return CastInst::Create(ExtOpcode, S: Cmp, Ty);
924 }
925
926 const APInt *Op1C;
927 if (!match(V: C1, P: m_APInt(Res&: Op1C)))
928 return nullptr;
929
930 assert(!Op1C->uge(TypeBits) &&
931 "Shift over the type width should have been removed already");
932
933 // See if we can propagate this shift into the input, this covers the trivial
934 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
935 if (I.getOpcode() != Instruction::AShr) {
936 bool IsLeftShift = I.getOpcode() == Instruction::Shl;
937 ShiftSemantics Semantics =
938 IsLeftShift ? ShiftSemantics::Lossy : ShiftSemantics::Unsigned;
939 if (canEvaluateShifted(V: Op0, NumBits: Op1C->getZExtValue(), IsLeftShift, Semantics,
940 CxtI: &I)) {
941 LLVM_DEBUG(
942 dbgs() << "ICE: GetShiftedValue propagating shift through expression"
943 " to eliminate shift:\n IN: "
944 << *Op0 << "\n SH: " << I << "\n");
945
946 return replaceInstUsesWith(I, V: getShiftedValue(V: Op0, NumBits: Op1C->getZExtValue(),
947 IsLeftShift, Semantics));
948 }
949 }
950
951 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
952 return FoldedShift;
953
954 if (!Op0->hasOneUse())
955 return nullptr;
956
957 if (auto *Op0BO = dyn_cast<BinaryOperator>(Val: Op0)) {
958 // If the operand is a bitwise operator with a constant RHS, and the
959 // shift is the only use, we can pull it out of the shift.
960 const APInt *Op0C;
961 if (match(V: Op0BO->getOperand(i_nocapture: 1), P: m_APInt(Res&: Op0C))) {
962 if (canShiftBinOpWithConstantRHS(Shift&: I, BO: Op0BO)) {
963 Value *NewRHS =
964 Builder.CreateBinOp(Opc: I.getOpcode(), LHS: Op0BO->getOperand(i_nocapture: 1), RHS: C1);
965
966 Value *NewShift =
967 Builder.CreateBinOp(Opc: I.getOpcode(), LHS: Op0BO->getOperand(i_nocapture: 0), RHS: C1);
968 NewShift->takeName(V: Op0BO);
969
970 return BinaryOperator::Create(Op: Op0BO->getOpcode(), S1: NewShift, S2: NewRHS);
971 }
972 }
973 }
974
975 // If we have a select that conditionally executes some binary operator,
976 // see if we can pull it the select and operator through the shift.
977 //
978 // For example, turning:
979 // shl (select C, (add X, C1), X), C2
980 // Into:
981 // Y = shl X, C2
982 // select C, (add Y, C1 << C2), Y
983 Value *Cond;
984 BinaryOperator *TBO;
985 Value *FalseVal;
986 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_OneUse(SubPattern: m_BinOp(I&: TBO)),
987 R: m_Value(V&: FalseVal)))) {
988 const APInt *C;
989 if (!isa<Constant>(Val: FalseVal) && TBO->getOperand(i_nocapture: 0) == FalseVal &&
990 match(V: TBO->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) &&
991 canShiftBinOpWithConstantRHS(Shift&: I, BO: TBO)) {
992 Value *NewRHS =
993 Builder.CreateBinOp(Opc: I.getOpcode(), LHS: TBO->getOperand(i_nocapture: 1), RHS: C1);
994
995 Value *NewShift = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: FalseVal, RHS: C1);
996 Value *NewOp = Builder.CreateBinOp(Opc: TBO->getOpcode(), LHS: NewShift, RHS: NewRHS);
997 return SelectInst::Create(C: Cond, S1: NewOp, S2: NewShift);
998 }
999 }
1000
1001 BinaryOperator *FBO;
1002 Value *TrueVal;
1003 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TrueVal),
1004 R: m_OneUse(SubPattern: m_BinOp(I&: FBO))))) {
1005 const APInt *C;
1006 if (!isa<Constant>(Val: TrueVal) && FBO->getOperand(i_nocapture: 0) == TrueVal &&
1007 match(V: FBO->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) &&
1008 canShiftBinOpWithConstantRHS(Shift&: I, BO: FBO)) {
1009 Value *NewRHS =
1010 Builder.CreateBinOp(Opc: I.getOpcode(), LHS: FBO->getOperand(i_nocapture: 1), RHS: C1);
1011
1012 Value *NewShift = Builder.CreateBinOp(Opc: I.getOpcode(), LHS: TrueVal, RHS: C1);
1013 Value *NewOp = Builder.CreateBinOp(Opc: FBO->getOpcode(), LHS: NewShift, RHS: NewRHS);
1014 return SelectInst::Create(C: Cond, S1: NewShift, S2: NewOp);
1015 }
1016 }
1017
1018 return nullptr;
1019}
1020
1021// Tries to perform
1022// (lshr (add (zext X), (zext Y)), K)
1023// -> (icmp ult (add X, Y), X)
1024// where
1025// - The add's operands are zexts from a K-bits integer to a bigger type.
1026// - The add is only used by the shr, or by iK (or narrower) truncates.
1027// - The lshr type has more than 2 bits (other types are boolean math).
1028// - K > 1
1029// note that
1030// - The resulting add cannot have nuw/nsw, else on overflow we get a
1031// poison value and the transform isn't legal anymore.
1032Instruction *InstCombinerImpl::foldLShrOverflowBit(BinaryOperator &I) {
1033 assert(I.getOpcode() == Instruction::LShr);
1034
1035 Value *Add = I.getOperand(i_nocapture: 0);
1036 Value *ShiftAmt = I.getOperand(i_nocapture: 1);
1037 Type *Ty = I.getType();
1038
1039 if (Ty->getScalarSizeInBits() < 3)
1040 return nullptr;
1041
1042 const APInt *ShAmtAPInt = nullptr;
1043 Value *X = nullptr, *Y = nullptr;
1044 if (!match(V: ShiftAmt, P: m_APInt(Res&: ShAmtAPInt)) ||
1045 !match(V: Add,
1046 P: m_Add(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))), R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y))))))
1047 return nullptr;
1048
1049 const unsigned ShAmt = ShAmtAPInt->getZExtValue();
1050 if (ShAmt == 1)
1051 return nullptr;
1052
1053 // X/Y are zexts from `ShAmt`-sized ints.
1054 if (X->getType()->getScalarSizeInBits() != ShAmt ||
1055 Y->getType()->getScalarSizeInBits() != ShAmt)
1056 return nullptr;
1057
1058 // Make sure that `Add` is only used by `I` and `ShAmt`-truncates.
1059 if (!Add->hasOneUse()) {
1060 for (User *U : Add->users()) {
1061 if (U == &I)
1062 continue;
1063
1064 TruncInst *Trunc = dyn_cast<TruncInst>(Val: U);
1065 if (!Trunc || Trunc->getType()->getScalarSizeInBits() > ShAmt)
1066 return nullptr;
1067 }
1068 }
1069
1070 // Insert at Add so that the newly created `NarrowAdd` will dominate it's
1071 // users (i.e. `Add`'s users).
1072 Instruction *AddInst = cast<Instruction>(Val: Add);
1073 Builder.SetInsertPoint(AddInst);
1074
1075 Value *NarrowAdd = Builder.CreateAdd(LHS: X, RHS: Y, Name: "add.narrowed");
1076 Value *Overflow =
1077 Builder.CreateICmpULT(LHS: NarrowAdd, RHS: X, Name: "add.narrowed.overflow");
1078
1079 // Replace the uses of the original add with a zext of the
1080 // NarrowAdd's result. Note that all users at this stage are known to
1081 // be ShAmt-sized truncs, or the lshr itself.
1082 if (!Add->hasOneUse()) {
1083 replaceInstUsesWith(I&: *AddInst, V: Builder.CreateZExt(V: NarrowAdd, DestTy: Ty));
1084 eraseInstFromFunction(I&: *AddInst);
1085 }
1086
1087 // Replace the LShr with a zext of the overflow check.
1088 return new ZExtInst(Overflow, Ty);
1089}
1090
1091// Try to set nuw/nsw flags on shl or exact flag on lshr/ashr using knownbits.
1092static bool setShiftFlags(BinaryOperator &I, const SimplifyQuery &Q) {
1093 assert(I.isShift() && "Expected a shift as input");
1094 // We already have all the flags.
1095 if (I.getOpcode() == Instruction::Shl) {
1096 if (I.hasNoUnsignedWrap() && I.hasNoSignedWrap())
1097 return false;
1098 } else {
1099 if (I.isExact())
1100 return false;
1101
1102 // shr (shl X, Y), Y
1103 if (match(V: I.getOperand(i_nocapture: 0), P: m_Shl(L: m_Value(), R: m_Specific(V: I.getOperand(i_nocapture: 1))))) {
1104 I.setIsExact();
1105 return true;
1106 }
1107 // Infer 'exact' flag if shift amount is cttz(x) on the same operand.
1108 if (match(V: I.getOperand(i_nocapture: 1),
1109 P: m_Cttz(Op0: m_Specific(V: I.getOperand(i_nocapture: 0)), Op1: m_Value()))) {
1110 I.setIsExact();
1111 return true;
1112 }
1113 }
1114
1115 // Compute what we know about shift count.
1116 KnownBits KnownCnt = computeKnownBits(V: I.getOperand(i_nocapture: 1), Q);
1117 unsigned BitWidth = KnownCnt.getBitWidth();
1118 // Since shift produces a poison value if RHS is equal to or larger than the
1119 // bit width, we can safely assume that RHS is less than the bit width.
1120 uint64_t MaxCnt = KnownCnt.getMaxValue().getLimitedValue(Limit: BitWidth - 1);
1121
1122 KnownBits KnownAmt = computeKnownBits(V: I.getOperand(i_nocapture: 0), Q);
1123 bool Changed = false;
1124
1125 if (I.getOpcode() == Instruction::Shl) {
1126 // If we have as many leading zeros than maximum shift cnt we have nuw.
1127 if (!I.hasNoUnsignedWrap() && MaxCnt <= KnownAmt.countMinLeadingZeros()) {
1128 I.setHasNoUnsignedWrap();
1129 Changed = true;
1130 }
1131 // If we have more sign bits than maximum shift cnt we have nsw.
1132 if (!I.hasNoSignedWrap()) {
1133 if (MaxCnt < KnownAmt.countMinSignBits() ||
1134 MaxCnt <
1135 ComputeNumSignBits(Op: I.getOperand(i_nocapture: 0), DL: Q.DL, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT)) {
1136 I.setHasNoSignedWrap();
1137 Changed = true;
1138 }
1139 }
1140 return Changed;
1141 }
1142
1143 // If we have at least as many trailing zeros as maximum count then we have
1144 // exact.
1145 Changed = MaxCnt <= KnownAmt.countMinTrailingZeros();
1146 I.setIsExact(Changed);
1147
1148 return Changed;
1149}
1150
1151Instruction *InstCombinerImpl::visitShl(BinaryOperator &I) {
1152 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
1153
1154 if (Value *V = simplifyShlInst(Op0: I.getOperand(i_nocapture: 0), Op1: I.getOperand(i_nocapture: 1),
1155 IsNSW: I.hasNoSignedWrap(), IsNUW: I.hasNoUnsignedWrap(), Q))
1156 return replaceInstUsesWith(I, V);
1157
1158 if (Instruction *X = foldVectorBinop(Inst&: I))
1159 return X;
1160
1161 if (Instruction *V = commonShiftTransforms(I))
1162 return V;
1163
1164 if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(OuterShift: &I, Q, Builder))
1165 return V;
1166
1167 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1168 Type *Ty = I.getType();
1169 unsigned BitWidth = Ty->getScalarSizeInBits();
1170
1171 const APInt *C;
1172 if (match(V: Op1, P: m_APInt(Res&: C))) {
1173 unsigned ShAmtC = C->getZExtValue();
1174
1175 // shl (zext X), C --> zext (shl X, C)
1176 // This is only valid if X would have zeros shifted out.
1177 Value *X;
1178 if (match(V: Op0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))))) {
1179 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1180 if (ShAmtC < SrcWidth &&
1181 MaskedValueIsZero(V: X, Mask: APInt::getHighBitsSet(numBits: SrcWidth, hiBitsSet: ShAmtC), CxtI: &I))
1182 return new ZExtInst(Builder.CreateShl(LHS: X, RHS: ShAmtC), Ty);
1183 }
1184
1185 // (X >> C) << C --> X & (-1 << C)
1186 if (match(V: Op0, P: m_Shr(L: m_Value(V&: X), R: m_Specific(V: Op1)))) {
1187 APInt Mask(APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - ShAmtC));
1188 return BinaryOperator::CreateAnd(V1: X, V2: ConstantInt::get(Ty, V: Mask));
1189 }
1190
1191 const APInt *C1;
1192 if (match(V: Op0, P: m_Exact(SubPattern: m_Shr(L: m_Value(V&: X), R: m_APInt(Res&: C1)))) &&
1193 C1->ult(RHS: BitWidth)) {
1194 unsigned ShrAmt = C1->getZExtValue();
1195 if (ShrAmt < ShAmtC) {
1196 // If C1 < C: (X >>?,exact C1) << C --> X << (C - C1)
1197 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShAmtC - ShrAmt);
1198 auto *NewShl = BinaryOperator::CreateShl(V1: X, V2: ShiftDiff);
1199 NewShl->setHasNoUnsignedWrap(
1200 I.hasNoUnsignedWrap() ||
1201 (ShrAmt &&
1202 cast<Instruction>(Val: Op0)->getOpcode() == Instruction::LShr &&
1203 I.hasNoSignedWrap()));
1204 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1205 return NewShl;
1206 }
1207 if (ShrAmt > ShAmtC) {
1208 // If C1 > C: (X >>?exact C1) << C --> X >>?exact (C1 - C)
1209 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShrAmt - ShAmtC);
1210 auto *NewShr = BinaryOperator::Create(
1211 Op: cast<BinaryOperator>(Val: Op0)->getOpcode(), S1: X, S2: ShiftDiff);
1212 NewShr->setIsExact(true);
1213 return NewShr;
1214 }
1215 }
1216
1217 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shr(L: m_Value(V&: X), R: m_APInt(Res&: C1)))) &&
1218 C1->ult(RHS: BitWidth)) {
1219 unsigned ShrAmt = C1->getZExtValue();
1220 if (ShrAmt < ShAmtC) {
1221 // If C1 < C: (X >>? C1) << C --> (X << (C - C1)) & (-1 << C)
1222 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShAmtC - ShrAmt);
1223 auto *NewShl = BinaryOperator::CreateShl(V1: X, V2: ShiftDiff);
1224 NewShl->setHasNoUnsignedWrap(
1225 I.hasNoUnsignedWrap() ||
1226 (ShrAmt &&
1227 cast<Instruction>(Val: Op0)->getOpcode() == Instruction::LShr &&
1228 I.hasNoSignedWrap()));
1229 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1230 Builder.Insert(I: NewShl);
1231 APInt Mask(APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - ShAmtC));
1232 return BinaryOperator::CreateAnd(V1: NewShl, V2: ConstantInt::get(Ty, V: Mask));
1233 }
1234 if (ShrAmt > ShAmtC) {
1235 // If C1 > C: (X >>? C1) << C --> (X >>? (C1 - C)) & (-1 << C)
1236 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShrAmt - ShAmtC);
1237 auto *OldShr = cast<BinaryOperator>(Val: Op0);
1238 auto *NewShr =
1239 BinaryOperator::Create(Op: OldShr->getOpcode(), S1: X, S2: ShiftDiff);
1240 NewShr->setIsExact(OldShr->isExact());
1241 Builder.Insert(I: NewShr);
1242 APInt Mask(APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - ShAmtC));
1243 return BinaryOperator::CreateAnd(V1: NewShr, V2: ConstantInt::get(Ty, V: Mask));
1244 }
1245 }
1246
1247 // Similar to above, but look through an intermediate trunc instruction.
1248 BinaryOperator *Shr;
1249 if (match(V: Op0, P: m_OneUse(SubPattern: m_Trunc(Op: m_OneUse(SubPattern: m_BinOp(I&: Shr))))) &&
1250 match(V: Shr, P: m_Shr(L: m_Value(V&: X), R: m_APInt(Res&: C1)))) {
1251 // The larger shift direction survives through the transform.
1252 unsigned ShrAmtC = C1->getZExtValue();
1253 unsigned ShDiff = ShrAmtC > ShAmtC ? ShrAmtC - ShAmtC : ShAmtC - ShrAmtC;
1254 Constant *ShiftDiffC = ConstantInt::get(Ty: X->getType(), V: ShDiff);
1255 auto ShiftOpc = ShrAmtC > ShAmtC ? Shr->getOpcode() : Instruction::Shl;
1256
1257 // If C1 > C:
1258 // (trunc (X >> C1)) << C --> (trunc (X >> (C1 - C))) && (-1 << C)
1259 // If C > C1:
1260 // (trunc (X >> C1)) << C --> (trunc (X << (C - C1))) && (-1 << C)
1261 Value *NewShift = Builder.CreateBinOp(Opc: ShiftOpc, LHS: X, RHS: ShiftDiffC, Name: "sh.diff");
1262 Value *Trunc = Builder.CreateTrunc(V: NewShift, DestTy: Ty, Name: "tr.sh.diff");
1263 APInt Mask(APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - ShAmtC));
1264 return BinaryOperator::CreateAnd(V1: Trunc, V2: ConstantInt::get(Ty, V: Mask));
1265 }
1266
1267 // If we have an opposite shift by the same amount, we may be able to
1268 // reorder binops and shifts to eliminate math/logic.
1269 auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1270 switch (BinOpcode) {
1271 default:
1272 return false;
1273 case Instruction::Add:
1274 case Instruction::And:
1275 case Instruction::Or:
1276 case Instruction::Xor:
1277 case Instruction::Sub:
1278 // NOTE: Sub is not commutable and the tranforms below may not be valid
1279 // when the shift-right is operand 1 (RHS) of the sub.
1280 return true;
1281 }
1282 };
1283 BinaryOperator *Op0BO;
1284 if (match(V: Op0, P: m_OneUse(SubPattern: m_BinOp(I&: Op0BO))) &&
1285 isSuitableBinOpcode(Op0BO->getOpcode())) {
1286 // Commute so shift-right is on LHS of the binop.
1287 // (Y bop (X >> C)) << C -> ((X >> C) bop Y) << C
1288 // (Y bop ((X >> C) & CC)) << C -> (((X >> C) & CC) bop Y) << C
1289 Value *Shr = Op0BO->getOperand(i_nocapture: 0);
1290 Value *Y = Op0BO->getOperand(i_nocapture: 1);
1291 Value *X;
1292 const APInt *CC;
1293 if (Op0BO->isCommutative() && Y->hasOneUse() &&
1294 (match(V: Y, P: m_Shr(L: m_Value(), R: m_Specific(V: Op1))) ||
1295 match(V: Y, P: m_And(L: m_OneUse(SubPattern: m_Shr(L: m_Value(), R: m_Specific(V: Op1))),
1296 R: m_APInt(Res&: CC)))))
1297 std::swap(a&: Shr, b&: Y);
1298
1299 // ((X >> C) bop Y) << C -> (X bop (Y << C)) & (~0 << C)
1300 if (match(V: Shr, P: m_OneUse(SubPattern: m_Shr(L: m_Value(V&: X), R: m_Specific(V: Op1))))) {
1301 // Y << C
1302 Value *YS = Builder.CreateShl(LHS: Y, RHS: Op1, Name: Op0BO->getName());
1303 // (X bop (Y << C))
1304 Value *B =
1305 Builder.CreateBinOp(Opc: Op0BO->getOpcode(), LHS: X, RHS: YS, Name: Shr->getName());
1306 unsigned Op1Val = C->getLimitedValue(Limit: BitWidth);
1307 APInt Bits = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - Op1Val);
1308 Constant *Mask = ConstantInt::get(Ty, V: Bits);
1309 return BinaryOperator::CreateAnd(V1: B, V2: Mask);
1310 }
1311
1312 // (((X >> C) & CC) bop Y) << C -> (X & (CC << C)) bop (Y << C)
1313 if (match(V: Shr,
1314 P: m_OneUse(SubPattern: m_And(L: m_OneUse(SubPattern: m_Shr(L: m_Value(V&: X), R: m_Specific(V: Op1))),
1315 R: m_APInt(Res&: CC))))) {
1316 // Y << C
1317 Value *YS = Builder.CreateShl(LHS: Y, RHS: Op1, Name: Op0BO->getName());
1318 // X & (CC << C)
1319 Value *M = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty, V: CC->shl(ShiftAmt: *C)),
1320 Name: X->getName() + ".mask");
1321 auto *NewOp = BinaryOperator::Create(Op: Op0BO->getOpcode(), S1: M, S2: YS);
1322 if (auto *Disjoint = dyn_cast<PossiblyDisjointInst>(Val: Op0BO);
1323 Disjoint && Disjoint->isDisjoint())
1324 cast<PossiblyDisjointInst>(Val: NewOp)->setIsDisjoint(true);
1325 return NewOp;
1326 }
1327 }
1328
1329 // (C1 - X) << C --> (C1 << C) - (X << C)
1330 if (match(V: Op0, P: m_OneUse(SubPattern: m_Sub(L: m_APInt(Res&: C1), R: m_Value(V&: X))))) {
1331 Constant *NewLHS = ConstantInt::get(Ty, V: C1->shl(ShiftAmt: *C));
1332 Value *NewShift = Builder.CreateShl(LHS: X, RHS: Op1);
1333 return BinaryOperator::CreateSub(V1: NewLHS, V2: NewShift);
1334 }
1335 }
1336
1337 if (setShiftFlags(I, Q))
1338 return &I;
1339
1340 // Transform (x >> y) << y to x & (-1 << y)
1341 // Valid for any type of right-shift.
1342 Value *X;
1343 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shr(L: m_Value(V&: X), R: m_Specific(V: Op1))))) {
1344 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1345 Value *Mask = Builder.CreateShl(LHS: AllOnes, RHS: Op1);
1346 return BinaryOperator::CreateAnd(V1: Mask, V2: X);
1347 }
1348
1349 // Transform (-1 >> y) << y to -1 << y
1350 if (match(V: Op0, P: m_LShr(L: m_AllOnes(), R: m_Specific(V: Op1)))) {
1351 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1352 return BinaryOperator::CreateShl(V1: AllOnes, V2: Op1);
1353 }
1354
1355 Constant *C1;
1356 if (match(V: Op1, P: m_ImmConstant(C&: C1))) {
1357 Constant *C2;
1358 Value *X;
1359 // (X * C2) << C1 --> X * (C2 << C1)
1360 if (match(V: Op0, P: m_Mul(L: m_Value(V&: X), R: m_ImmConstant(C&: C2))))
1361 return BinaryOperator::CreateMul(V1: X, V2: Builder.CreateShl(LHS: C2, RHS: C1));
1362
1363 // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1364 if (match(V: Op0, P: m_ZExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
1365 auto *NewC = Builder.CreateShl(LHS: ConstantInt::get(Ty, V: 1), RHS: C1);
1366 return createSelectInstWithUnknownProfile(C: X, S1: NewC,
1367 S2: ConstantInt::getNullValue(Ty));
1368 }
1369 }
1370
1371 if (match(V: Op0, P: m_One())) {
1372 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1373 if (match(V: Op1, P: m_Sub(L: m_SpecificInt(V: BitWidth - 1), R: m_Value(V&: X))))
1374 return BinaryOperator::CreateLShr(
1375 V1: ConstantInt::get(Ty, V: APInt::getSignMask(BitWidth)), V2: X);
1376
1377 // Canonicalize "extract lowest set bit" using cttz to and-with-negate:
1378 // 1 << (cttz X) --> -X & X
1379 if (match(V: Op1, P: m_OneUse(SubPattern: m_Cttz(Op0: m_Value(V&: X), Op1: m_Value())))) {
1380 Value *NegX = Builder.CreateNeg(V: X, Name: "neg");
1381 return BinaryOperator::CreateAnd(V1: NegX, V2: X);
1382 }
1383 }
1384
1385 return nullptr;
1386}
1387
1388Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
1389 if (Value *V = simplifyLShrInst(Op0: I.getOperand(i_nocapture: 0), Op1: I.getOperand(i_nocapture: 1), IsExact: I.isExact(),
1390 Q: SQ.getWithInstruction(I: &I)))
1391 return replaceInstUsesWith(I, V);
1392
1393 if (Instruction *X = foldVectorBinop(Inst&: I))
1394 return X;
1395
1396 if (Instruction *R = commonShiftTransforms(I))
1397 return R;
1398
1399 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1400 Type *Ty = I.getType();
1401 Value *X;
1402 const APInt *C;
1403 unsigned BitWidth = Ty->getScalarSizeInBits();
1404
1405 // lshr 1, X --> zext (X == 0)
1406 if (match(V: Op0, P: m_One()))
1407 return new ZExtInst(Builder.CreateIsNull(Arg: Op1), Ty);
1408
1409 // (iN (~X) u>> (N - 1)) --> zext (X > -1)
1410 if (match(V: Op0, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: X)))) &&
1411 match(V: Op1, P: m_SpecificIntAllowPoison(V: BitWidth - 1)))
1412 return new ZExtInst(Builder.CreateIsNotNeg(Arg: X, Name: "isnotneg"), Ty);
1413
1414 // ((X << nuw Z) sub nuw Y) >>u exact Z --> X sub nuw (Y >>u exact Z)
1415 Value *Y;
1416 if (I.isExact() &&
1417 match(V: Op0, P: m_OneUse(SubPattern: m_NUWSub(L: m_NUWShl(L: m_Value(V&: X), R: m_Specific(V: Op1)),
1418 R: m_Value(V&: Y))))) {
1419 Value *NewLshr = Builder.CreateLShr(LHS: Y, RHS: Op1, Name: "", /*isExact=*/true);
1420 auto *NewSub = BinaryOperator::CreateNUWSub(V1: X, V2: NewLshr);
1421 NewSub->setHasNoSignedWrap(
1422 cast<OverflowingBinaryOperator>(Val: Op0)->hasNoSignedWrap());
1423 return NewSub;
1424 }
1425
1426 // Fold (X + Y) / 2 --> (X & Y) iff (X u<= 1) && (Y u<= 1)
1427 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_Value(V&: Y))) && match(V: Op1, P: m_One()) &&
1428 computeKnownBits(V: X, CxtI: &I).countMaxActiveBits() <= 1 &&
1429 computeKnownBits(V: Y, CxtI: &I).countMaxActiveBits() <= 1)
1430 return BinaryOperator::CreateAnd(V1: X, V2: Y);
1431
1432 // (sub nuw X, (Y << nuw Z)) >>u exact Z --> (X >>u exact Z) sub nuw Y
1433 if (I.isExact() &&
1434 match(V: Op0, P: m_OneUse(SubPattern: m_NUWSub(L: m_Value(V&: X),
1435 R: m_NUWShl(L: m_Value(V&: Y), R: m_Specific(V: Op1)))))) {
1436 Value *NewLshr = Builder.CreateLShr(LHS: X, RHS: Op1, Name: "", /*isExact=*/true);
1437 auto *NewSub = BinaryOperator::CreateNUWSub(V1: NewLshr, V2: Y);
1438 NewSub->setHasNoSignedWrap(
1439 cast<OverflowingBinaryOperator>(Val: Op0)->hasNoSignedWrap());
1440 return NewSub;
1441 }
1442
1443 auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1444 switch (BinOpcode) {
1445 default:
1446 return false;
1447 case Instruction::Add:
1448 case Instruction::And:
1449 case Instruction::Or:
1450 case Instruction::Xor:
1451 // Sub is handled separately.
1452 return true;
1453 }
1454 };
1455
1456 // If both the binop and the shift are nuw, then:
1457 // ((X << nuw Z) binop nuw Y) >>u Z --> X binop nuw (Y >>u Z)
1458 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_BinOp(L: m_NUWShl(L: m_Value(V&: X), R: m_Specific(V: Op1)),
1459 R: m_Value(V&: Y))))) {
1460 BinaryOperator *Op0OB = cast<BinaryOperator>(Val: Op0);
1461 if (isSuitableBinOpcode(Op0OB->getOpcode())) {
1462 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: Op0);
1463 !OBO || OBO->hasNoUnsignedWrap()) {
1464 Value *NewLshr = Builder.CreateLShr(
1465 LHS: Y, RHS: Op1, Name: "", isExact: I.isExact() && Op0OB->getOpcode() != Instruction::And);
1466 auto *NewBinOp = BinaryOperator::Create(Op: Op0OB->getOpcode(), S1: NewLshr, S2: X);
1467 if (OBO) {
1468 NewBinOp->setHasNoUnsignedWrap(true);
1469 NewBinOp->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1470 } else if (auto *Disjoint = dyn_cast<PossiblyDisjointInst>(Val: Op0)) {
1471 cast<PossiblyDisjointInst>(Val: NewBinOp)->setIsDisjoint(
1472 Disjoint->isDisjoint());
1473 }
1474 return NewBinOp;
1475 }
1476 }
1477 }
1478
1479 if (match(V: Op1, P: m_APInt(Res&: C))) {
1480 unsigned ShAmtC = C->getZExtValue();
1481 auto *II = dyn_cast<IntrinsicInst>(Val: Op0);
1482 if (II && isPowerOf2_32(Value: BitWidth) && Log2_32(Value: BitWidth) == ShAmtC &&
1483 (II->getIntrinsicID() == Intrinsic::ctlz ||
1484 II->getIntrinsicID() == Intrinsic::cttz ||
1485 II->getIntrinsicID() == Intrinsic::ctpop)) {
1486 // ctlz.i32(x)>>5 --> zext(x == 0)
1487 // cttz.i32(x)>>5 --> zext(x == 0)
1488 // ctpop.i32(x)>>5 --> zext(x == -1)
1489 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1490 Constant *RHS = ConstantInt::getSigned(Ty, V: IsPop ? -1 : 0);
1491 Value *Cmp = Builder.CreateICmpEQ(LHS: II->getArgOperand(i: 0), RHS);
1492 return new ZExtInst(Cmp, Ty);
1493 }
1494
1495 const APInt *C1;
1496 if (match(V: Op0, P: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C1))) && C1->ult(RHS: BitWidth)) {
1497 if (C1->ult(RHS: ShAmtC)) {
1498 unsigned ShlAmtC = C1->getZExtValue();
1499 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShAmtC - ShlAmtC);
1500 if (cast<BinaryOperator>(Val: Op0)->hasNoUnsignedWrap()) {
1501 // (X <<nuw C1) >>u C --> X >>u (C - C1)
1502 auto *NewLShr = BinaryOperator::CreateLShr(V1: X, V2: ShiftDiff);
1503 NewLShr->setIsExact(I.isExact());
1504 return NewLShr;
1505 }
1506 if (Op0->hasOneUse()) {
1507 // (X << C1) >>u C --> (X >>u (C - C1)) & (-1 >> C)
1508 Value *NewLShr = Builder.CreateLShr(LHS: X, RHS: ShiftDiff, Name: "", isExact: I.isExact());
1509 APInt Mask(APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - ShAmtC));
1510 return BinaryOperator::CreateAnd(V1: NewLShr, V2: ConstantInt::get(Ty, V: Mask));
1511 }
1512 } else if (C1->ugt(RHS: ShAmtC)) {
1513 unsigned ShlAmtC = C1->getZExtValue();
1514 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShlAmtC - ShAmtC);
1515 if (cast<BinaryOperator>(Val: Op0)->hasNoUnsignedWrap()) {
1516 // (X <<nuw C1) >>u C --> X <<nuw/nsw (C1 - C)
1517 auto *NewShl = BinaryOperator::CreateShl(V1: X, V2: ShiftDiff);
1518 NewShl->setHasNoUnsignedWrap(true);
1519 NewShl->setHasNoSignedWrap(ShAmtC > 0);
1520 return NewShl;
1521 }
1522 if (Op0->hasOneUse()) {
1523 // (X << C1) >>u C --> X << (C1 - C) & (-1 >> C)
1524 Value *NewShl = Builder.CreateShl(LHS: X, RHS: ShiftDiff);
1525 APInt Mask(APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - ShAmtC));
1526 return BinaryOperator::CreateAnd(V1: NewShl, V2: ConstantInt::get(Ty, V: Mask));
1527 }
1528 } else {
1529 assert(*C1 == ShAmtC);
1530 // (X << C) >>u C --> X & (-1 >>u C)
1531 APInt Mask(APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - ShAmtC));
1532 return BinaryOperator::CreateAnd(V1: X, V2: ConstantInt::get(Ty, V: Mask));
1533 }
1534 }
1535
1536 // ((X << C) + Y) >>u C --> (X + (Y >>u C)) & (-1 >>u C)
1537 // TODO: Consolidate with the more general transform that starts from shl
1538 // (the shifts are in the opposite order).
1539 if (match(V: Op0,
1540 P: m_OneUse(SubPattern: m_c_Add(L: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: X), R: m_Specific(V: Op1))),
1541 R: m_Value(V&: Y))))) {
1542 Value *NewLshr = Builder.CreateLShr(LHS: Y, RHS: Op1);
1543 Value *NewAdd = Builder.CreateAdd(LHS: NewLshr, RHS: X);
1544 unsigned Op1Val = C->getLimitedValue(Limit: BitWidth);
1545 APInt Bits = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - Op1Val);
1546 Constant *Mask = ConstantInt::get(Ty, V: Bits);
1547 return BinaryOperator::CreateAnd(V1: NewAdd, V2: Mask);
1548 }
1549
1550 if (match(V: Op0, P: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X)))) &&
1551 (!Ty->isIntegerTy() || shouldChangeType(From: Ty, To: X->getType()))) {
1552 assert(ShAmtC < X->getType()->getScalarSizeInBits() &&
1553 "Big shift not simplified to zero?");
1554 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1555 Value *NewLShr = Builder.CreateLShr(LHS: X, RHS: ShAmtC);
1556 return new ZExtInst(NewLShr, Ty);
1557 }
1558
1559 if (match(V: Op0, P: m_SExt(Op: m_Value(V&: X)))) {
1560 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1561 // lshr (sext i1 X to iN), C --> select (X, -1 >> C, 0)
1562 if (SrcTyBitWidth == 1) {
1563 auto *NewC = ConstantInt::get(
1564 Ty, V: APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - ShAmtC));
1565 return SelectInst::Create(C: X, S1: NewC, S2: ConstantInt::getNullValue(Ty));
1566 }
1567
1568 if ((!Ty->isIntegerTy() || shouldChangeType(From: Ty, To: X->getType())) &&
1569 Op0->hasOneUse()) {
1570 // Are we moving the sign bit to the low bit and widening with high
1571 // zeros? lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1572 if (ShAmtC == BitWidth - 1) {
1573 Value *NewLShr = Builder.CreateLShr(LHS: X, RHS: SrcTyBitWidth - 1);
1574 return new ZExtInst(NewLShr, Ty);
1575 }
1576
1577 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1578 if (ShAmtC == BitWidth - SrcTyBitWidth) {
1579 // The new shift amount can't be more than the narrow source type.
1580 unsigned NewShAmt = std::min(a: ShAmtC, b: SrcTyBitWidth - 1);
1581 Value *AShr = Builder.CreateAShr(LHS: X, RHS: NewShAmt);
1582 return new ZExtInst(AShr, Ty);
1583 }
1584 }
1585 }
1586
1587 if (ShAmtC == BitWidth - 1) {
1588 // lshr i32 or(X,-X), 31 --> zext (X != 0)
1589 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Or(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X)))))
1590 return new ZExtInst(Builder.CreateIsNotNull(Arg: X), Ty);
1591
1592 // lshr i32 (X -nsw Y), 31 --> zext (X < Y)
1593 if (match(V: Op0, P: m_OneUse(SubPattern: m_NSWSub(L: m_Value(V&: X), R: m_Value(V&: Y)))))
1594 return new ZExtInst(Builder.CreateICmpSLT(LHS: X, RHS: Y), Ty);
1595
1596 // Check if a number is negative and odd:
1597 // lshr i32 (srem X, 2), 31 --> and (X >> 31), X
1598 if (match(V: Op0, P: m_OneUse(SubPattern: m_SRem(L: m_Value(V&: X), R: m_SpecificInt(V: 2))))) {
1599 Value *Signbit = Builder.CreateLShr(LHS: X, RHS: ShAmtC);
1600 return BinaryOperator::CreateAnd(V1: Signbit, V2: X);
1601 }
1602
1603 // lshr iN (X - 1) & ~X, N-1 --> zext (X == 0)
1604 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Add(L: m_Value(V&: X), R: m_AllOnes()),
1605 R: m_Not(V: m_Deferred(V: X))))))
1606 return new ZExtInst(Builder.CreateIsNull(Arg: X), Ty);
1607 }
1608
1609 Instruction *TruncSrc;
1610 if (match(V: Op0, P: m_OneUse(SubPattern: m_Trunc(Op: m_Instruction(I&: TruncSrc)))) &&
1611 match(V: TruncSrc, P: m_LShr(L: m_Value(V&: X), R: m_APInt(Res&: C1)))) {
1612 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1613 unsigned AmtSum = ShAmtC + C1->getZExtValue();
1614
1615 // If the combined shift fits in the source width:
1616 // (trunc (X >>u C1)) >>u C --> and (trunc (X >>u (C1 + C)), MaskC
1617 //
1618 // If the first shift covers the number of bits truncated, then the
1619 // mask instruction is eliminated (and so the use check is relaxed).
1620 if (AmtSum < SrcWidth &&
1621 (TruncSrc->hasOneUse() || C1->uge(RHS: SrcWidth - BitWidth))) {
1622 Value *SumShift = Builder.CreateLShr(LHS: X, RHS: AmtSum, Name: "sum.shift");
1623 Value *Trunc = Builder.CreateTrunc(V: SumShift, DestTy: Ty, Name: I.getName());
1624
1625 // If the first shift does not cover the number of bits truncated, then
1626 // we require a mask to get rid of high bits in the result.
1627 APInt MaskC = APInt::getAllOnes(numBits: BitWidth).lshr(shiftAmt: ShAmtC);
1628 return BinaryOperator::CreateAnd(V1: Trunc, V2: ConstantInt::get(Ty, V: MaskC));
1629 }
1630 }
1631
1632 const APInt *MulC;
1633 if (match(V: Op0, P: m_NUWMul(L: m_Value(V&: X), R: m_APInt(Res&: MulC)))) {
1634 if (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1635 MulC->logBase2() == ShAmtC) {
1636 // Look for a "splat" mul pattern - it replicates bits across each half
1637 // of a value, so a right shift simplifies back to just X:
1638 // lshr i[2N] (mul nuw X, (2^N)+1), N --> X
1639 if (ShAmtC * 2 == BitWidth)
1640 return replaceInstUsesWith(I, V: X);
1641
1642 // lshr (mul nuw (X, 2^N + 1)), N -> add nuw (X, lshr(X, N))
1643 if (Op0->hasOneUse()) {
1644 auto *NewAdd = BinaryOperator::CreateNUWAdd(
1645 V1: X, V2: Builder.CreateLShr(LHS: X, RHS: ConstantInt::get(Ty, V: ShAmtC), Name: "",
1646 isExact: I.isExact()));
1647 NewAdd->setHasNoSignedWrap(
1648 cast<OverflowingBinaryOperator>(Val: Op0)->hasNoSignedWrap());
1649 return NewAdd;
1650 }
1651 }
1652
1653 // The one-use check is not strictly necessary, but codegen may not be
1654 // able to invert the transform and perf may suffer with an extra mul
1655 // instruction.
1656 if (Op0->hasOneUse()) {
1657 APInt NewMulC = MulC->lshr(shiftAmt: ShAmtC);
1658 // if c is divisible by (1 << ShAmtC):
1659 // lshr (mul nuw x, MulC), ShAmtC -> mul nuw nsw x, (MulC >> ShAmtC)
1660 if (MulC->eq(RHS: NewMulC.shl(shiftAmt: ShAmtC))) {
1661 auto *NewMul =
1662 BinaryOperator::CreateNUWMul(V1: X, V2: ConstantInt::get(Ty, V: NewMulC));
1663 assert(ShAmtC != 0 &&
1664 "lshr X, 0 should be handled by simplifyLShrInst.");
1665 NewMul->setHasNoSignedWrap(true);
1666 return NewMul;
1667 }
1668 }
1669 }
1670
1671 // lshr (mul nsw (X, 2^N + 1)), N -> add nsw (X, lshr(X, N))
1672 if (match(V: Op0, P: m_OneUse(SubPattern: m_NSWMul(L: m_Value(V&: X), R: m_APInt(Res&: MulC))))) {
1673 if (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1674 MulC->logBase2() == ShAmtC) {
1675 return BinaryOperator::CreateNSWAdd(
1676 V1: X, V2: Builder.CreateLShr(LHS: X, RHS: ConstantInt::get(Ty, V: ShAmtC), Name: "",
1677 isExact: I.isExact()));
1678 }
1679 }
1680
1681 // Try to narrow bswap.
1682 // In the case where the shift amount equals the bitwidth difference, the
1683 // shift is eliminated.
1684 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::bswap>(
1685 Op0: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))))))) {
1686 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1687 unsigned WidthDiff = BitWidth - SrcWidth;
1688 if (SrcWidth % 16 == 0) {
1689 Value *NarrowSwap = Builder.CreateUnaryIntrinsic(ID: Intrinsic::bswap, Op: X);
1690 if (ShAmtC >= WidthDiff) {
1691 // (bswap (zext X)) >> C --> zext (bswap X >> C')
1692 Value *NewShift = Builder.CreateLShr(LHS: NarrowSwap, RHS: ShAmtC - WidthDiff);
1693 return new ZExtInst(NewShift, Ty);
1694 } else {
1695 // (bswap (zext X)) >> C --> (zext (bswap X)) << C'
1696 Value *NewZExt = Builder.CreateZExt(V: NarrowSwap, DestTy: Ty);
1697 Constant *ShiftDiff = ConstantInt::get(Ty, V: WidthDiff - ShAmtC);
1698 return BinaryOperator::CreateShl(V1: NewZExt, V2: ShiftDiff);
1699 }
1700 }
1701 }
1702
1703 // Reduce add-carry of bools to logic:
1704 // ((zext BoolX) + (zext BoolY)) >> 1 --> zext (BoolX && BoolY)
1705 Value *BoolX, *BoolY;
1706 if (ShAmtC == 1 && match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1707 match(V: X, P: m_ZExt(Op: m_Value(V&: BoolX))) && match(V: Y, P: m_ZExt(Op: m_Value(V&: BoolY))) &&
1708 BoolX->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
1709 BoolY->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
1710 (X->hasOneUse() || Y->hasOneUse() || Op0->hasOneUse())) {
1711 Value *And = Builder.CreateAnd(LHS: BoolX, RHS: BoolY);
1712 return new ZExtInst(And, Ty);
1713 }
1714 }
1715
1716 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
1717 if (setShiftFlags(I, Q))
1718 return &I;
1719
1720 // Transform (x << y) >> y to x & (-1 >> y)
1721 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: X), R: m_Specific(V: Op1))))) {
1722 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1723 Value *Mask = Builder.CreateLShr(LHS: AllOnes, RHS: Op1);
1724 return BinaryOperator::CreateAnd(V1: Mask, V2: X);
1725 }
1726
1727 // Transform (-1 << y) >> y to -1 >> y
1728 if (match(V: Op0, P: m_Shl(L: m_AllOnes(), R: m_Specific(V: Op1)))) {
1729 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty);
1730 return BinaryOperator::CreateLShr(V1: AllOnes, V2: Op1);
1731 }
1732
1733 if (Instruction *Overflow = foldLShrOverflowBit(I))
1734 return Overflow;
1735
1736 // Transform ((pow2 << x) >> cttz(pow2 << y)) -> ((1 << x) >> y)
1737 Value *Shl0_Op0, *Shl0_Op1, *Shl1_Op1;
1738 BinaryOperator *Shl1;
1739 if (match(V: Op0, P: m_Shl(L: m_Value(V&: Shl0_Op0), R: m_Value(V&: Shl0_Op1))) &&
1740 match(V: Op1, P: m_Cttz(Op0: m_BinOp(I&: Shl1), Op1: m_Value())) &&
1741 match(V: Shl1, P: m_Shl(L: m_Specific(V: Shl0_Op0), R: m_Value(V&: Shl1_Op1))) &&
1742 isKnownToBeAPowerOfTwo(V: Shl0_Op0, /*OrZero=*/true, CxtI: &I)) {
1743 auto *Shl0 = cast<BinaryOperator>(Val: Op0);
1744 bool HasNUW = Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap();
1745 bool HasNSW = Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap();
1746 if (HasNUW || HasNSW) {
1747 Value *NewShl = Builder.CreateShl(LHS: ConstantInt::get(Ty: Shl1->getType(), V: 1),
1748 RHS: Shl0_Op1, Name: "", HasNUW, HasNSW);
1749 return BinaryOperator::CreateLShr(V1: NewShl, V2: Shl1_Op1);
1750 }
1751 }
1752 return nullptr;
1753}
1754
1755Instruction *
1756InstCombinerImpl::foldVariableSignZeroExtensionOfVariableHighBitExtract(
1757 BinaryOperator &OldAShr) {
1758 assert(OldAShr.getOpcode() == Instruction::AShr &&
1759 "Must be called with arithmetic right-shift instruction only.");
1760
1761 // Check that constant C is a splat of the element-wise bitwidth of V.
1762 auto BitWidthSplat = [](Constant *C, Value *V) {
1763 return match(
1764 V: C, P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_EQ,
1765 Threshold: APInt(C->getType()->getScalarSizeInBits(),
1766 V->getType()->getScalarSizeInBits())));
1767 };
1768
1769 // It should look like variable-length sign-extension on the outside:
1770 // (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1771 Value *NBits;
1772 Instruction *MaybeTrunc;
1773 Constant *C1, *C2;
1774 if (!match(V: &OldAShr,
1775 P: m_AShr(L: m_Shl(L: m_Instruction(I&: MaybeTrunc),
1776 R: m_ZExtOrSelf(Op: m_Sub(L: m_Constant(C&: C1),
1777 R: m_ZExtOrSelf(Op: m_Value(V&: NBits))))),
1778 R: m_ZExtOrSelf(Op: m_Sub(L: m_Constant(C&: C2),
1779 R: m_ZExtOrSelf(Op: m_Deferred(V: NBits)))))) ||
1780 !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1781 return nullptr;
1782
1783 // There may or may not be a truncation after outer two shifts.
1784 Instruction *HighBitExtract;
1785 match(V: MaybeTrunc, P: m_TruncOrSelf(Op: m_Instruction(I&: HighBitExtract)));
1786 bool HadTrunc = MaybeTrunc != HighBitExtract;
1787
1788 // And finally, the innermost part of the pattern must be a right-shift.
1789 Value *X, *NumLowBitsToSkip;
1790 if (!match(V: HighBitExtract, P: m_Shr(L: m_Value(V&: X), R: m_Value(V&: NumLowBitsToSkip))))
1791 return nullptr;
1792
1793 // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1794 Constant *C0;
1795 if (!match(V: NumLowBitsToSkip,
1796 P: m_ZExtOrSelf(
1797 Op: m_Sub(L: m_Constant(C&: C0), R: m_ZExtOrSelf(Op: m_Specific(V: NBits))))) ||
1798 !BitWidthSplat(C0, HighBitExtract))
1799 return nullptr;
1800
1801 // Since the NBits is identical for all shifts, if the outermost and
1802 // innermost shifts are identical, then outermost shifts are redundant.
1803 // If we had truncation, do keep it though.
1804 if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1805 return replaceInstUsesWith(I&: OldAShr, V: MaybeTrunc);
1806
1807 // Else, if there was a truncation, then we need to ensure that one
1808 // instruction will go away.
1809 if (HadTrunc && !match(V: &OldAShr, P: m_c_BinOp(L: m_OneUse(SubPattern: m_Value()), R: m_Value())))
1810 return nullptr;
1811
1812 // Finally, bypass two innermost shifts, and perform the outermost shift on
1813 // the operands of the innermost shift.
1814 Instruction *NewAShr =
1815 BinaryOperator::Create(Op: OldAShr.getOpcode(), S1: X, S2: NumLowBitsToSkip);
1816 NewAShr->copyIRFlags(V: HighBitExtract); // We can preserve 'exact'-ness.
1817 if (!HadTrunc)
1818 return NewAShr;
1819
1820 Builder.Insert(I: NewAShr);
1821 return TruncInst::CreateTruncOrBitCast(S: NewAShr, Ty: OldAShr.getType());
1822}
1823
1824Instruction *InstCombinerImpl::visitAShr(BinaryOperator &I) {
1825 if (Value *V = simplifyAShrInst(Op0: I.getOperand(i_nocapture: 0), Op1: I.getOperand(i_nocapture: 1), IsExact: I.isExact(),
1826 Q: SQ.getWithInstruction(I: &I)))
1827 return replaceInstUsesWith(I, V);
1828
1829 if (Instruction *X = foldVectorBinop(Inst&: I))
1830 return X;
1831
1832 if (Instruction *R = commonShiftTransforms(I))
1833 return R;
1834
1835 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
1836 Type *Ty = I.getType();
1837 unsigned BitWidth = Ty->getScalarSizeInBits();
1838 const APInt *ShAmtAPInt;
1839 if (match(V: Op1, P: m_APInt(Res&: ShAmtAPInt)) && ShAmtAPInt->ult(RHS: BitWidth)) {
1840 unsigned ShAmt = ShAmtAPInt->getZExtValue();
1841
1842 // If the shift amount equals the difference in width of the destination
1843 // and source scalar types:
1844 // ashr (shl (zext X), C), C --> sext X
1845 Value *X;
1846 if (match(V: Op0, P: m_Shl(L: m_ZExt(Op: m_Value(V&: X)), R: m_Specific(V: Op1))) &&
1847 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1848 return new SExtInst(X, Ty);
1849
1850 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1851 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1852 const APInt *ShOp1;
1853 if (match(V: Op0, P: m_NSWShl(L: m_Value(V&: X), R: m_APInt(Res&: ShOp1))) &&
1854 ShOp1->ult(RHS: BitWidth)) {
1855 unsigned ShlAmt = ShOp1->getZExtValue();
1856 if (ShlAmt < ShAmt) {
1857 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1858 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShAmt - ShlAmt);
1859 auto *NewAShr = BinaryOperator::CreateAShr(V1: X, V2: ShiftDiff);
1860 NewAShr->setIsExact(I.isExact());
1861 return NewAShr;
1862 }
1863 if (ShlAmt > ShAmt) {
1864 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1865 Constant *ShiftDiff = ConstantInt::get(Ty, V: ShlAmt - ShAmt);
1866 auto *NewShl = BinaryOperator::Create(Op: Instruction::Shl, S1: X, S2: ShiftDiff);
1867 NewShl->setHasNoSignedWrap(true);
1868 return NewShl;
1869 }
1870 }
1871
1872 if (match(V: Op0, P: m_AShr(L: m_Value(V&: X), R: m_APInt(Res&: ShOp1))) &&
1873 ShOp1->ult(RHS: BitWidth)) {
1874 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1875 // Oversized arithmetic shifts replicate the sign bit.
1876 AmtSum = std::min(a: AmtSum, b: BitWidth - 1);
1877 // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1878 return BinaryOperator::CreateAShr(V1: X, V2: ConstantInt::get(Ty, V: AmtSum));
1879 }
1880
1881 if (match(V: Op0, P: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: X)))) &&
1882 (Ty->isVectorTy() || shouldChangeType(From: Ty, To: X->getType()))) {
1883 // ashr (sext X), C --> sext (ashr X, C')
1884 Type *SrcTy = X->getType();
1885 ShAmt = std::min(a: ShAmt, b: SrcTy->getScalarSizeInBits() - 1);
1886 Value *NewSh = Builder.CreateAShr(LHS: X, RHS: ConstantInt::get(Ty: SrcTy, V: ShAmt));
1887 return new SExtInst(NewSh, Ty);
1888 }
1889
1890 if (ShAmt == BitWidth - 1) {
1891 // ashr i32 or(X,-X), 31 --> sext (X != 0)
1892 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Or(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X)))))
1893 return new SExtInst(Builder.CreateIsNotNull(Arg: X), Ty);
1894
1895 // ashr i32 (X -nsw Y), 31 --> sext (X < Y)
1896 Value *Y;
1897 if (match(V: Op0, P: m_OneUse(SubPattern: m_NSWSub(L: m_Value(V&: X), R: m_Value(V&: Y)))))
1898 return new SExtInst(Builder.CreateICmpSLT(LHS: X, RHS: Y), Ty);
1899
1900 // ashr iN (X - 1) & ~X, N-1 --> sext (X == 0)
1901 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Add(L: m_Value(V&: X), R: m_AllOnes()),
1902 R: m_Not(V: m_Deferred(V: X))))))
1903 return new SExtInst(Builder.CreateIsNull(Arg: X), Ty);
1904 }
1905
1906 const APInt *MulC;
1907 if (match(V: Op0, P: m_OneUse(SubPattern: m_NSWMul(L: m_Value(V&: X), R: m_APInt(Res&: MulC)))) &&
1908 (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1909 MulC->logBase2() == ShAmt &&
1910 (ShAmt < BitWidth - 1))) /* Minus 1 for the sign bit */ {
1911
1912 // ashr (mul nsw (X, 2^N + 1)), N -> add nsw (X, ashr(X, N))
1913 auto *NewAdd = BinaryOperator::CreateNSWAdd(
1914 V1: X,
1915 V2: Builder.CreateAShr(LHS: X, RHS: ConstantInt::get(Ty, V: ShAmt), Name: "", isExact: I.isExact()));
1916 NewAdd->setHasNoUnsignedWrap(
1917 cast<OverflowingBinaryOperator>(Val: Op0)->hasNoUnsignedWrap());
1918 return NewAdd;
1919 }
1920 }
1921
1922 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
1923 if (setShiftFlags(I, Q))
1924 return &I;
1925
1926 // Prefer `-(x & 1)` over `(x << (bitwidth(x)-1)) a>> (bitwidth(x)-1)`
1927 // as the pattern to splat the lowest bit.
1928 // FIXME: iff X is already masked, we don't need the one-use check.
1929 Value *X;
1930 if (match(V: Op1, P: m_SpecificIntAllowPoison(V: BitWidth - 1)) &&
1931 match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: X),
1932 R: m_SpecificIntAllowPoison(V: BitWidth - 1))))) {
1933 Constant *Mask = ConstantInt::get(Ty, V: 1);
1934 // Retain the knowledge about the ignored lanes.
1935 Mask = Constant::mergeUndefsWith(
1936 C: Constant::mergeUndefsWith(C: Mask, Other: cast<Constant>(Val: Op1)),
1937 Other: cast<Constant>(Val: cast<Instruction>(Val: Op0)->getOperand(i: 1)));
1938 X = Builder.CreateAnd(LHS: X, RHS: Mask);
1939 return BinaryOperator::CreateNeg(Op: X);
1940 }
1941
1942 if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(OldAShr&: I))
1943 return R;
1944
1945 // See if we can turn a signed shr into an unsigned shr.
1946 if (MaskedValueIsZero(V: Op0, Mask: APInt::getSignMask(BitWidth), CxtI: &I)) {
1947 Instruction *Lshr = BinaryOperator::CreateLShr(V1: Op0, V2: Op1);
1948 Lshr->setIsExact(I.isExact());
1949 return Lshr;
1950 }
1951
1952 // ashr (xor %x, -1), %y --> xor (ashr %x, %y), -1
1953 if (match(V: Op0, P: m_OneUse(SubPattern: m_Not(V: m_Value(V&: X))))) {
1954 // Note that we must drop 'exact'-ness of the shift!
1955 // Note that we can't keep undef's in -1 vector constant!
1956 auto *NewAShr = Builder.CreateAShr(LHS: X, RHS: Op1, Name: Op0->getName() + ".not");
1957 return BinaryOperator::CreateNot(Op: NewAShr);
1958 }
1959
1960 return nullptr;
1961}
1962