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