LLVM 17.0.0git
InstCombineShifts.cpp
Go to the documentation of this file.
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"
18using namespace llvm;
19using namespace PatternMatch;
20
21#define DEBUG_TYPE "instcombine"
22
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 =
44 return MaximalRepresentableShiftAmount.uge(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.
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(Sh0,
65 m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(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(Sh0Op0,
75 m_Instruction(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(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(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(Sh0, m_Shr(m_Value(), m_Value())) &&
89 match(Sh1, m_Shr(m_Value(), 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(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
106 return nullptr;
107
108 // Can we fold (ShAmt0+ShAmt1) ?
109 auto *NewShAmt = dyn_cast_or_null<Constant>(
110 simplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false,
111 SQ.getWithInstruction(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?
118 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(NewShAmt,
130 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 // All good, we can do this fold.
140 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType());
141
142 BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
143
144 // The flags can only be propagated if there wasn't a trunc.
145 if (!Trunc) {
146 // If the pattern did not involve trunc, and both of the original shifts
147 // had the same flag set, preserve the flag.
148 if (ShiftOpcode == Instruction::BinaryOps::Shl) {
149 NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
150 Sh1->hasNoUnsignedWrap());
151 NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
152 Sh1->hasNoSignedWrap());
153 } else {
154 NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
155 }
156 }
157
158 Instruction *Ret = NewShift;
159 if (Trunc) {
160 Builder.Insert(NewShift);
161 Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
162 }
163
164 return Ret;
165}
166
167// If we have some pattern that leaves only some low bits set, and then performs
168// left-shift of those bits, if none of the bits that are left after the final
169// shift are modified by the mask, we can omit the mask.
170//
171// There are many variants to this pattern:
172// a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
173// b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt
174// c) (x & (-1 l>> MaskShAmt)) << ShiftShAmt
175// d) (x & ((-1 << MaskShAmt) l>> MaskShAmt)) << ShiftShAmt
176// e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
177// f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
178// All these patterns can be simplified to just:
179// x << ShiftShAmt
180// iff:
181// a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
182// c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
183static Instruction *
185 const SimplifyQuery &Q,
186 InstCombiner::BuilderTy &Builder) {
187 assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
188 "The input must be 'shl'!");
189
190 Value *Masked, *ShiftShAmt;
191 match(OuterShift,
192 m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt))));
193
194 // *If* there is a truncation between an outer shift and a possibly-mask,
195 // then said truncation *must* be one-use, else we can't perform the fold.
196 Value *Trunc;
197 if (match(Masked, m_CombineAnd(m_Trunc(m_Value(Masked)), m_Value(Trunc))) &&
198 !Trunc->hasOneUse())
199 return nullptr;
200
201 Type *NarrowestTy = OuterShift->getType();
202 Type *WidestTy = Masked->getType();
203 bool HadTrunc = WidestTy != NarrowestTy;
204
205 // The mask must be computed in a type twice as wide to ensure
206 // that no bits are lost if the sum-of-shifts is wider than the base type.
207 Type *ExtendedTy = WidestTy->getExtendedType();
208
209 Value *MaskShAmt;
210
211 // ((1 << MaskShAmt) - 1)
212 auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
213 // (~(-1 << maskNbits))
214 auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes());
215 // (-1 l>> MaskShAmt)
216 auto MaskC = m_LShr(m_AllOnes(), m_Value(MaskShAmt));
217 // ((-1 << MaskShAmt) l>> MaskShAmt)
218 auto MaskD =
219 m_LShr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
220
221 Value *X;
222 Constant *NewMask;
223
224 if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
225 // Peek through an optional zext of the shift amount.
226 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
227
228 // Verify that it would be safe to try to add those two shift amounts.
229 if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
230 MaskShAmt))
231 return nullptr;
232
233 // Can we simplify (MaskShAmt+ShiftShAmt) ?
234 auto *SumOfShAmts = dyn_cast_or_null<Constant>(simplifyAddInst(
235 MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
236 if (!SumOfShAmts)
237 return nullptr; // Did not simplify.
238 // In this pattern SumOfShAmts correlates with the number of low bits
239 // that shall remain in the root value (OuterShift).
240
241 // An extend of an undef value becomes zero because the high bits are never
242 // completely unknown. Replace the `undef` shift amounts with final
243 // shift bitwidth to ensure that the value remains undef when creating the
244 // subsequent shift op.
245 SumOfShAmts = Constant::replaceUndefsWith(
246 SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
247 ExtendedTy->getScalarSizeInBits()));
248 auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy);
249 // And compute the mask as usual: ~(-1 << (SumOfShAmts))
250 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
251 auto *ExtendedInvertedMask =
252 ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts);
253 NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
254 } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
255 match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
256 m_Deferred(MaskShAmt)))) {
257 // Peek through an optional zext of the shift amount.
258 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
259
260 // Verify that it would be safe to try to add those two shift amounts.
261 if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
262 MaskShAmt))
263 return nullptr;
264
265 // Can we simplify (ShiftShAmt-MaskShAmt) ?
266 auto *ShAmtsDiff = dyn_cast_or_null<Constant>(simplifySubInst(
267 ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
268 if (!ShAmtsDiff)
269 return nullptr; // Did not simplify.
270 // In this pattern ShAmtsDiff correlates with the number of high bits that
271 // shall be unset in the root value (OuterShift).
272
273 // An extend of an undef value becomes zero because the high bits are never
274 // completely unknown. Replace the `undef` shift amounts with negated
275 // bitwidth of innermost shift to ensure that the value remains undef when
276 // creating the subsequent shift op.
277 unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
278 ShAmtsDiff = Constant::replaceUndefsWith(
279 ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(),
280 -WidestTyBitWidth));
281 auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt(
282 ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
283 WidestTyBitWidth,
284 /*isSigned=*/false),
285 ShAmtsDiff),
286 ExtendedTy);
287 // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
288 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
289 NewMask =
290 ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear);
291 } else
292 return nullptr; // Don't know anything about this pattern.
293
294 NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
295
296 // Does this mask has any unset bits? If not then we can just not apply it.
297 bool NeedMask = !match(NewMask, m_AllOnes());
298
299 // If we need to apply a mask, there are several more restrictions we have.
300 if (NeedMask) {
301 // The old masking instruction must go away.
302 if (!Masked->hasOneUse())
303 return nullptr;
304 // The original "masking" instruction must not have been`ashr`.
305 if (match(Masked, m_AShr(m_Value(), m_Value())))
306 return nullptr;
307 }
308
309 // If we need to apply truncation, let's do it first, since we can.
310 // We have already ensured that the old truncation will go away.
311 if (HadTrunc)
312 X = Builder.CreateTrunc(X, NarrowestTy);
313
314 // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
315 // We didn't change the Type of this outermost shift, so we can just do it.
316 auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
317 OuterShift->getOperand(1));
318 if (!NeedMask)
319 return NewShift;
320
321 Builder.Insert(NewShift);
322 return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
323}
324
325/// If we have a shift-by-constant of a bin op (bitwise logic op or add/sub w/
326/// shl) that itself has a shift-by-constant operand with identical opcode, we
327/// may be able to convert that into 2 independent shifts followed by the logic
328/// op. This eliminates a use of an intermediate value (reduces dependency
329/// chain).
331 InstCombiner::BuilderTy &Builder) {
332 assert(I.isShift() && "Expected a shift as input");
333 auto *BinInst = dyn_cast<BinaryOperator>(I.getOperand(0));
334 if (!BinInst ||
335 (!BinInst->isBitwiseLogicOp() &&
336 BinInst->getOpcode() != Instruction::Add &&
337 BinInst->getOpcode() != Instruction::Sub) ||
338 !BinInst->hasOneUse())
339 return nullptr;
340
341 Constant *C0, *C1;
342 if (!match(I.getOperand(1), m_Constant(C1)))
343 return nullptr;
344
345 Instruction::BinaryOps ShiftOpcode = I.getOpcode();
346 // Transform for add/sub only works with shl.
347 if ((BinInst->getOpcode() == Instruction::Add ||
348 BinInst->getOpcode() == Instruction::Sub) &&
349 ShiftOpcode != Instruction::Shl)
350 return nullptr;
351
352 Type *Ty = I.getType();
353
354 // Find a matching one-use shift by constant. The fold is not valid if the sum
355 // of the shift values equals or exceeds bitwidth.
356 // TODO: Remove the one-use check if the other logic operand (Y) is constant.
357 Value *X, *Y;
358 auto matchFirstShift = [&](Value *V) {
359 APInt Threshold(Ty->getScalarSizeInBits(), Ty->getScalarSizeInBits());
360 return match(V,
361 m_OneUse(m_BinOp(ShiftOpcode, m_Value(X), m_Constant(C0)))) &&
364 };
365
366 // Logic ops and Add are commutative, so check each operand for a match. Sub
367 // is not so we cannot reoder if we match operand(1) and need to keep the
368 // operands in their original positions.
369 bool FirstShiftIsOp1 = false;
370 if (matchFirstShift(BinInst->getOperand(0)))
371 Y = BinInst->getOperand(1);
372 else if (matchFirstShift(BinInst->getOperand(1))) {
373 Y = BinInst->getOperand(0);
374 FirstShiftIsOp1 = BinInst->getOpcode() == Instruction::Sub;
375 } else
376 return nullptr;
377
378 // shift (binop (shift X, C0), Y), C1 -> binop (shift X, C0+C1), (shift Y, C1)
379 Constant *ShiftSumC = ConstantExpr::getAdd(C0, C1);
380 Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
381 Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, C1);
382 Value *Op1 = FirstShiftIsOp1 ? NewShift2 : NewShift1;
383 Value *Op2 = FirstShiftIsOp1 ? NewShift1 : NewShift2;
384 return BinaryOperator::Create(BinInst->getOpcode(), Op1, Op2);
385}
386
389 return Phi;
390
391 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
392 assert(Op0->getType() == Op1->getType());
393 Type *Ty = I.getType();
394
395 // If the shift amount is a one-use `sext`, we can demote it to `zext`.
396 Value *Y;
397 if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
398 Value *NewExt = Builder.CreateZExt(Y, Ty, Op1->getName());
399 return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
400 }
401
402 // See if we can fold away this shift.
404 return &I;
405
406 // Try to fold constant and into select arguments.
407 if (isa<Constant>(Op0))
408 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
409 if (Instruction *R = FoldOpIntoSelect(I, SI))
410 return R;
411
412 if (Constant *CUI = dyn_cast<Constant>(Op1))
413 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
414 return Res;
415
416 if (auto *NewShift = cast_or_null<Instruction>(
418 return NewShift;
419
420 // Pre-shift a constant shifted by a variable amount with constant offset:
421 // C shift (A add nuw C1) --> (C shift C1) shift A
422 Value *A;
423 Constant *C, *C1;
424 if (match(Op0, m_Constant(C)) &&
425 match(Op1, m_NUWAdd(m_Value(A), m_Constant(C1)))) {
426 Value *NewC = Builder.CreateBinOp(I.getOpcode(), C, C1);
427 return BinaryOperator::Create(I.getOpcode(), NewC, A);
428 }
429
430 unsigned BitWidth = Ty->getScalarSizeInBits();
431
432 const APInt *AC, *AddC;
433 // Try to pre-shift a constant shifted by a variable amount added with a
434 // negative number:
435 // C << (X - AddC) --> (C >> AddC) << X
436 // and
437 // C >> (X - AddC) --> (C << AddC) >> X
438 if (match(Op0, m_APInt(AC)) && match(Op1, m_Add(m_Value(A), m_APInt(AddC))) &&
439 AddC->isNegative() && (-*AddC).ult(BitWidth)) {
440 assert(!AC->isZero() && "Expected simplify of shifted zero");
441 unsigned PosOffset = (-*AddC).getZExtValue();
442
443 auto isSuitableForPreShift = [PosOffset, &I, AC]() {
444 switch (I.getOpcode()) {
445 default:
446 return false;
447 case Instruction::Shl:
448 return (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) &&
449 AC->eq(AC->lshr(PosOffset).shl(PosOffset));
450 case Instruction::LShr:
451 return I.isExact() && AC->eq(AC->shl(PosOffset).lshr(PosOffset));
452 case Instruction::AShr:
453 return I.isExact() && AC->eq(AC->shl(PosOffset).ashr(PosOffset));
454 }
455 };
456 if (isSuitableForPreShift()) {
457 Constant *NewC = ConstantInt::get(Ty, I.getOpcode() == Instruction::Shl
458 ? AC->lshr(PosOffset)
459 : AC->shl(PosOffset));
460 BinaryOperator *NewShiftOp =
461 BinaryOperator::Create(I.getOpcode(), NewC, A);
462 if (I.getOpcode() == Instruction::Shl) {
463 NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
464 } else {
465 NewShiftOp->setIsExact();
466 }
467 return NewShiftOp;
468 }
469 }
470
471 // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2.
472 // Because shifts by negative values (which could occur if A were negative)
473 // are undefined.
474 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Constant(C))) &&
475 match(C, m_Power2())) {
476 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
477 // demand the sign bit (and many others) here??
479 Value *Rem = Builder.CreateAnd(A, Mask, Op1->getName());
480 return replaceOperand(I, 1, Rem);
481 }
482
484 return Logic;
485
486 if (match(Op1, m_Or(m_Value(), m_SpecificInt(BitWidth - 1))))
487 return replaceOperand(I, 1, ConstantInt::get(Ty, BitWidth - 1));
488
489 return nullptr;
490}
491
492/// Return true if we can simplify two logical (either left or right) shifts
493/// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
494static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
495 Instruction *InnerShift,
496 InstCombinerImpl &IC, Instruction *CxtI) {
497 assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
498
499 // We need constant scalar or constant splat shifts.
500 const APInt *InnerShiftConst;
501 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
502 return false;
503
504 // Two logical shifts in the same direction:
505 // shl (shl X, C1), C2 --> shl X, C1 + C2
506 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
507 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
508 if (IsInnerShl == IsOuterShl)
509 return true;
510
511 // Equal shift amounts in opposite directions become bitwise 'and':
512 // lshr (shl X, C), C --> and X, C'
513 // shl (lshr X, C), C --> and X, C'
514 if (*InnerShiftConst == OuterShAmt)
515 return true;
516
517 // If the 2nd shift is bigger than the 1st, we can fold:
518 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
519 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
520 // but it isn't profitable unless we know the and'd out bits are already zero.
521 // Also, check that the inner shift is valid (less than the type width) or
522 // we'll crash trying to produce the bit mask for the 'and'.
523 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
524 if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
525 unsigned InnerShAmt = InnerShiftConst->getZExtValue();
526 unsigned MaskShift =
527 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
528 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
529 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI))
530 return true;
531 }
532
533 return false;
534}
535
536/// See if we can compute the specified value, but shifted logically to the left
537/// or right by some number of bits. This should return true if the expression
538/// can be computed for the same cost as the current expression tree. This is
539/// used to eliminate extraneous shifting from things like:
540/// %C = shl i128 %A, 64
541/// %D = shl i128 %B, 96
542/// %E = or i128 %C, %D
543/// %F = lshr i128 %E, 64
544/// where the client will ask if E can be computed shifted right by 64-bits. If
545/// this succeeds, getShiftedValue() will be called to produce the value.
546static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
547 InstCombinerImpl &IC, Instruction *CxtI) {
548 // We can always evaluate constants shifted.
549 if (isa<Constant>(V))
550 return true;
551
552 Instruction *I = dyn_cast<Instruction>(V);
553 if (!I) return false;
554
555 // We can't mutate something that has multiple uses: doing so would
556 // require duplicating the instruction in general, which isn't profitable.
557 if (!I->hasOneUse()) return false;
558
559 switch (I->getOpcode()) {
560 default: return false;
561 case Instruction::And:
562 case Instruction::Or:
563 case Instruction::Xor:
564 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
565 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
566 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
567
568 case Instruction::Shl:
569 case Instruction::LShr:
570 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
571
572 case Instruction::Select: {
573 SelectInst *SI = cast<SelectInst>(I);
574 Value *TrueVal = SI->getTrueValue();
575 Value *FalseVal = SI->getFalseValue();
576 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
577 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
578 }
579 case Instruction::PHI: {
580 // We can change a phi if we can change all operands. Note that we never
581 // get into trouble with cyclic PHIs here because we only consider
582 // instructions with a single use.
583 PHINode *PN = cast<PHINode>(I);
584 for (Value *IncValue : PN->incoming_values())
585 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
586 return false;
587 return true;
588 }
589 case Instruction::Mul: {
590 const APInt *MulConst;
591 // We can fold (shr (mul X, -(1 << C)), C) -> (and (neg X), C`)
592 return !IsLeftShift && match(I->getOperand(1), m_APInt(MulConst)) &&
593 MulConst->isNegatedPowerOf2() && MulConst->countr_zero() == NumBits;
594 }
595 }
596}
597
598/// Fold OuterShift (InnerShift X, C1), C2.
599/// See canEvaluateShiftedShift() for the constraints on these instructions.
600static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
601 bool IsOuterShl,
602 InstCombiner::BuilderTy &Builder) {
603 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
604 Type *ShType = InnerShift->getType();
605 unsigned TypeWidth = ShType->getScalarSizeInBits();
606
607 // We only accept shifts-by-a-constant in canEvaluateShifted().
608 const APInt *C1;
609 match(InnerShift->getOperand(1), m_APInt(C1));
610 unsigned InnerShAmt = C1->getZExtValue();
611
612 // Change the shift amount and clear the appropriate IR flags.
613 auto NewInnerShift = [&](unsigned ShAmt) {
614 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
615 if (IsInnerShl) {
616 InnerShift->setHasNoUnsignedWrap(false);
617 InnerShift->setHasNoSignedWrap(false);
618 } else {
619 InnerShift->setIsExact(false);
620 }
621 return InnerShift;
622 };
623
624 // Two logical shifts in the same direction:
625 // shl (shl X, C1), C2 --> shl X, C1 + C2
626 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
627 if (IsInnerShl == IsOuterShl) {
628 // If this is an oversized composite shift, then unsigned shifts get 0.
629 if (InnerShAmt + OuterShAmt >= TypeWidth)
630 return Constant::getNullValue(ShType);
631
632 return NewInnerShift(InnerShAmt + OuterShAmt);
633 }
634
635 // Equal shift amounts in opposite directions become bitwise 'and':
636 // lshr (shl X, C), C --> and X, C'
637 // shl (lshr X, C), C --> and X, C'
638 if (InnerShAmt == OuterShAmt) {
639 APInt Mask = IsInnerShl
640 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
641 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
642 Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
643 ConstantInt::get(ShType, Mask));
644 if (auto *AndI = dyn_cast<Instruction>(And)) {
645 AndI->moveBefore(InnerShift);
646 AndI->takeName(InnerShift);
647 }
648 return And;
649 }
650
651 assert(InnerShAmt > OuterShAmt &&
652 "Unexpected opposite direction logical shift pair");
653
654 // In general, we would need an 'and' for this transform, but
655 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
656 // lshr (shl X, C1), C2 --> shl X, C1 - C2
657 // shl (lshr X, C1), C2 --> lshr X, C1 - C2
658 return NewInnerShift(InnerShAmt - OuterShAmt);
659}
660
661/// When canEvaluateShifted() returns true for an expression, this function
662/// inserts the new computation that produces the shifted value.
663static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
664 InstCombinerImpl &IC, const DataLayout &DL) {
665 // We can always evaluate constants shifted.
666 if (Constant *C = dyn_cast<Constant>(V)) {
667 if (isLeftShift)
668 return IC.Builder.CreateShl(C, NumBits);
669 else
670 return IC.Builder.CreateLShr(C, NumBits);
671 }
672
673 Instruction *I = cast<Instruction>(V);
674 IC.addToWorklist(I);
675
676 switch (I->getOpcode()) {
677 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
678 case Instruction::And:
679 case Instruction::Or:
680 case Instruction::Xor:
681 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
682 I->setOperand(
683 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
684 I->setOperand(
685 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
686 return I;
687
688 case Instruction::Shl:
689 case Instruction::LShr:
690 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
691 IC.Builder);
692
693 case Instruction::Select:
694 I->setOperand(
695 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
696 I->setOperand(
697 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
698 return I;
699 case Instruction::PHI: {
700 // We can change a phi if we can change all operands. Note that we never
701 // get into trouble with cyclic PHIs here because we only consider
702 // instructions with a single use.
703 PHINode *PN = cast<PHINode>(I);
704 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
706 isLeftShift, IC, DL));
707 return PN;
708 }
709 case Instruction::Mul: {
710 assert(!isLeftShift && "Unexpected shift direction!");
711 auto *Neg = BinaryOperator::CreateNeg(I->getOperand(0));
712 IC.InsertNewInstWith(Neg, *I);
713 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
714 APInt Mask = APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits);
715 auto *And = BinaryOperator::CreateAnd(Neg,
716 ConstantInt::get(I->getType(), Mask));
717 And->takeName(I);
718 return IC.InsertNewInstWith(And, *I);
719 }
720 }
721}
722
723// If this is a bitwise operator or add with a constant RHS we might be able
724// to pull it through a shift.
726 BinaryOperator *BO) {
727 switch (BO->getOpcode()) {
728 default:
729 return false; // Do not perform transform!
730 case Instruction::Add:
731 return Shift.getOpcode() == Instruction::Shl;
732 case Instruction::Or:
733 case Instruction::And:
734 return true;
735 case Instruction::Xor:
736 // Do not change a 'not' of logical shift because that would create a normal
737 // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
738 return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
739 }
740}
741
743 BinaryOperator &I) {
744 // (C2 << X) << C1 --> (C2 << C1) << X
745 // (C2 >> X) >> C1 --> (C2 >> C1) >> X
746 Constant *C2;
747 Value *X;
748 if (match(Op0, m_BinOp(I.getOpcode(), m_Constant(C2), m_Value(X))))
750 I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), C2, C1), X);
751
752 bool IsLeftShift = I.getOpcode() == Instruction::Shl;
753 Type *Ty = I.getType();
754 unsigned TypeBits = Ty->getScalarSizeInBits();
755
756 // (X / +DivC) >> (Width - 1) --> ext (X <= -DivC)
757 // (X / -DivC) >> (Width - 1) --> ext (X >= +DivC)
758 const APInt *DivC;
759 if (!IsLeftShift && match(C1, m_SpecificIntAllowUndef(TypeBits - 1)) &&
760 match(Op0, m_SDiv(m_Value(X), m_APInt(DivC))) && !DivC->isZero() &&
761 !DivC->isMinSignedValue()) {
762 Constant *NegDivC = ConstantInt::get(Ty, -(*DivC));
765 Value *Cmp = Builder.CreateICmp(Pred, X, NegDivC);
766 auto ExtOpcode = (I.getOpcode() == Instruction::AShr) ? Instruction::SExt
767 : Instruction::ZExt;
768 return CastInst::Create(ExtOpcode, Cmp, Ty);
769 }
770
771 const APInt *Op1C;
772 if (!match(C1, m_APInt(Op1C)))
773 return nullptr;
774
775 assert(!Op1C->uge(TypeBits) &&
776 "Shift over the type width should have been removed already");
777
778 // See if we can propagate this shift into the input, this covers the trivial
779 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
780 if (I.getOpcode() != Instruction::AShr &&
781 canEvaluateShifted(Op0, Op1C->getZExtValue(), IsLeftShift, *this, &I)) {
783 dbgs() << "ICE: GetShiftedValue propagating shift through expression"
784 " to eliminate shift:\n IN: "
785 << *Op0 << "\n SH: " << I << "\n");
786
787 return replaceInstUsesWith(
788 I, getShiftedValue(Op0, Op1C->getZExtValue(), IsLeftShift, *this, DL));
789 }
790
791 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
792 return FoldedShift;
793
794 if (!Op0->hasOneUse())
795 return nullptr;
796
797 if (auto *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
798 // If the operand is a bitwise operator with a constant RHS, and the
799 // shift is the only use, we can pull it out of the shift.
800 const APInt *Op0C;
801 if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
802 if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
803 Value *NewRHS =
804 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(1), C1);
805
806 Value *NewShift =
807 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), C1);
808 NewShift->takeName(Op0BO);
809
810 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, NewRHS);
811 }
812 }
813 }
814
815 // If we have a select that conditionally executes some binary operator,
816 // see if we can pull it the select and operator through the shift.
817 //
818 // For example, turning:
819 // shl (select C, (add X, C1), X), C2
820 // Into:
821 // Y = shl X, C2
822 // select C, (add Y, C1 << C2), Y
823 Value *Cond;
824 BinaryOperator *TBO;
825 Value *FalseVal;
826 if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
827 m_Value(FalseVal)))) {
828 const APInt *C;
829 if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
830 match(TBO->getOperand(1), m_APInt(C)) &&
832 Value *NewRHS =
833 Builder.CreateBinOp(I.getOpcode(), TBO->getOperand(1), C1);
834
835 Value *NewShift = Builder.CreateBinOp(I.getOpcode(), FalseVal, C1);
836 Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, NewRHS);
837 return SelectInst::Create(Cond, NewOp, NewShift);
838 }
839 }
840
841 BinaryOperator *FBO;
842 Value *TrueVal;
843 if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
844 m_OneUse(m_BinOp(FBO))))) {
845 const APInt *C;
846 if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
847 match(FBO->getOperand(1), m_APInt(C)) &&
849 Value *NewRHS =
850 Builder.CreateBinOp(I.getOpcode(), FBO->getOperand(1), C1);
851
852 Value *NewShift = Builder.CreateBinOp(I.getOpcode(), TrueVal, C1);
853 Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, NewRHS);
854 return SelectInst::Create(Cond, NewShift, NewOp);
855 }
856 }
857
858 return nullptr;
859}
860
861// Tries to perform
862// (lshr (add (zext X), (zext Y)), K)
863// -> (icmp ult (add X, Y), X)
864// where
865// - The add's operands are zexts from a K-bits integer to a bigger type.
866// - The add is only used by the shr, or by iK (or narrower) truncates.
867// - The lshr type has more than 2 bits (other types are boolean math).
868// - K > 1
869// note that
870// - The resulting add cannot have nuw/nsw, else on overflow we get a
871// poison value and the transform isn't legal anymore.
872Instruction *InstCombinerImpl::foldLShrOverflowBit(BinaryOperator &I) {
873 assert(I.getOpcode() == Instruction::LShr);
874
875 Value *Add = I.getOperand(0);
876 Value *ShiftAmt = I.getOperand(1);
877 Type *Ty = I.getType();
878
879 if (Ty->getScalarSizeInBits() < 3)
880 return nullptr;
881
882 const APInt *ShAmtAPInt = nullptr;
883 Value *X = nullptr, *Y = nullptr;
884 if (!match(ShiftAmt, m_APInt(ShAmtAPInt)) ||
885 !match(Add,
887 return nullptr;
888
889 const unsigned ShAmt = ShAmtAPInt->getZExtValue();
890 if (ShAmt == 1)
891 return nullptr;
892
893 // X/Y are zexts from `ShAmt`-sized ints.
894 if (X->getType()->getScalarSizeInBits() != ShAmt ||
895 Y->getType()->getScalarSizeInBits() != ShAmt)
896 return nullptr;
897
898 // Make sure that `Add` is only used by `I` and `ShAmt`-truncates.
899 if (!Add->hasOneUse()) {
900 for (User *U : Add->users()) {
901 if (U == &I)
902 continue;
903
904 TruncInst *Trunc = dyn_cast<TruncInst>(U);
905 if (!Trunc || Trunc->getType()->getScalarSizeInBits() > ShAmt)
906 return nullptr;
907 }
908 }
909
910 // Insert at Add so that the newly created `NarrowAdd` will dominate it's
911 // users (i.e. `Add`'s users).
912 Instruction *AddInst = cast<Instruction>(Add);
913 Builder.SetInsertPoint(AddInst);
914
915 Value *NarrowAdd = Builder.CreateAdd(X, Y, "add.narrowed");
916 Value *Overflow =
917 Builder.CreateICmpULT(NarrowAdd, X, "add.narrowed.overflow");
918
919 // Replace the uses of the original add with a zext of the
920 // NarrowAdd's result. Note that all users at this stage are known to
921 // be ShAmt-sized truncs, or the lshr itself.
922 if (!Add->hasOneUse())
923 replaceInstUsesWith(*AddInst, Builder.CreateZExt(NarrowAdd, Ty));
924
925 // Replace the LShr with a zext of the overflow check.
926 return new ZExtInst(Overflow, Ty);
927}
928
931
932 if (Value *V = simplifyShlInst(I.getOperand(0), I.getOperand(1),
933 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
934 return replaceInstUsesWith(I, V);
935
937 return X;
938
940 return V;
941
943 return V;
944
945 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
946 Type *Ty = I.getType();
947 unsigned BitWidth = Ty->getScalarSizeInBits();
948
949 const APInt *C;
950 if (match(Op1, m_APInt(C))) {
951 unsigned ShAmtC = C->getZExtValue();
952
953 // shl (zext X), C --> zext (shl X, C)
954 // This is only valid if X would have zeros shifted out.
955 Value *X;
956 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
957 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
958 if (ShAmtC < SrcWidth &&
959 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmtC), 0, &I))
960 return new ZExtInst(Builder.CreateShl(X, ShAmtC), Ty);
961 }
962
963 // (X >> C) << C --> X & (-1 << C)
964 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
966 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
967 }
968
969 const APInt *C1;
970 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(C1)))) &&
971 C1->ult(BitWidth)) {
972 unsigned ShrAmt = C1->getZExtValue();
973 if (ShrAmt < ShAmtC) {
974 // If C1 < C: (X >>?,exact C1) << C --> X << (C - C1)
975 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
976 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
977 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
978 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
979 return NewShl;
980 }
981 if (ShrAmt > ShAmtC) {
982 // If C1 > C: (X >>?exact C1) << C --> X >>?exact (C1 - C)
983 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
984 auto *NewShr = BinaryOperator::Create(
985 cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
986 NewShr->setIsExact(true);
987 return NewShr;
988 }
989 }
990
991 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_APInt(C1)))) &&
992 C1->ult(BitWidth)) {
993 unsigned ShrAmt = C1->getZExtValue();
994 if (ShrAmt < ShAmtC) {
995 // If C1 < C: (X >>? C1) << C --> (X << (C - C1)) & (-1 << C)
996 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
997 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
998 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
999 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1000 Builder.Insert(NewShl);
1002 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1003 }
1004 if (ShrAmt > ShAmtC) {
1005 // If C1 > C: (X >>? C1) << C --> (X >>? (C1 - C)) & (-1 << C)
1006 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
1007 auto *OldShr = cast<BinaryOperator>(Op0);
1008 auto *NewShr =
1009 BinaryOperator::Create(OldShr->getOpcode(), X, ShiftDiff);
1010 NewShr->setIsExact(OldShr->isExact());
1011 Builder.Insert(NewShr);
1013 return BinaryOperator::CreateAnd(NewShr, ConstantInt::get(Ty, Mask));
1014 }
1015 }
1016
1017 // Similar to above, but look through an intermediate trunc instruction.
1018 BinaryOperator *Shr;
1019 if (match(Op0, m_OneUse(m_Trunc(m_OneUse(m_BinOp(Shr))))) &&
1020 match(Shr, m_Shr(m_Value(X), m_APInt(C1)))) {
1021 // The larger shift direction survives through the transform.
1022 unsigned ShrAmtC = C1->getZExtValue();
1023 unsigned ShDiff = ShrAmtC > ShAmtC ? ShrAmtC - ShAmtC : ShAmtC - ShrAmtC;
1024 Constant *ShiftDiffC = ConstantInt::get(X->getType(), ShDiff);
1025 auto ShiftOpc = ShrAmtC > ShAmtC ? Shr->getOpcode() : Instruction::Shl;
1026
1027 // If C1 > C:
1028 // (trunc (X >> C1)) << C --> (trunc (X >> (C1 - C))) && (-1 << C)
1029 // If C > C1:
1030 // (trunc (X >> C1)) << C --> (trunc (X << (C - C1))) && (-1 << C)
1031 Value *NewShift = Builder.CreateBinOp(ShiftOpc, X, ShiftDiffC, "sh.diff");
1032 Value *Trunc = Builder.CreateTrunc(NewShift, Ty, "tr.sh.diff");
1034 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, Mask));
1035 }
1036
1037 if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1038 unsigned AmtSum = ShAmtC + C1->getZExtValue();
1039 // Oversized shifts are simplified to zero in InstSimplify.
1040 if (AmtSum < BitWidth)
1041 // (X << C1) << C2 --> X << (C1 + C2)
1042 return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum));
1043 }
1044
1045 // If we have an opposite shift by the same amount, we may be able to
1046 // reorder binops and shifts to eliminate math/logic.
1047 auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1048 switch (BinOpcode) {
1049 default:
1050 return false;
1051 case Instruction::Add:
1052 case Instruction::And:
1053 case Instruction::Or:
1054 case Instruction::Xor:
1055 case Instruction::Sub:
1056 // NOTE: Sub is not commutable and the tranforms below may not be valid
1057 // when the shift-right is operand 1 (RHS) of the sub.
1058 return true;
1059 }
1060 };
1061 BinaryOperator *Op0BO;
1062 if (match(Op0, m_OneUse(m_BinOp(Op0BO))) &&
1063 isSuitableBinOpcode(Op0BO->getOpcode())) {
1064 // Commute so shift-right is on LHS of the binop.
1065 // (Y bop (X >> C)) << C -> ((X >> C) bop Y) << C
1066 // (Y bop ((X >> C) & CC)) << C -> (((X >> C) & CC) bop Y) << C
1067 Value *Shr = Op0BO->getOperand(0);
1068 Value *Y = Op0BO->getOperand(1);
1069 Value *X;
1070 const APInt *CC;
1071 if (Op0BO->isCommutative() && Y->hasOneUse() &&
1072 (match(Y, m_Shr(m_Value(), m_Specific(Op1))) ||
1074 m_APInt(CC)))))
1075 std::swap(Shr, Y);
1076
1077 // ((X >> C) bop Y) << C -> (X bop (Y << C)) & (~0 << C)
1078 if (match(Shr, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1079 // Y << C
1080 Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1081 // (X bop (Y << C))
1082 Value *B =
1083 Builder.CreateBinOp(Op0BO->getOpcode(), X, YS, Shr->getName());
1084 unsigned Op1Val = C->getLimitedValue(BitWidth);
1085 APInt Bits = APInt::getHighBitsSet(BitWidth, BitWidth - Op1Val);
1086 Constant *Mask = ConstantInt::get(Ty, Bits);
1087 return BinaryOperator::CreateAnd(B, Mask);
1088 }
1089
1090 // (((X >> C) & CC) bop Y) << C -> (X & (CC << C)) bop (Y << C)
1091 if (match(Shr,
1093 m_APInt(CC))))) {
1094 // Y << C
1095 Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1096 // X & (CC << C)
1097 Value *M = Builder.CreateAnd(X, ConstantInt::get(Ty, CC->shl(*C)),
1098 X->getName() + ".mask");
1099 return BinaryOperator::Create(Op0BO->getOpcode(), M, YS);
1100 }
1101 }
1102
1103 // (C1 - X) << C --> (C1 << C) - (X << C)
1104 if (match(Op0, m_OneUse(m_Sub(m_APInt(C1), m_Value(X))))) {
1105 Constant *NewLHS = ConstantInt::get(Ty, C1->shl(*C));
1106 Value *NewShift = Builder.CreateShl(X, Op1);
1107 return BinaryOperator::CreateSub(NewLHS, NewShift);
1108 }
1109
1110 // If the shifted-out value is known-zero, then this is a NUW shift.
1111 if (!I.hasNoUnsignedWrap() &&
1113 &I)) {
1114 I.setHasNoUnsignedWrap();
1115 return &I;
1116 }
1117
1118 // If the shifted-out value is all signbits, then this is a NSW shift.
1119 if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmtC) {
1120 I.setHasNoSignedWrap();
1121 return &I;
1122 }
1123 }
1124
1125 // Transform (x >> y) << y to x & (-1 << y)
1126 // Valid for any type of right-shift.
1127 Value *X;
1128 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1130 Value *Mask = Builder.CreateShl(AllOnes, Op1);
1131 return BinaryOperator::CreateAnd(Mask, X);
1132 }
1133
1134 Constant *C1;
1135 if (match(Op1, m_Constant(C1))) {
1136 Constant *C2;
1137 Value *X;
1138 // (X * C2) << C1 --> X * (C2 << C1)
1139 if (match(Op0, m_Mul(m_Value(X), m_Constant(C2))))
1140 return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1));
1141
1142 // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1143 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1144 auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1);
1146 }
1147 }
1148
1149 if (match(Op0, m_One())) {
1150 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1151 if (match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1152 return BinaryOperator::CreateLShr(
1154
1155 // Canonicalize "extract lowest set bit" using cttz to and-with-negate:
1156 // 1 << (cttz X) --> -X & X
1157 if (match(Op1,
1158 m_OneUse(m_Intrinsic<Intrinsic::cttz>(m_Value(X), m_Value())))) {
1159 Value *NegX = Builder.CreateNeg(X, "neg");
1160 return BinaryOperator::CreateAnd(NegX, X);
1161 }
1162
1163 // The only way to shift out the 1 is with an over-shift, so that would
1164 // be poison with or without "nuw". Undef is excluded because (undef << X)
1165 // is not undef (it is zero).
1166 Constant *ConstantOne = cast<Constant>(Op0);
1167 if (!I.hasNoUnsignedWrap() && !ConstantOne->containsUndefElement()) {
1168 I.setHasNoUnsignedWrap();
1169 return &I;
1170 }
1171 }
1172
1173 return nullptr;
1174}
1175
1177 if (Value *V = simplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1179 return replaceInstUsesWith(I, V);
1180
1182 return X;
1183
1185 return R;
1186
1187 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1188 Type *Ty = I.getType();
1189 Value *X;
1190 const APInt *C;
1191 unsigned BitWidth = Ty->getScalarSizeInBits();
1192
1193 // (iN (~X) u>> (N - 1)) --> zext (X > -1)
1194 if (match(Op0, m_OneUse(m_Not(m_Value(X)))) &&
1196 return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
1197
1198 if (match(Op1, m_APInt(C))) {
1199 unsigned ShAmtC = C->getZExtValue();
1200 auto *II = dyn_cast<IntrinsicInst>(Op0);
1201 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmtC &&
1202 (II->getIntrinsicID() == Intrinsic::ctlz ||
1203 II->getIntrinsicID() == Intrinsic::cttz ||
1204 II->getIntrinsicID() == Intrinsic::ctpop)) {
1205 // ctlz.i32(x)>>5 --> zext(x == 0)
1206 // cttz.i32(x)>>5 --> zext(x == 0)
1207 // ctpop.i32(x)>>5 --> zext(x == -1)
1208 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1209 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1210 Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1211 return new ZExtInst(Cmp, Ty);
1212 }
1213
1214 Value *X;
1215 const APInt *C1;
1216 if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1217 if (C1->ult(ShAmtC)) {
1218 unsigned ShlAmtC = C1->getZExtValue();
1219 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShlAmtC);
1220 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1221 // (X <<nuw C1) >>u C --> X >>u (C - C1)
1222 auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1223 NewLShr->setIsExact(I.isExact());
1224 return NewLShr;
1225 }
1226 if (Op0->hasOneUse()) {
1227 // (X << C1) >>u C --> (X >>u (C - C1)) & (-1 >> C)
1228 Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1230 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1231 }
1232 } else if (C1->ugt(ShAmtC)) {
1233 unsigned ShlAmtC = C1->getZExtValue();
1234 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmtC - ShAmtC);
1235 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) {
1236 // (X <<nuw C1) >>u C --> X <<nuw (C1 - C)
1237 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1238 NewShl->setHasNoUnsignedWrap(true);
1239 return NewShl;
1240 }
1241 if (Op0->hasOneUse()) {
1242 // (X << C1) >>u C --> X << (C1 - C) & (-1 >> C)
1243 Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1245 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1246 }
1247 } else {
1248 assert(*C1 == ShAmtC);
1249 // (X << C) >>u C --> X & (-1 >>u C)
1251 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1252 }
1253 }
1254
1255 // ((X << C) + Y) >>u C --> (X + (Y >>u C)) & (-1 >>u C)
1256 // TODO: Consolidate with the more general transform that starts from shl
1257 // (the shifts are in the opposite order).
1258 Value *Y;
1259 if (match(Op0,
1261 m_Value(Y))))) {
1262 Value *NewLshr = Builder.CreateLShr(Y, Op1);
1263 Value *NewAdd = Builder.CreateAdd(NewLshr, X);
1264 unsigned Op1Val = C->getLimitedValue(BitWidth);
1265 APInt Bits = APInt::getLowBitsSet(BitWidth, BitWidth - Op1Val);
1266 Constant *Mask = ConstantInt::get(Ty, Bits);
1267 return BinaryOperator::CreateAnd(NewAdd, Mask);
1268 }
1269
1270 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1271 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1272 assert(ShAmtC < X->getType()->getScalarSizeInBits() &&
1273 "Big shift not simplified to zero?");
1274 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1275 Value *NewLShr = Builder.CreateLShr(X, ShAmtC);
1276 return new ZExtInst(NewLShr, Ty);
1277 }
1278
1279 if (match(Op0, m_SExt(m_Value(X)))) {
1280 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1281 // lshr (sext i1 X to iN), C --> select (X, -1 >> C, 0)
1282 if (SrcTyBitWidth == 1) {
1283 auto *NewC = ConstantInt::get(
1284 Ty, APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1286 }
1287
1288 if ((!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType())) &&
1289 Op0->hasOneUse()) {
1290 // Are we moving the sign bit to the low bit and widening with high
1291 // zeros? lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1292 if (ShAmtC == BitWidth - 1) {
1293 Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1294 return new ZExtInst(NewLShr, Ty);
1295 }
1296
1297 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1298 if (ShAmtC == BitWidth - SrcTyBitWidth) {
1299 // The new shift amount can't be more than the narrow source type.
1300 unsigned NewShAmt = std::min(ShAmtC, SrcTyBitWidth - 1);
1301 Value *AShr = Builder.CreateAShr(X, NewShAmt);
1302 return new ZExtInst(AShr, Ty);
1303 }
1304 }
1305 }
1306
1307 if (ShAmtC == BitWidth - 1) {
1308 // lshr i32 or(X,-X), 31 --> zext (X != 0)
1309 if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1310 return new ZExtInst(Builder.CreateIsNotNull(X), Ty);
1311
1312 // lshr i32 (X -nsw Y), 31 --> zext (X < Y)
1313 if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1314 return new ZExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1315
1316 // Check if a number is negative and odd:
1317 // lshr i32 (srem X, 2), 31 --> and (X >> 31), X
1318 if (match(Op0, m_OneUse(m_SRem(m_Value(X), m_SpecificInt(2))))) {
1319 Value *Signbit = Builder.CreateLShr(X, ShAmtC);
1320 return BinaryOperator::CreateAnd(Signbit, X);
1321 }
1322 }
1323
1324 // (X >>u C1) >>u C --> X >>u (C1 + C)
1325 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1)))) {
1326 // Oversized shifts are simplified to zero in InstSimplify.
1327 unsigned AmtSum = ShAmtC + C1->getZExtValue();
1328 if (AmtSum < BitWidth)
1329 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
1330 }
1331
1332 Instruction *TruncSrc;
1333 if (match(Op0, m_OneUse(m_Trunc(m_Instruction(TruncSrc)))) &&
1334 match(TruncSrc, m_LShr(m_Value(X), m_APInt(C1)))) {
1335 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1336 unsigned AmtSum = ShAmtC + C1->getZExtValue();
1337
1338 // If the combined shift fits in the source width:
1339 // (trunc (X >>u C1)) >>u C --> and (trunc (X >>u (C1 + C)), MaskC
1340 //
1341 // If the first shift covers the number of bits truncated, then the
1342 // mask instruction is eliminated (and so the use check is relaxed).
1343 if (AmtSum < SrcWidth &&
1344 (TruncSrc->hasOneUse() || C1->uge(SrcWidth - BitWidth))) {
1345 Value *SumShift = Builder.CreateLShr(X, AmtSum, "sum.shift");
1346 Value *Trunc = Builder.CreateTrunc(SumShift, Ty, I.getName());
1347
1348 // If the first shift does not cover the number of bits truncated, then
1349 // we require a mask to get rid of high bits in the result.
1350 APInt MaskC = APInt::getAllOnes(BitWidth).lshr(ShAmtC);
1351 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, MaskC));
1352 }
1353 }
1354
1355 const APInt *MulC;
1356 if (match(Op0, m_NUWMul(m_Value(X), m_APInt(MulC)))) {
1357 // Look for a "splat" mul pattern - it replicates bits across each half of
1358 // a value, so a right shift is just a mask of the low bits:
1359 // lshr i[2N] (mul nuw X, (2^N)+1), N --> and iN X, (2^N)-1
1360 // TODO: Generalize to allow more than just half-width shifts?
1361 if (BitWidth > 2 && ShAmtC * 2 == BitWidth && (*MulC - 1).isPowerOf2() &&
1362 MulC->logBase2() == ShAmtC)
1363 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, *MulC - 2));
1364
1365 // The one-use check is not strictly necessary, but codegen may not be
1366 // able to invert the transform and perf may suffer with an extra mul
1367 // instruction.
1368 if (Op0->hasOneUse()) {
1369 APInt NewMulC = MulC->lshr(ShAmtC);
1370 // if c is divisible by (1 << ShAmtC):
1371 // lshr (mul nuw x, MulC), ShAmtC -> mul nuw x, (MulC >> ShAmtC)
1372 if (MulC->eq(NewMulC.shl(ShAmtC))) {
1373 auto *NewMul =
1374 BinaryOperator::CreateNUWMul(X, ConstantInt::get(Ty, NewMulC));
1375 BinaryOperator *OrigMul = cast<BinaryOperator>(Op0);
1376 NewMul->setHasNoSignedWrap(OrigMul->hasNoSignedWrap());
1377 return NewMul;
1378 }
1379 }
1380 }
1381
1382 // Try to narrow bswap.
1383 // In the case where the shift amount equals the bitwidth difference, the
1384 // shift is eliminated.
1385 if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::bswap>(
1386 m_OneUse(m_ZExt(m_Value(X))))))) {
1387 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1388 unsigned WidthDiff = BitWidth - SrcWidth;
1389 if (SrcWidth % 16 == 0) {
1390 Value *NarrowSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1391 if (ShAmtC >= WidthDiff) {
1392 // (bswap (zext X)) >> C --> zext (bswap X >> C')
1393 Value *NewShift = Builder.CreateLShr(NarrowSwap, ShAmtC - WidthDiff);
1394 return new ZExtInst(NewShift, Ty);
1395 } else {
1396 // (bswap (zext X)) >> C --> (zext (bswap X)) << C'
1397 Value *NewZExt = Builder.CreateZExt(NarrowSwap, Ty);
1398 Constant *ShiftDiff = ConstantInt::get(Ty, WidthDiff - ShAmtC);
1399 return BinaryOperator::CreateShl(NewZExt, ShiftDiff);
1400 }
1401 }
1402 }
1403
1404 // Reduce add-carry of bools to logic:
1405 // ((zext BoolX) + (zext BoolY)) >> 1 --> zext (BoolX && BoolY)
1406 Value *BoolX, *BoolY;
1407 if (ShAmtC == 1 && match(Op0, m_Add(m_Value(X), m_Value(Y))) &&
1408 match(X, m_ZExt(m_Value(BoolX))) && match(Y, m_ZExt(m_Value(BoolY))) &&
1409 BoolX->getType()->isIntOrIntVectorTy(1) &&
1410 BoolY->getType()->isIntOrIntVectorTy(1) &&
1411 (X->hasOneUse() || Y->hasOneUse() || Op0->hasOneUse())) {
1412 Value *And = Builder.CreateAnd(BoolX, BoolY);
1413 return new ZExtInst(And, Ty);
1414 }
1415
1416 // If the shifted-out value is known-zero, then this is an exact shift.
1417 if (!I.isExact() &&
1418 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmtC), 0, &I)) {
1419 I.setIsExact();
1420 return &I;
1421 }
1422 }
1423
1424 // Transform (x << y) >> y to x & (-1 >> y)
1425 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1427 Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1428 return BinaryOperator::CreateAnd(Mask, X);
1429 }
1430
1431 if (Instruction *Overflow = foldLShrOverflowBit(I))
1432 return Overflow;
1433
1434 return nullptr;
1435}
1436
1439 BinaryOperator &OldAShr) {
1440 assert(OldAShr.getOpcode() == Instruction::AShr &&
1441 "Must be called with arithmetic right-shift instruction only.");
1442
1443 // Check that constant C is a splat of the element-wise bitwidth of V.
1444 auto BitWidthSplat = [](Constant *C, Value *V) {
1445 return match(
1447 APInt(C->getType()->getScalarSizeInBits(),
1448 V->getType()->getScalarSizeInBits())));
1449 };
1450
1451 // It should look like variable-length sign-extension on the outside:
1452 // (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1453 Value *NBits;
1454 Instruction *MaybeTrunc;
1455 Constant *C1, *C2;
1456 if (!match(&OldAShr,
1457 m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1459 m_ZExtOrSelf(m_Value(NBits))))),
1461 m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1462 !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1463 return nullptr;
1464
1465 // There may or may not be a truncation after outer two shifts.
1466 Instruction *HighBitExtract;
1467 match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1468 bool HadTrunc = MaybeTrunc != HighBitExtract;
1469
1470 // And finally, the innermost part of the pattern must be a right-shift.
1471 Value *X, *NumLowBitsToSkip;
1472 if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1473 return nullptr;
1474
1475 // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1476 Constant *C0;
1477 if (!match(NumLowBitsToSkip,
1479 m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1480 !BitWidthSplat(C0, HighBitExtract))
1481 return nullptr;
1482
1483 // Since the NBits is identical for all shifts, if the outermost and
1484 // innermost shifts are identical, then outermost shifts are redundant.
1485 // If we had truncation, do keep it though.
1486 if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1487 return replaceInstUsesWith(OldAShr, MaybeTrunc);
1488
1489 // Else, if there was a truncation, then we need to ensure that one
1490 // instruction will go away.
1491 if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1492 return nullptr;
1493
1494 // Finally, bypass two innermost shifts, and perform the outermost shift on
1495 // the operands of the innermost shift.
1496 Instruction *NewAShr =
1497 BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1498 NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1499 if (!HadTrunc)
1500 return NewAShr;
1501
1502 Builder.Insert(NewAShr);
1503 return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1504}
1505
1507 if (Value *V = simplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1509 return replaceInstUsesWith(I, V);
1510
1512 return X;
1513
1515 return R;
1516
1517 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1518 Type *Ty = I.getType();
1519 unsigned BitWidth = Ty->getScalarSizeInBits();
1520 const APInt *ShAmtAPInt;
1521 if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1522 unsigned ShAmt = ShAmtAPInt->getZExtValue();
1523
1524 // If the shift amount equals the difference in width of the destination
1525 // and source scalar types:
1526 // ashr (shl (zext X), C), C --> sext X
1527 Value *X;
1528 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1529 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1530 return new SExtInst(X, Ty);
1531
1532 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1533 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1534 const APInt *ShOp1;
1535 if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1536 ShOp1->ult(BitWidth)) {
1537 unsigned ShlAmt = ShOp1->getZExtValue();
1538 if (ShlAmt < ShAmt) {
1539 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1540 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1541 auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1542 NewAShr->setIsExact(I.isExact());
1543 return NewAShr;
1544 }
1545 if (ShlAmt > ShAmt) {
1546 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1547 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1548 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1549 NewShl->setHasNoSignedWrap(true);
1550 return NewShl;
1551 }
1552 }
1553
1554 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1555 ShOp1->ult(BitWidth)) {
1556 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1557 // Oversized arithmetic shifts replicate the sign bit.
1558 AmtSum = std::min(AmtSum, BitWidth - 1);
1559 // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1560 return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1561 }
1562
1563 if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1564 (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1565 // ashr (sext X), C --> sext (ashr X, C')
1566 Type *SrcTy = X->getType();
1567 ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1568 Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1569 return new SExtInst(NewSh, Ty);
1570 }
1571
1572 if (ShAmt == BitWidth - 1) {
1573 // ashr i32 or(X,-X), 31 --> sext (X != 0)
1574 if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1575 return new SExtInst(Builder.CreateIsNotNull(X), Ty);
1576
1577 // ashr i32 (X -nsw Y), 31 --> sext (X < Y)
1578 Value *Y;
1579 if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1580 return new SExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1581 }
1582
1583 // If the shifted-out value is known-zero, then this is an exact shift.
1584 if (!I.isExact() &&
1585 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) {
1586 I.setIsExact();
1587 return &I;
1588 }
1589 }
1590
1591 // Prefer `-(x & 1)` over `(x << (bitwidth(x)-1)) a>> (bitwidth(x)-1)`
1592 // as the pattern to splat the lowest bit.
1593 // FIXME: iff X is already masked, we don't need the one-use check.
1594 Value *X;
1595 if (match(Op1, m_SpecificIntAllowUndef(BitWidth - 1)) &&
1598 Constant *Mask = ConstantInt::get(Ty, 1);
1599 // Retain the knowledge about the ignored lanes.
1601 Constant::mergeUndefsWith(Mask, cast<Constant>(Op1)),
1602 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)));
1603 X = Builder.CreateAnd(X, Mask);
1605 }
1606
1608 return R;
1609
1610 // See if we can turn a signed shr into an unsigned shr.
1612 Instruction *Lshr = BinaryOperator::CreateLShr(Op0, Op1);
1613 Lshr->setIsExact(I.isExact());
1614 return Lshr;
1615 }
1616
1617 // ashr (xor %x, -1), %y --> xor (ashr %x, %y), -1
1618 if (match(Op0, m_OneUse(m_Not(m_Value(X))))) {
1619 // Note that we must drop 'exact'-ness of the shift!
1620 // Note that we can't keep undef's in -1 vector constant!
1621 auto *NewAShr = Builder.CreateAShr(X, Op1, Op0->getName() + ".not");
1622 return BinaryOperator::CreateNot(NewAShr);
1623 }
1624
1625 return nullptr;
1626}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
assume Assume Builder
SmallVector< MachineOperand, 4 > Cond
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This file provides internal interfaces used to implement the InstCombine.
static Value * foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt, bool IsOuterShl, InstCombiner::BuilderTy &Builder)
Fold OuterShift (InnerShift X, C1), C2.
static Instruction * dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift, const SimplifyQuery &Q, InstCombiner::BuilderTy &Builder)
static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift, InstCombinerImpl &IC, Instruction *CxtI)
See if we can compute the specified value, but shifted logically to the left or right by some number ...
bool canTryToConstantAddTwoShiftAmounts(Value *Sh0, Value *ShAmt0, Value *Sh1, Value *ShAmt1)
static Instruction * foldShiftOfShiftedBinOp(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
If we have a shift-by-constant of a bin op (bitwise logic op or add/sub w/ shl) that itself has a shi...
static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl, Instruction *InnerShift, InstCombinerImpl &IC, Instruction *CxtI)
Return true if we can simplify two logical (either left or right) shifts that have constant shift amo...
static Value * getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift, InstCombinerImpl &IC, const DataLayout &DL)
When canEvaluateShifted() returns true for an expression, this function inserts the new computation t...
static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift, BinaryOperator *BO)
This file provides the interface for the instcombine pass implementation.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
@ SI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static unsigned getScalarSizeInBits(Type *Ty)
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
Value * RHS
Class for arbitrary precision integers.
Definition: APInt.h:75
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:214
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition: APInt.h:441
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:209
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:415
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1494
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1160
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:366
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1089
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:312
bool eq(const APInt &RHS) const
Equality comparison.
Definition: APInt.h:1057
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition: APInt.h:1592
unsigned logBase2() const
Definition: APInt.h:1707
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:861
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:289
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:279
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:839
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1199
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition: InstrTypes.h:391
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:718
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:748
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:743
@ ICMP_EQ
equal
Definition: InstrTypes.h:739
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:746
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2621
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2110
static Constant * getNot(Constant *C)
Definition: Constants.cpp:2608
static Constant * getZExtOrBitCast(Constant *C, Type *Ty)
Definition: Constants.cpp:2003
static Constant * getShl(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2647
static Constant * getLShr(Constant *C1, Constant *C2, bool isExact=false)
Definition: Constants.cpp:2654
static Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
Definition: Constants.cpp:2614
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2082
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:114
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
Definition: Constants.cpp:753
bool containsUndefElement() const
Return true if this is a vector constant that includes any strictly undef (not poison) elements.
Definition: Constants.cpp:340
static Constant * mergeUndefsWith(Constant *C, Constant *Other)
Merges undefs of a Constant with another Constant, along with the undefs already present.
Definition: Constants.cpp:777
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:403
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:356
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:956
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2152
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1926
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1645
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1366
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition: IRBuilder.h:2454
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1930
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2136
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:145
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1345
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1404
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1256
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2444
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1595
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2168
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1385
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2246
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitLShr(BinaryOperator &I)
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
Value * reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, const SimplifyQuery &SQ, bool AnalyzeForSignBitExtraction=false)
Instruction * visitAShr(BinaryOperator &I)
Instruction * visitShl(BinaryOperator &I)
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * foldVariableSignZeroExtensionOfVariableHighBitExtract(BinaryOperator &OldAShr)
Instruction * commonShiftTransforms(BinaryOperator &I)
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Instruction * FoldShiftByConstant(Value *Op0, Constant *Op1, BinaryOperator &I)
Instruction * InsertNewInstWith(Instruction *New, Instruction &Old)
Same as InsertNewInstBefore, but also sets the debug loc.
Definition: InstCombiner.h:407
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:418
const SimplifyQuery SQ
Definition: InstCombiner.h:74
const DataLayout & DL
Definition: InstCombiner.h:73
unsigned ComputeNumSignBits(const Value *Op, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:482
AssumptionCache & AC
Definition: InstCombiner.h:70
void addToWorklist(Instruction *I)
Definition: InstCombiner.h:367
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:442
BuilderTy & Builder
Definition: InstCombiner.h:58
bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth=0, const Instruction *CxtI=nullptr) const
Definition: InstCombiner.h:477
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
bool isLogicalShift() const
Return true if this is a logical shift left or a logical shift right.
Definition: Instruction.h:209
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:168
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
op_range incoming_values()
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
This class represents a sign extension of integer types.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:267
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:237
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Type * getExtendedType() const
Given scalar/vector integer type, returns a type with elements twice as wide as in the original type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:231
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:381
This class represents zero extension of integer types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:453
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:854
match_combine_or< CastClass_match< OpTy, Instruction::ZExt >, OpTy > m_ZExtOrSelf(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Definition: PatternMatch.h:979
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:84
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:544
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:144
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:716
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:772
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:517
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:224
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
deferredval_ty< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
Definition: PatternMatch.h:790
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a 'Neg' as 'sub 0, V'.
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
match_combine_or< CastClass_match< OpTy, Instruction::Trunc >, OpTy > m_TruncOrSelf(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
specific_intval< true > m_SpecificIntAllowUndef(APInt V)
Definition: PatternMatch.h:862
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:278
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
Exact_match< T > m_Exact(const T &SubPattern)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:991
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
Definition: PatternMatch.h:218
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
Definition: PatternMatch.h:598
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Value * simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a AShr, fold the result or return nulll.
Value * simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Sub, fold the result or return null.
Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:382
Value * simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Shl, fold the result or return null.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:292
Value * simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a LShr, fold the result or return null.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:184
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
SimplifyQuery getWithInstruction(Instruction *I) const