LLVM 22.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 if (NewShAmt->getType() != X->getType()) {
140 NewShAmt = ConstantFoldCastOperand(Instruction::ZExt, NewShAmt,
141 X->getType(), SQ.DL);
142 if (!NewShAmt)
143 return nullptr;
144 }
145
146 // All good, we can do this fold.
147 BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt);
148
149 // The flags can only be propagated if there wasn't a trunc.
150 if (!Trunc) {
151 // If the pattern did not involve trunc, and both of the original shifts
152 // had the same flag set, preserve the flag.
153 if (ShiftOpcode == Instruction::BinaryOps::Shl) {
154 NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() &&
155 Sh1->hasNoUnsignedWrap());
156 NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() &&
157 Sh1->hasNoSignedWrap());
158 } else {
159 NewShift->setIsExact(Sh0->isExact() && Sh1->isExact());
160 }
161 }
162
163 Instruction *Ret = NewShift;
164 if (Trunc) {
165 Builder.Insert(NewShift);
166 Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType());
167 }
168
169 return Ret;
170}
171
172// If we have some pattern that leaves only some low bits set, and then performs
173// left-shift of those bits, if none of the bits that are left after the final
174// shift are modified by the mask, we can omit the mask.
175//
176// There are many variants to this pattern:
177// a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt
178// b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt
179// c) (x & (-1 l>> MaskShAmt)) << ShiftShAmt
180// d) (x & ((-1 << MaskShAmt) l>> MaskShAmt)) << ShiftShAmt
181// e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt
182// f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt
183// All these patterns can be simplified to just:
184// x << ShiftShAmt
185// iff:
186// a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x)
187// c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt)
188static Instruction *
190 const SimplifyQuery &Q,
191 InstCombiner::BuilderTy &Builder) {
192 assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl &&
193 "The input must be 'shl'!");
194
195 Value *Masked, *ShiftShAmt;
196 match(OuterShift,
197 m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt))));
198
199 // *If* there is a truncation between an outer shift and a possibly-mask,
200 // then said truncation *must* be one-use, else we can't perform the fold.
201 Value *Trunc;
203 !Trunc->hasOneUse())
204 return nullptr;
205
206 Type *NarrowestTy = OuterShift->getType();
207 Type *WidestTy = Masked->getType();
208 bool HadTrunc = WidestTy != NarrowestTy;
209
210 // The mask must be computed in a type twice as wide to ensure
211 // that no bits are lost if the sum-of-shifts is wider than the base type.
212 Type *ExtendedTy = WidestTy->getExtendedType();
213
214 Value *MaskShAmt;
215
216 // ((1 << MaskShAmt) - 1)
217 auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes());
218 // (~(-1 << maskNbits))
219 auto MaskB = m_Not(m_Shl(m_AllOnes(), m_Value(MaskShAmt)));
220 // (-1 l>> MaskShAmt)
221 auto MaskC = m_LShr(m_AllOnes(), m_Value(MaskShAmt));
222 // ((-1 << MaskShAmt) l>> MaskShAmt)
223 auto MaskD =
224 m_LShr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt));
225
226 Value *X;
227 Constant *NewMask;
228
229 if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) {
230 // Peek through an optional zext of the shift amount.
231 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
232
233 // Verify that it would be safe to try to add those two shift amounts.
234 if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
235 MaskShAmt))
236 return nullptr;
237
238 // Can we simplify (MaskShAmt+ShiftShAmt) ?
240 MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
241 if (!SumOfShAmts)
242 return nullptr; // Did not simplify.
243 // In this pattern SumOfShAmts correlates with the number of low bits
244 // that shall remain in the root value (OuterShift).
245
246 // An extend of an undef value becomes zero because the high bits are never
247 // completely unknown. Replace the `undef` shift amounts with final
248 // shift bitwidth to ensure that the value remains undef when creating the
249 // subsequent shift op.
250 SumOfShAmts = Constant::replaceUndefsWith(
251 SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(),
252 ExtendedTy->getScalarSizeInBits()));
253 auto *ExtendedSumOfShAmts = ConstantFoldCastOperand(
254 Instruction::ZExt, SumOfShAmts, ExtendedTy, Q.DL);
255 if (!ExtendedSumOfShAmts)
256 return nullptr;
257
258 // And compute the mask as usual: ~(-1 << (SumOfShAmts))
259 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
260 Constant *ExtendedInvertedMask = ConstantFoldBinaryOpOperands(
261 Instruction::Shl, ExtendedAllOnes, ExtendedSumOfShAmts, Q.DL);
262 if (!ExtendedInvertedMask)
263 return nullptr;
264
265 NewMask = ConstantExpr::getNot(ExtendedInvertedMask);
266 } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) ||
267 match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)),
268 m_Deferred(MaskShAmt)))) {
269 // Peek through an optional zext of the shift amount.
270 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt)));
271
272 // Verify that it would be safe to try to add those two shift amounts.
273 if (!canTryToConstantAddTwoShiftAmounts(OuterShift, ShiftShAmt, Masked,
274 MaskShAmt))
275 return nullptr;
276
277 // Can we simplify (ShiftShAmt-MaskShAmt) ?
279 ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q));
280 if (!ShAmtsDiff)
281 return nullptr; // Did not simplify.
282 // In this pattern ShAmtsDiff correlates with the number of high bits that
283 // shall be unset in the root value (OuterShift).
284
285 // An extend of an undef value becomes zero because the high bits are never
286 // completely unknown. Replace the `undef` shift amounts with negated
287 // bitwidth of innermost shift to ensure that the value remains undef when
288 // creating the subsequent shift op.
289 unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits();
290 ShAmtsDiff = Constant::replaceUndefsWith(
291 ShAmtsDiff,
292 ConstantInt::getSigned(ShAmtsDiff->getType()->getScalarType(),
293 -(int)WidestTyBitWidth));
294 auto *ExtendedNumHighBitsToClear = ConstantFoldCastOperand(
295 Instruction::ZExt,
296 ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(),
297 WidestTyBitWidth,
298 /*isSigned=*/false),
299 ShAmtsDiff),
300 ExtendedTy, Q.DL);
301 if (!ExtendedNumHighBitsToClear)
302 return nullptr;
303
304 // And compute the mask as usual: (-1 l>> (NumHighBitsToClear))
305 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy);
306 NewMask = ConstantFoldBinaryOpOperands(Instruction::LShr, ExtendedAllOnes,
307 ExtendedNumHighBitsToClear, Q.DL);
308 if (!NewMask)
309 return nullptr;
310 } else
311 return nullptr; // Don't know anything about this pattern.
312
313 NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy);
314
315 // Does this mask has any unset bits? If not then we can just not apply it.
316 bool NeedMask = !match(NewMask, m_AllOnes());
317
318 // If we need to apply a mask, there are several more restrictions we have.
319 if (NeedMask) {
320 // The old masking instruction must go away.
321 if (!Masked->hasOneUse())
322 return nullptr;
323 // The original "masking" instruction must not have been`ashr`.
324 if (match(Masked, m_AShr(m_Value(), m_Value())))
325 return nullptr;
326 }
327
328 // If we need to apply truncation, let's do it first, since we can.
329 // We have already ensured that the old truncation will go away.
330 if (HadTrunc)
331 X = Builder.CreateTrunc(X, NarrowestTy);
332
333 // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits.
334 // We didn't change the Type of this outermost shift, so we can just do it.
335 auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X,
336 OuterShift->getOperand(1));
337 if (!NeedMask)
338 return NewShift;
339
340 Builder.Insert(NewShift);
341 return BinaryOperator::Create(Instruction::And, NewShift, NewMask);
342}
343
344/// If we have a shift-by-constant of a bin op (bitwise logic op or add/sub w/
345/// shl) that itself has a shift-by-constant operand with identical opcode, we
346/// may be able to convert that into 2 independent shifts followed by the logic
347/// op. This eliminates a use of an intermediate value (reduces dependency
348/// chain).
350 InstCombiner::BuilderTy &Builder) {
351 assert(I.isShift() && "Expected a shift as input");
352 auto *BinInst = dyn_cast<BinaryOperator>(I.getOperand(0));
353 if (!BinInst ||
354 (!BinInst->isBitwiseLogicOp() &&
355 BinInst->getOpcode() != Instruction::Add &&
356 BinInst->getOpcode() != Instruction::Sub) ||
357 !BinInst->hasOneUse())
358 return nullptr;
359
360 Constant *C0, *C1;
361 if (!match(I.getOperand(1), m_Constant(C1)))
362 return nullptr;
363
364 Instruction::BinaryOps ShiftOpcode = I.getOpcode();
365 // Transform for add/sub only works with shl.
366 if ((BinInst->getOpcode() == Instruction::Add ||
367 BinInst->getOpcode() == Instruction::Sub) &&
368 ShiftOpcode != Instruction::Shl)
369 return nullptr;
370
371 Type *Ty = I.getType();
372
373 // Find a matching shift by constant. The fold is not valid if the sum
374 // of the shift values equals or exceeds bitwidth.
375 Value *X, *Y;
376 auto matchFirstShift = [&](Value *V, Value *W) {
377 unsigned Size = Ty->getScalarSizeInBits();
378 APInt Threshold(Size, Size);
379 return match(V, m_BinOp(ShiftOpcode, m_Value(X), m_Constant(C0))) &&
380 (V->hasOneUse() || match(W, m_ImmConstant())) &&
383 };
384
385 // Logic ops and Add are commutative, so check each operand for a match. Sub
386 // is not so we cannot reoder if we match operand(1) and need to keep the
387 // operands in their original positions.
388 bool FirstShiftIsOp1 = false;
389 if (matchFirstShift(BinInst->getOperand(0), BinInst->getOperand(1)))
390 Y = BinInst->getOperand(1);
391 else if (matchFirstShift(BinInst->getOperand(1), BinInst->getOperand(0))) {
392 Y = BinInst->getOperand(0);
393 FirstShiftIsOp1 = BinInst->getOpcode() == Instruction::Sub;
394 } else
395 return nullptr;
396
397 // shift (binop (shift X, C0), Y), C1 -> binop (shift X, C0+C1), (shift Y, C1)
398 Constant *ShiftSumC = ConstantExpr::getAdd(C0, C1);
399 Value *NewShift1 = Builder.CreateBinOp(ShiftOpcode, X, ShiftSumC);
400 Value *NewShift2 = Builder.CreateBinOp(ShiftOpcode, Y, C1);
401 Value *Op1 = FirstShiftIsOp1 ? NewShift2 : NewShift1;
402 Value *Op2 = FirstShiftIsOp1 ? NewShift1 : NewShift2;
403 return BinaryOperator::Create(BinInst->getOpcode(), Op1, Op2);
404}
405
408 return Phi;
409
410 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
411 assert(Op0->getType() == Op1->getType());
412 Type *Ty = I.getType();
413
414 // If the shift amount is a one-use `sext`, we can demote it to `zext`.
415 Value *Y;
416 if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) {
417 Value *NewExt = Builder.CreateZExt(Y, Ty, Op1->getName());
418 return BinaryOperator::Create(I.getOpcode(), Op0, NewExt);
419 }
420
421 // See if we can fold away this shift.
423 return &I;
424
425 // Try to fold constant and into select arguments.
426 if (isa<Constant>(Op0))
428 if (Instruction *R = FoldOpIntoSelect(I, SI))
429 return R;
430
431 Constant *CUI;
432 if (match(Op1, m_ImmConstant(CUI)))
433 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
434 return Res;
435
436 if (auto *NewShift = cast_or_null<Instruction>(
438 return NewShift;
439
440 // Pre-shift a constant shifted by a variable amount with constant offset:
441 // C shift (A add nuw C1) --> (C shift C1) shift A
442 Value *A;
443 Constant *C, *C1;
444 if (match(Op0, m_Constant(C)) &&
445 match(Op1, m_NUWAddLike(m_Value(A), m_Constant(C1)))) {
446 Value *NewC = Builder.CreateBinOp(I.getOpcode(), C, C1);
447 BinaryOperator *NewShiftOp = BinaryOperator::Create(I.getOpcode(), NewC, A);
448 if (I.getOpcode() == Instruction::Shl) {
449 NewShiftOp->setHasNoSignedWrap(I.hasNoSignedWrap());
450 NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
451 } else {
452 NewShiftOp->setIsExact(I.isExact());
453 }
454 return NewShiftOp;
455 }
456
457 unsigned BitWidth = Ty->getScalarSizeInBits();
458
459 const APInt *AC, *AddC;
460 // Try to pre-shift a constant shifted by a variable amount added with a
461 // negative number:
462 // C << (X - AddC) --> (C >> AddC) << X
463 // and
464 // C >> (X - AddC) --> (C << AddC) >> X
465 if (match(Op0, m_APInt(AC)) && match(Op1, m_Add(m_Value(A), m_APInt(AddC))) &&
466 AddC->isNegative() && (-*AddC).ult(BitWidth)) {
467 assert(!AC->isZero() && "Expected simplify of shifted zero");
468 unsigned PosOffset = (-*AddC).getZExtValue();
469
470 auto isSuitableForPreShift = [PosOffset, &I, AC]() {
471 switch (I.getOpcode()) {
472 default:
473 return false;
474 case Instruction::Shl:
475 return (I.hasNoSignedWrap() || I.hasNoUnsignedWrap()) &&
476 AC->eq(AC->lshr(PosOffset).shl(PosOffset));
477 case Instruction::LShr:
478 return I.isExact() && AC->eq(AC->shl(PosOffset).lshr(PosOffset));
479 case Instruction::AShr:
480 return I.isExact() && AC->eq(AC->shl(PosOffset).ashr(PosOffset));
481 }
482 };
483 if (isSuitableForPreShift()) {
484 Constant *NewC = ConstantInt::get(Ty, I.getOpcode() == Instruction::Shl
485 ? AC->lshr(PosOffset)
486 : AC->shl(PosOffset));
487 BinaryOperator *NewShiftOp =
488 BinaryOperator::Create(I.getOpcode(), NewC, A);
489 if (I.getOpcode() == Instruction::Shl) {
490 NewShiftOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
491 } else {
492 NewShiftOp->setIsExact();
493 }
494 return NewShiftOp;
495 }
496 }
497
498 // X shift (A srem C) -> X shift (A and (C - 1)) iff C is a power of 2.
499 // Because shifts by negative values (which could occur if A were negative)
500 // are undefined.
501 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Constant(C))) &&
502 match(C, m_Power2())) {
503 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't
504 // demand the sign bit (and many others) here??
505 Constant *Mask = ConstantExpr::getSub(C, ConstantInt::get(Ty, 1));
506 Value *Rem = Builder.CreateAnd(A, Mask, Op1->getName());
507 return replaceOperand(I, 1, Rem);
508 }
509
511 return Logic;
512
513 if (match(Op1, m_Or(m_Value(), m_SpecificInt(BitWidth - 1))))
514 return replaceOperand(I, 1, ConstantInt::get(Ty, BitWidth - 1));
515
516 Instruction *CmpIntr;
517 if ((I.getOpcode() == Instruction::LShr ||
518 I.getOpcode() == Instruction::AShr) &&
519 match(Op0, m_OneUse(m_Instruction(CmpIntr))) &&
520 isa<CmpIntrinsic>(CmpIntr) &&
521 match(Op1, m_SpecificInt(Ty->getScalarSizeInBits() - 1))) {
522 Value *Cmp =
523 Builder.CreateICmp(cast<CmpIntrinsic>(CmpIntr)->getLTPredicate(),
524 CmpIntr->getOperand(0), CmpIntr->getOperand(1));
525 return CastInst::Create(I.getOpcode() == Instruction::LShr
526 ? Instruction::ZExt
527 : Instruction::SExt,
528 Cmp, Ty);
529 }
530
531 return nullptr;
532}
533
534/// Return true if we can simplify two logical (either left or right) shifts
535/// that have constant shift amounts: OuterShift (InnerShift X, C1), C2.
536static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl,
537 Instruction *InnerShift,
538 InstCombinerImpl &IC, Instruction *CxtI) {
539 assert(InnerShift->isLogicalShift() && "Unexpected instruction type");
540
541 // We need constant scalar or constant splat shifts.
542 const APInt *InnerShiftConst;
543 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst)))
544 return false;
545
546 // Two logical shifts in the same direction:
547 // shl (shl X, C1), C2 --> shl X, C1 + C2
548 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
549 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
550 if (IsInnerShl == IsOuterShl)
551 return true;
552
553 // Equal shift amounts in opposite directions become bitwise 'and':
554 // lshr (shl X, C), C --> and X, C'
555 // shl (lshr X, C), C --> and X, C'
556 if (*InnerShiftConst == OuterShAmt)
557 return true;
558
559 // If the 2nd shift is bigger than the 1st, we can fold:
560 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3
561 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3
562 // but it isn't profitable unless we know the and'd out bits are already zero.
563 // Also, check that the inner shift is valid (less than the type width) or
564 // we'll crash trying to produce the bit mask for the 'and'.
565 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits();
566 if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) {
567 unsigned InnerShAmt = InnerShiftConst->getZExtValue();
568 unsigned MaskShift =
569 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt;
570 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift;
571 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, CxtI))
572 return true;
573 }
574
575 return false;
576}
577
578/// See if we can compute the specified value, but shifted logically to the left
579/// or right by some number of bits. This should return true if the expression
580/// can be computed for the same cost as the current expression tree. This is
581/// used to eliminate extraneous shifting from things like:
582/// %C = shl i128 %A, 64
583/// %D = shl i128 %B, 96
584/// %E = or i128 %C, %D
585/// %F = lshr i128 %E, 64
586/// where the client will ask if E can be computed shifted right by 64-bits. If
587/// this succeeds, getShiftedValue() will be called to produce the value.
588static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift,
589 InstCombinerImpl &IC, Instruction *CxtI) {
590 // We can always evaluate immediate constants.
591 if (match(V, m_ImmConstant()))
592 return true;
593
595 if (!I) return false;
596
597 // We can't mutate something that has multiple uses: doing so would
598 // require duplicating the instruction in general, which isn't profitable.
599 if (!I->hasOneUse()) return false;
600
601 switch (I->getOpcode()) {
602 default: return false;
603 case Instruction::And:
604 case Instruction::Or:
605 case Instruction::Xor:
606 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
607 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) &&
608 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I);
609
610 case Instruction::Shl:
611 case Instruction::LShr:
612 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI);
613
614 case Instruction::Select: {
616 Value *TrueVal = SI->getTrueValue();
617 Value *FalseVal = SI->getFalseValue();
618 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) &&
619 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI);
620 }
621 case Instruction::PHI: {
622 // We can change a phi if we can change all operands. Note that we never
623 // get into trouble with cyclic PHIs here because we only consider
624 // instructions with a single use.
625 PHINode *PN = cast<PHINode>(I);
626 for (Value *IncValue : PN->incoming_values())
627 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN))
628 return false;
629 return true;
630 }
631 case Instruction::Mul: {
632 const APInt *MulConst;
633 // We can fold (shr (mul X, -(1 << C)), C) -> (and (neg X), C`)
634 return !IsLeftShift && match(I->getOperand(1), m_APInt(MulConst)) &&
635 MulConst->isNegatedPowerOf2() && MulConst->countr_zero() == NumBits;
636 }
637 }
638}
639
640/// Fold OuterShift (InnerShift X, C1), C2.
641/// See canEvaluateShiftedShift() for the constraints on these instructions.
642static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt,
643 bool IsOuterShl,
644 InstCombiner::BuilderTy &Builder) {
645 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl;
646 Type *ShType = InnerShift->getType();
647 unsigned TypeWidth = ShType->getScalarSizeInBits();
648
649 // We only accept shifts-by-a-constant in canEvaluateShifted().
650 const APInt *C1;
651 match(InnerShift->getOperand(1), m_APInt(C1));
652 unsigned InnerShAmt = C1->getZExtValue();
653
654 // Change the shift amount and clear the appropriate IR flags.
655 auto NewInnerShift = [&](unsigned ShAmt) {
656 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt));
657 if (IsInnerShl) {
658 InnerShift->setHasNoUnsignedWrap(false);
659 InnerShift->setHasNoSignedWrap(false);
660 } else {
661 InnerShift->setIsExact(false);
662 }
663 return InnerShift;
664 };
665
666 // Two logical shifts in the same direction:
667 // shl (shl X, C1), C2 --> shl X, C1 + C2
668 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2
669 if (IsInnerShl == IsOuterShl) {
670 // If this is an oversized composite shift, then unsigned shifts get 0.
671 if (InnerShAmt + OuterShAmt >= TypeWidth)
672 return Constant::getNullValue(ShType);
673
674 return NewInnerShift(InnerShAmt + OuterShAmt);
675 }
676
677 // Equal shift amounts in opposite directions become bitwise 'and':
678 // lshr (shl X, C), C --> and X, C'
679 // shl (lshr X, C), C --> and X, C'
680 if (InnerShAmt == OuterShAmt) {
681 APInt Mask = IsInnerShl
682 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt)
683 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt);
684 Value *And = Builder.CreateAnd(InnerShift->getOperand(0),
685 ConstantInt::get(ShType, Mask));
686 if (auto *AndI = dyn_cast<Instruction>(And)) {
687 AndI->moveBefore(InnerShift->getIterator());
688 AndI->takeName(InnerShift);
689 }
690 return And;
691 }
692
693 assert(InnerShAmt > OuterShAmt &&
694 "Unexpected opposite direction logical shift pair");
695
696 // In general, we would need an 'and' for this transform, but
697 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used.
698 // lshr (shl X, C1), C2 --> shl X, C1 - C2
699 // shl (lshr X, C1), C2 --> lshr X, C1 - C2
700 return NewInnerShift(InnerShAmt - OuterShAmt);
701}
702
703/// When canEvaluateShifted() returns true for an expression, this function
704/// inserts the new computation that produces the shifted value.
705static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift,
706 InstCombinerImpl &IC, const DataLayout &DL) {
707 // We can always evaluate constants shifted.
708 if (Constant *C = dyn_cast<Constant>(V)) {
709 if (isLeftShift)
710 return IC.Builder.CreateShl(C, NumBits);
711 else
712 return IC.Builder.CreateLShr(C, NumBits);
713 }
714
716 IC.addToWorklist(I);
717
718 switch (I->getOpcode()) {
719 default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
720 case Instruction::And:
721 case Instruction::Or:
722 case Instruction::Xor:
723 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted.
724 I->setOperand(
725 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL));
726 I->setOperand(
727 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
728 return I;
729
730 case Instruction::Shl:
731 case Instruction::LShr:
732 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift,
733 IC.Builder);
734
735 case Instruction::Select:
736 I->setOperand(
737 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL));
738 I->setOperand(
739 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL));
740 return I;
741 case Instruction::PHI: {
742 // We can change a phi if we can change all operands. Note that we never
743 // get into trouble with cyclic PHIs here because we only consider
744 // instructions with a single use.
745 PHINode *PN = cast<PHINode>(I);
746 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
748 isLeftShift, IC, DL));
749 return PN;
750 }
751 case Instruction::Mul: {
752 assert(!isLeftShift && "Unexpected shift direction!");
753 auto *Neg = BinaryOperator::CreateNeg(I->getOperand(0));
754 IC.InsertNewInstWith(Neg, I->getIterator());
755 unsigned TypeWidth = I->getType()->getScalarSizeInBits();
756 APInt Mask = APInt::getLowBitsSet(TypeWidth, TypeWidth - NumBits);
757 auto *And = BinaryOperator::CreateAnd(Neg,
758 ConstantInt::get(I->getType(), Mask));
759 And->takeName(I);
760 return IC.InsertNewInstWith(And, I->getIterator());
761 }
762 }
763}
764
765// If this is a bitwise operator or add with a constant RHS we might be able
766// to pull it through a shift.
768 BinaryOperator *BO) {
769 switch (BO->getOpcode()) {
770 default:
771 return false; // Do not perform transform!
772 case Instruction::Add:
773 return Shift.getOpcode() == Instruction::Shl;
774 case Instruction::Or:
775 case Instruction::And:
776 return true;
777 case Instruction::Xor:
778 // Do not change a 'not' of logical shift because that would create a normal
779 // 'xor'. The 'not' is likely better for analysis, SCEV, and codegen.
780 return !(Shift.isLogicalShift() && match(BO, m_Not(m_Value())));
781 }
782}
783
785 BinaryOperator &I) {
786 // (C2 << X) << C1 --> (C2 << C1) << X
787 // (C2 >> X) >> C1 --> (C2 >> C1) >> X
788 Constant *C2;
789 Value *X;
790 bool IsLeftShift = I.getOpcode() == Instruction::Shl;
791 if (match(Op0, m_BinOp(I.getOpcode(), m_ImmConstant(C2), m_Value(X)))) {
793 I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), C2, C1), X);
795 if (IsLeftShift) {
796 R->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() &&
797 BO0->hasNoUnsignedWrap());
798 R->setHasNoSignedWrap(I.hasNoSignedWrap() && BO0->hasNoSignedWrap());
799 } else
800 R->setIsExact(I.isExact() && BO0->isExact());
801 return R;
802 }
803
804 Type *Ty = I.getType();
805 unsigned TypeBits = Ty->getScalarSizeInBits();
806
807 // (X / +DivC) >> (Width - 1) --> ext (X <= -DivC)
808 // (X / -DivC) >> (Width - 1) --> ext (X >= +DivC)
809 const APInt *DivC;
810 if (!IsLeftShift && match(C1, m_SpecificIntAllowPoison(TypeBits - 1)) &&
811 match(Op0, m_SDiv(m_Value(X), m_APInt(DivC))) && !DivC->isZero() &&
812 !DivC->isMinSignedValue()) {
813 Constant *NegDivC = ConstantInt::get(Ty, -(*DivC));
816 Value *Cmp = Builder.CreateICmp(Pred, X, NegDivC);
817 auto ExtOpcode = (I.getOpcode() == Instruction::AShr) ? Instruction::SExt
818 : Instruction::ZExt;
819 return CastInst::Create(ExtOpcode, Cmp, Ty);
820 }
821
822 const APInt *Op1C;
823 if (!match(C1, m_APInt(Op1C)))
824 return nullptr;
825
826 assert(!Op1C->uge(TypeBits) &&
827 "Shift over the type width should have been removed already");
828
829 // See if we can propagate this shift into the input, this covers the trivial
830 // cast of lshr(shl(x,c1),c2) as well as other more complex cases.
831 if (I.getOpcode() != Instruction::AShr &&
832 canEvaluateShifted(Op0, Op1C->getZExtValue(), IsLeftShift, *this, &I)) {
834 dbgs() << "ICE: GetShiftedValue propagating shift through expression"
835 " to eliminate shift:\n IN: "
836 << *Op0 << "\n SH: " << I << "\n");
837
838 return replaceInstUsesWith(
839 I, getShiftedValue(Op0, Op1C->getZExtValue(), IsLeftShift, *this, DL));
840 }
841
842 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I))
843 return FoldedShift;
844
845 if (!Op0->hasOneUse())
846 return nullptr;
847
848 if (auto *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
849 // If the operand is a bitwise operator with a constant RHS, and the
850 // shift is the only use, we can pull it out of the shift.
851 const APInt *Op0C;
852 if (match(Op0BO->getOperand(1), m_APInt(Op0C))) {
853 if (canShiftBinOpWithConstantRHS(I, Op0BO)) {
854 Value *NewRHS =
855 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(1), C1);
856
857 Value *NewShift =
858 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), C1);
859 NewShift->takeName(Op0BO);
860
861 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, NewRHS);
862 }
863 }
864 }
865
866 // If we have a select that conditionally executes some binary operator,
867 // see if we can pull it the select and operator through the shift.
868 //
869 // For example, turning:
870 // shl (select C, (add X, C1), X), C2
871 // Into:
872 // Y = shl X, C2
873 // select C, (add Y, C1 << C2), Y
874 Value *Cond;
875 BinaryOperator *TBO;
876 Value *FalseVal;
877 if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)),
878 m_Value(FalseVal)))) {
879 const APInt *C;
880 if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal &&
881 match(TBO->getOperand(1), m_APInt(C)) &&
883 Value *NewRHS =
884 Builder.CreateBinOp(I.getOpcode(), TBO->getOperand(1), C1);
885
886 Value *NewShift = Builder.CreateBinOp(I.getOpcode(), FalseVal, C1);
887 Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, NewRHS);
888 return SelectInst::Create(Cond, NewOp, NewShift);
889 }
890 }
891
892 BinaryOperator *FBO;
893 Value *TrueVal;
894 if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal),
895 m_OneUse(m_BinOp(FBO))))) {
896 const APInt *C;
897 if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal &&
898 match(FBO->getOperand(1), m_APInt(C)) &&
900 Value *NewRHS =
901 Builder.CreateBinOp(I.getOpcode(), FBO->getOperand(1), C1);
902
903 Value *NewShift = Builder.CreateBinOp(I.getOpcode(), TrueVal, C1);
904 Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, NewRHS);
905 return SelectInst::Create(Cond, NewShift, NewOp);
906 }
907 }
908
909 return nullptr;
910}
911
912// Tries to perform
913// (lshr (add (zext X), (zext Y)), K)
914// -> (icmp ult (add X, Y), X)
915// where
916// - The add's operands are zexts from a K-bits integer to a bigger type.
917// - The add is only used by the shr, or by iK (or narrower) truncates.
918// - The lshr type has more than 2 bits (other types are boolean math).
919// - K > 1
920// note that
921// - The resulting add cannot have nuw/nsw, else on overflow we get a
922// poison value and the transform isn't legal anymore.
923Instruction *InstCombinerImpl::foldLShrOverflowBit(BinaryOperator &I) {
924 assert(I.getOpcode() == Instruction::LShr);
925
926 Value *Add = I.getOperand(0);
927 Value *ShiftAmt = I.getOperand(1);
928 Type *Ty = I.getType();
929
930 if (Ty->getScalarSizeInBits() < 3)
931 return nullptr;
932
933 const APInt *ShAmtAPInt = nullptr;
934 Value *X = nullptr, *Y = nullptr;
935 if (!match(ShiftAmt, m_APInt(ShAmtAPInt)) ||
936 !match(Add,
938 return nullptr;
939
940 const unsigned ShAmt = ShAmtAPInt->getZExtValue();
941 if (ShAmt == 1)
942 return nullptr;
943
944 // X/Y are zexts from `ShAmt`-sized ints.
945 if (X->getType()->getScalarSizeInBits() != ShAmt ||
946 Y->getType()->getScalarSizeInBits() != ShAmt)
947 return nullptr;
948
949 // Make sure that `Add` is only used by `I` and `ShAmt`-truncates.
950 if (!Add->hasOneUse()) {
951 for (User *U : Add->users()) {
952 if (U == &I)
953 continue;
954
955 TruncInst *Trunc = dyn_cast<TruncInst>(U);
956 if (!Trunc || Trunc->getType()->getScalarSizeInBits() > ShAmt)
957 return nullptr;
958 }
959 }
960
961 // Insert at Add so that the newly created `NarrowAdd` will dominate it's
962 // users (i.e. `Add`'s users).
964 Builder.SetInsertPoint(AddInst);
965
966 Value *NarrowAdd = Builder.CreateAdd(X, Y, "add.narrowed");
967 Value *Overflow =
968 Builder.CreateICmpULT(NarrowAdd, X, "add.narrowed.overflow");
969
970 // Replace the uses of the original add with a zext of the
971 // NarrowAdd's result. Note that all users at this stage are known to
972 // be ShAmt-sized truncs, or the lshr itself.
973 if (!Add->hasOneUse()) {
974 replaceInstUsesWith(*AddInst, Builder.CreateZExt(NarrowAdd, Ty));
975 eraseInstFromFunction(*AddInst);
976 }
977
978 // Replace the LShr with a zext of the overflow check.
979 return new ZExtInst(Overflow, Ty);
980}
981
982// Try to set nuw/nsw flags on shl or exact flag on lshr/ashr using knownbits.
984 assert(I.isShift() && "Expected a shift as input");
985 // We already have all the flags.
986 if (I.getOpcode() == Instruction::Shl) {
987 if (I.hasNoUnsignedWrap() && I.hasNoSignedWrap())
988 return false;
989 } else {
990 if (I.isExact())
991 return false;
992
993 // shr (shl X, Y), Y
994 if (match(I.getOperand(0), m_Shl(m_Value(), m_Specific(I.getOperand(1))))) {
995 I.setIsExact();
996 return true;
997 }
998 // Infer 'exact' flag if shift amount is cttz(x) on the same operand.
999 if (match(I.getOperand(1), m_Intrinsic<Intrinsic::cttz>(
1000 m_Specific(I.getOperand(0)), m_Value()))) {
1001 I.setIsExact();
1002 return true;
1003 }
1004 }
1005
1006 // Compute what we know about shift count.
1007 KnownBits KnownCnt = computeKnownBits(I.getOperand(1), Q);
1008 unsigned BitWidth = KnownCnt.getBitWidth();
1009 // Since shift produces a poison value if RHS is equal to or larger than the
1010 // bit width, we can safely assume that RHS is less than the bit width.
1011 uint64_t MaxCnt = KnownCnt.getMaxValue().getLimitedValue(BitWidth - 1);
1012
1013 KnownBits KnownAmt = computeKnownBits(I.getOperand(0), Q);
1014 bool Changed = false;
1015
1016 if (I.getOpcode() == Instruction::Shl) {
1017 // If we have as many leading zeros than maximum shift cnt we have nuw.
1018 if (!I.hasNoUnsignedWrap() && MaxCnt <= KnownAmt.countMinLeadingZeros()) {
1019 I.setHasNoUnsignedWrap();
1020 Changed = true;
1021 }
1022 // If we have more sign bits than maximum shift cnt we have nsw.
1023 if (!I.hasNoSignedWrap()) {
1024 if (MaxCnt < KnownAmt.countMinSignBits() ||
1025 MaxCnt <
1026 ComputeNumSignBits(I.getOperand(0), Q.DL, Q.AC, Q.CxtI, Q.DT)) {
1027 I.setHasNoSignedWrap();
1028 Changed = true;
1029 }
1030 }
1031 return Changed;
1032 }
1033
1034 // If we have at least as many trailing zeros as maximum count then we have
1035 // exact.
1036 Changed = MaxCnt <= KnownAmt.countMinTrailingZeros();
1037 I.setIsExact(Changed);
1038
1039 return Changed;
1040}
1041
1043 const SimplifyQuery Q = SQ.getWithInstruction(&I);
1044
1045 if (Value *V = simplifyShlInst(I.getOperand(0), I.getOperand(1),
1046 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q))
1047 return replaceInstUsesWith(I, V);
1048
1050 return X;
1051
1053 return V;
1054
1056 return V;
1057
1058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1059 Type *Ty = I.getType();
1060 unsigned BitWidth = Ty->getScalarSizeInBits();
1061
1062 const APInt *C;
1063 if (match(Op1, m_APInt(C))) {
1064 unsigned ShAmtC = C->getZExtValue();
1065
1066 // shl (zext X), C --> zext (shl X, C)
1067 // This is only valid if X would have zeros shifted out.
1068 Value *X;
1069 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) {
1070 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1071 if (ShAmtC < SrcWidth &&
1072 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmtC), &I))
1073 return new ZExtInst(Builder.CreateShl(X, ShAmtC), Ty);
1074 }
1075
1076 // (X >> C) << C --> X & (-1 << C)
1077 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) {
1079 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1080 }
1081
1082 const APInt *C1;
1083 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(C1)))) &&
1084 C1->ult(BitWidth)) {
1085 unsigned ShrAmt = C1->getZExtValue();
1086 if (ShrAmt < ShAmtC) {
1087 // If C1 < C: (X >>?,exact C1) << C --> X << (C - C1)
1088 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
1089 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1090 NewShl->setHasNoUnsignedWrap(
1091 I.hasNoUnsignedWrap() ||
1092 (ShrAmt &&
1093 cast<Instruction>(Op0)->getOpcode() == Instruction::LShr &&
1094 I.hasNoSignedWrap()));
1095 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1096 return NewShl;
1097 }
1098 if (ShrAmt > ShAmtC) {
1099 // If C1 > C: (X >>?exact C1) << C --> X >>?exact (C1 - C)
1100 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
1101 auto *NewShr = BinaryOperator::Create(
1102 cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff);
1103 NewShr->setIsExact(true);
1104 return NewShr;
1105 }
1106 }
1107
1108 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_APInt(C1)))) &&
1109 C1->ult(BitWidth)) {
1110 unsigned ShrAmt = C1->getZExtValue();
1111 if (ShrAmt < ShAmtC) {
1112 // If C1 < C: (X >>? C1) << C --> (X << (C - C1)) & (-1 << C)
1113 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShrAmt);
1114 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1115 NewShl->setHasNoUnsignedWrap(
1116 I.hasNoUnsignedWrap() ||
1117 (ShrAmt &&
1118 cast<Instruction>(Op0)->getOpcode() == Instruction::LShr &&
1119 I.hasNoSignedWrap()));
1120 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
1121 Builder.Insert(NewShl);
1123 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1124 }
1125 if (ShrAmt > ShAmtC) {
1126 // If C1 > C: (X >>? C1) << C --> (X >>? (C1 - C)) & (-1 << C)
1127 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmtC);
1128 auto *OldShr = cast<BinaryOperator>(Op0);
1129 auto *NewShr =
1130 BinaryOperator::Create(OldShr->getOpcode(), X, ShiftDiff);
1131 NewShr->setIsExact(OldShr->isExact());
1132 Builder.Insert(NewShr);
1134 return BinaryOperator::CreateAnd(NewShr, ConstantInt::get(Ty, Mask));
1135 }
1136 }
1137
1138 // Similar to above, but look through an intermediate trunc instruction.
1139 BinaryOperator *Shr;
1140 if (match(Op0, m_OneUse(m_Trunc(m_OneUse(m_BinOp(Shr))))) &&
1141 match(Shr, m_Shr(m_Value(X), m_APInt(C1)))) {
1142 // The larger shift direction survives through the transform.
1143 unsigned ShrAmtC = C1->getZExtValue();
1144 unsigned ShDiff = ShrAmtC > ShAmtC ? ShrAmtC - ShAmtC : ShAmtC - ShrAmtC;
1145 Constant *ShiftDiffC = ConstantInt::get(X->getType(), ShDiff);
1146 auto ShiftOpc = ShrAmtC > ShAmtC ? Shr->getOpcode() : Instruction::Shl;
1147
1148 // If C1 > C:
1149 // (trunc (X >> C1)) << C --> (trunc (X >> (C1 - C))) && (-1 << C)
1150 // If C > C1:
1151 // (trunc (X >> C1)) << C --> (trunc (X << (C - C1))) && (-1 << C)
1152 Value *NewShift = Builder.CreateBinOp(ShiftOpc, X, ShiftDiffC, "sh.diff");
1153 Value *Trunc = Builder.CreateTrunc(NewShift, Ty, "tr.sh.diff");
1155 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, Mask));
1156 }
1157
1158 // If we have an opposite shift by the same amount, we may be able to
1159 // reorder binops and shifts to eliminate math/logic.
1160 auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1161 switch (BinOpcode) {
1162 default:
1163 return false;
1164 case Instruction::Add:
1165 case Instruction::And:
1166 case Instruction::Or:
1167 case Instruction::Xor:
1168 case Instruction::Sub:
1169 // NOTE: Sub is not commutable and the tranforms below may not be valid
1170 // when the shift-right is operand 1 (RHS) of the sub.
1171 return true;
1172 }
1173 };
1174 BinaryOperator *Op0BO;
1175 if (match(Op0, m_OneUse(m_BinOp(Op0BO))) &&
1176 isSuitableBinOpcode(Op0BO->getOpcode())) {
1177 // Commute so shift-right is on LHS of the binop.
1178 // (Y bop (X >> C)) << C -> ((X >> C) bop Y) << C
1179 // (Y bop ((X >> C) & CC)) << C -> (((X >> C) & CC) bop Y) << C
1180 Value *Shr = Op0BO->getOperand(0);
1181 Value *Y = Op0BO->getOperand(1);
1182 Value *X;
1183 const APInt *CC;
1184 if (Op0BO->isCommutative() && Y->hasOneUse() &&
1185 (match(Y, m_Shr(m_Value(), m_Specific(Op1))) ||
1187 m_APInt(CC)))))
1188 std::swap(Shr, Y);
1189
1190 // ((X >> C) bop Y) << C -> (X bop (Y << C)) & (~0 << C)
1191 if (match(Shr, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1192 // Y << C
1193 Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1194 // (X bop (Y << C))
1195 Value *B =
1196 Builder.CreateBinOp(Op0BO->getOpcode(), X, YS, Shr->getName());
1197 unsigned Op1Val = C->getLimitedValue(BitWidth);
1198 APInt Bits = APInt::getHighBitsSet(BitWidth, BitWidth - Op1Val);
1199 Constant *Mask = ConstantInt::get(Ty, Bits);
1200 return BinaryOperator::CreateAnd(B, Mask);
1201 }
1202
1203 // (((X >> C) & CC) bop Y) << C -> (X & (CC << C)) bop (Y << C)
1204 if (match(Shr,
1206 m_APInt(CC))))) {
1207 // Y << C
1208 Value *YS = Builder.CreateShl(Y, Op1, Op0BO->getName());
1209 // X & (CC << C)
1210 Value *M = Builder.CreateAnd(X, ConstantInt::get(Ty, CC->shl(*C)),
1211 X->getName() + ".mask");
1212 auto *NewOp = BinaryOperator::Create(Op0BO->getOpcode(), M, YS);
1213 if (auto *Disjoint = dyn_cast<PossiblyDisjointInst>(Op0BO);
1214 Disjoint && Disjoint->isDisjoint())
1215 cast<PossiblyDisjointInst>(NewOp)->setIsDisjoint(true);
1216 return NewOp;
1217 }
1218 }
1219
1220 // (C1 - X) << C --> (C1 << C) - (X << C)
1221 if (match(Op0, m_OneUse(m_Sub(m_APInt(C1), m_Value(X))))) {
1222 Constant *NewLHS = ConstantInt::get(Ty, C1->shl(*C));
1223 Value *NewShift = Builder.CreateShl(X, Op1);
1224 return BinaryOperator::CreateSub(NewLHS, NewShift);
1225 }
1226 }
1227
1228 if (setShiftFlags(I, Q))
1229 return &I;
1230
1231 // Transform (x >> y) << y to x & (-1 << y)
1232 // Valid for any type of right-shift.
1233 Value *X;
1234 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) {
1236 Value *Mask = Builder.CreateShl(AllOnes, Op1);
1237 return BinaryOperator::CreateAnd(Mask, X);
1238 }
1239
1240 // Transform (-1 >> y) << y to -1 << y
1241 if (match(Op0, m_LShr(m_AllOnes(), m_Specific(Op1)))) {
1243 return BinaryOperator::CreateShl(AllOnes, Op1);
1244 }
1245
1246 Constant *C1;
1247 if (match(Op1, m_ImmConstant(C1))) {
1248 Constant *C2;
1249 Value *X;
1250 // (X * C2) << C1 --> X * (C2 << C1)
1251 if (match(Op0, m_Mul(m_Value(X), m_ImmConstant(C2))))
1252 return BinaryOperator::CreateMul(X, Builder.CreateShl(C2, C1));
1253
1254 // shl (zext i1 X), C1 --> select (X, 1 << C1, 0)
1255 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
1256 auto *NewC = Builder.CreateShl(ConstantInt::get(Ty, 1), C1);
1257 return createSelectInstWithUnknownProfile(X, NewC,
1259 }
1260 }
1261
1262 if (match(Op0, m_One())) {
1263 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1
1264 if (match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X))))
1265 return BinaryOperator::CreateLShr(
1266 ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X);
1267
1268 // Canonicalize "extract lowest set bit" using cttz to and-with-negate:
1269 // 1 << (cttz X) --> -X & X
1270 if (match(Op1,
1272 Value *NegX = Builder.CreateNeg(X, "neg");
1273 return BinaryOperator::CreateAnd(NegX, X);
1274 }
1275 }
1276
1277 return nullptr;
1278}
1279
1281 if (Value *V = simplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1282 SQ.getWithInstruction(&I)))
1283 return replaceInstUsesWith(I, V);
1284
1286 return X;
1287
1289 return R;
1290
1291 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1292 Type *Ty = I.getType();
1293 Value *X;
1294 const APInt *C;
1295 unsigned BitWidth = Ty->getScalarSizeInBits();
1296
1297 // (iN (~X) u>> (N - 1)) --> zext (X > -1)
1298 if (match(Op0, m_OneUse(m_Not(m_Value(X)))) &&
1300 return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
1301
1302 // ((X << nuw Z) sub nuw Y) >>u exact Z --> X sub nuw (Y >>u exact Z)
1303 Value *Y;
1304 if (I.isExact() &&
1306 m_Value(Y))))) {
1307 Value *NewLshr = Builder.CreateLShr(Y, Op1, "", /*isExact=*/true);
1308 auto *NewSub = BinaryOperator::CreateNUWSub(X, NewLshr);
1309 NewSub->setHasNoSignedWrap(
1311 return NewSub;
1312 }
1313
1314 // Fold (X + Y) / 2 --> (X & Y) iff (X u<= 1) && (Y u<= 1)
1315 if (match(Op0, m_Add(m_Value(X), m_Value(Y))) && match(Op1, m_One()) &&
1316 computeKnownBits(X, &I).countMaxActiveBits() <= 1 &&
1317 computeKnownBits(Y, &I).countMaxActiveBits() <= 1)
1318 return BinaryOperator::CreateAnd(X, Y);
1319
1320 // (sub nuw X, (Y << nuw Z)) >>u exact Z --> (X >>u exact Z) sub nuw Y
1321 if (I.isExact() &&
1323 m_NUWShl(m_Value(Y), m_Specific(Op1)))))) {
1324 Value *NewLshr = Builder.CreateLShr(X, Op1, "", /*isExact=*/true);
1325 auto *NewSub = BinaryOperator::CreateNUWSub(NewLshr, Y);
1326 NewSub->setHasNoSignedWrap(
1328 return NewSub;
1329 }
1330
1331 auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
1332 switch (BinOpcode) {
1333 default:
1334 return false;
1335 case Instruction::Add:
1336 case Instruction::And:
1337 case Instruction::Or:
1338 case Instruction::Xor:
1339 // Sub is handled separately.
1340 return true;
1341 }
1342 };
1343
1344 // If both the binop and the shift are nuw, then:
1345 // ((X << nuw Z) binop nuw Y) >>u Z --> X binop nuw (Y >>u Z)
1347 m_Value(Y))))) {
1349 if (isSuitableBinOpcode(Op0OB->getOpcode())) {
1350 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op0);
1351 !OBO || OBO->hasNoUnsignedWrap()) {
1352 Value *NewLshr = Builder.CreateLShr(
1353 Y, Op1, "", I.isExact() && Op0OB->getOpcode() != Instruction::And);
1354 auto *NewBinOp = BinaryOperator::Create(Op0OB->getOpcode(), NewLshr, X);
1355 if (OBO) {
1356 NewBinOp->setHasNoUnsignedWrap(true);
1357 NewBinOp->setHasNoSignedWrap(OBO->hasNoSignedWrap());
1358 } else if (auto *Disjoint = dyn_cast<PossiblyDisjointInst>(Op0)) {
1359 cast<PossiblyDisjointInst>(NewBinOp)->setIsDisjoint(
1360 Disjoint->isDisjoint());
1361 }
1362 return NewBinOp;
1363 }
1364 }
1365 }
1366
1367 if (match(Op1, m_APInt(C))) {
1368 unsigned ShAmtC = C->getZExtValue();
1369 auto *II = dyn_cast<IntrinsicInst>(Op0);
1370 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmtC &&
1371 (II->getIntrinsicID() == Intrinsic::ctlz ||
1372 II->getIntrinsicID() == Intrinsic::cttz ||
1373 II->getIntrinsicID() == Intrinsic::ctpop)) {
1374 // ctlz.i32(x)>>5 --> zext(x == 0)
1375 // cttz.i32(x)>>5 --> zext(x == 0)
1376 // ctpop.i32(x)>>5 --> zext(x == -1)
1377 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop;
1378 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0);
1379 Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS);
1380 return new ZExtInst(Cmp, Ty);
1381 }
1382
1383 const APInt *C1;
1384 if (match(Op0, m_Shl(m_Value(X), m_APInt(C1))) && C1->ult(BitWidth)) {
1385 if (C1->ult(ShAmtC)) {
1386 unsigned ShlAmtC = C1->getZExtValue();
1387 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmtC - ShlAmtC);
1389 // (X <<nuw C1) >>u C --> X >>u (C - C1)
1390 auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff);
1391 NewLShr->setIsExact(I.isExact());
1392 return NewLShr;
1393 }
1394 if (Op0->hasOneUse()) {
1395 // (X << C1) >>u C --> (X >>u (C - C1)) & (-1 >> C)
1396 Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact());
1398 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask));
1399 }
1400 } else if (C1->ugt(ShAmtC)) {
1401 unsigned ShlAmtC = C1->getZExtValue();
1402 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmtC - ShAmtC);
1404 // (X <<nuw C1) >>u C --> X <<nuw/nsw (C1 - C)
1405 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff);
1406 NewShl->setHasNoUnsignedWrap(true);
1407 NewShl->setHasNoSignedWrap(ShAmtC > 0);
1408 return NewShl;
1409 }
1410 if (Op0->hasOneUse()) {
1411 // (X << C1) >>u C --> X << (C1 - C) & (-1 >> C)
1412 Value *NewShl = Builder.CreateShl(X, ShiftDiff);
1414 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask));
1415 }
1416 } else {
1417 assert(*C1 == ShAmtC);
1418 // (X << C) >>u C --> X & (-1 >>u C)
1420 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask));
1421 }
1422 }
1423
1424 // ((X << C) + Y) >>u C --> (X + (Y >>u C)) & (-1 >>u C)
1425 // TODO: Consolidate with the more general transform that starts from shl
1426 // (the shifts are in the opposite order).
1427 if (match(Op0,
1429 m_Value(Y))))) {
1430 Value *NewLshr = Builder.CreateLShr(Y, Op1);
1431 Value *NewAdd = Builder.CreateAdd(NewLshr, X);
1432 unsigned Op1Val = C->getLimitedValue(BitWidth);
1433 APInt Bits = APInt::getLowBitsSet(BitWidth, BitWidth - Op1Val);
1434 Constant *Mask = ConstantInt::get(Ty, Bits);
1435 return BinaryOperator::CreateAnd(NewAdd, Mask);
1436 }
1437
1438 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) &&
1439 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) {
1440 assert(ShAmtC < X->getType()->getScalarSizeInBits() &&
1441 "Big shift not simplified to zero?");
1442 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN
1443 Value *NewLShr = Builder.CreateLShr(X, ShAmtC);
1444 return new ZExtInst(NewLShr, Ty);
1445 }
1446
1447 if (match(Op0, m_SExt(m_Value(X)))) {
1448 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits();
1449 // lshr (sext i1 X to iN), C --> select (X, -1 >> C, 0)
1450 if (SrcTyBitWidth == 1) {
1451 auto *NewC = ConstantInt::get(
1452 Ty, APInt::getLowBitsSet(BitWidth, BitWidth - ShAmtC));
1454 }
1455
1456 if ((!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType())) &&
1457 Op0->hasOneUse()) {
1458 // Are we moving the sign bit to the low bit and widening with high
1459 // zeros? lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN
1460 if (ShAmtC == BitWidth - 1) {
1461 Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1);
1462 return new ZExtInst(NewLShr, Ty);
1463 }
1464
1465 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN
1466 if (ShAmtC == BitWidth - SrcTyBitWidth) {
1467 // The new shift amount can't be more than the narrow source type.
1468 unsigned NewShAmt = std::min(ShAmtC, SrcTyBitWidth - 1);
1469 Value *AShr = Builder.CreateAShr(X, NewShAmt);
1470 return new ZExtInst(AShr, Ty);
1471 }
1472 }
1473 }
1474
1475 if (ShAmtC == BitWidth - 1) {
1476 // lshr i32 or(X,-X), 31 --> zext (X != 0)
1477 if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1478 return new ZExtInst(Builder.CreateIsNotNull(X), Ty);
1479
1480 // lshr i32 (X -nsw Y), 31 --> zext (X < Y)
1481 if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1482 return new ZExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1483
1484 // Check if a number is negative and odd:
1485 // lshr i32 (srem X, 2), 31 --> and (X >> 31), X
1486 if (match(Op0, m_OneUse(m_SRem(m_Value(X), m_SpecificInt(2))))) {
1487 Value *Signbit = Builder.CreateLShr(X, ShAmtC);
1488 return BinaryOperator::CreateAnd(Signbit, X);
1489 }
1490
1491 // lshr iN (X - 1) & ~X, N-1 --> zext (X == 0)
1493 m_Not(m_Deferred(X))))))
1494 return new ZExtInst(Builder.CreateIsNull(X), Ty);
1495 }
1496
1497 Instruction *TruncSrc;
1498 if (match(Op0, m_OneUse(m_Trunc(m_Instruction(TruncSrc)))) &&
1499 match(TruncSrc, m_LShr(m_Value(X), m_APInt(C1)))) {
1500 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1501 unsigned AmtSum = ShAmtC + C1->getZExtValue();
1502
1503 // If the combined shift fits in the source width:
1504 // (trunc (X >>u C1)) >>u C --> and (trunc (X >>u (C1 + C)), MaskC
1505 //
1506 // If the first shift covers the number of bits truncated, then the
1507 // mask instruction is eliminated (and so the use check is relaxed).
1508 if (AmtSum < SrcWidth &&
1509 (TruncSrc->hasOneUse() || C1->uge(SrcWidth - BitWidth))) {
1510 Value *SumShift = Builder.CreateLShr(X, AmtSum, "sum.shift");
1511 Value *Trunc = Builder.CreateTrunc(SumShift, Ty, I.getName());
1512
1513 // If the first shift does not cover the number of bits truncated, then
1514 // we require a mask to get rid of high bits in the result.
1515 APInt MaskC = APInt::getAllOnes(BitWidth).lshr(ShAmtC);
1516 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Ty, MaskC));
1517 }
1518 }
1519
1520 const APInt *MulC;
1521 if (match(Op0, m_NUWMul(m_Value(X), m_APInt(MulC)))) {
1522 if (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1523 MulC->logBase2() == ShAmtC) {
1524 // Look for a "splat" mul pattern - it replicates bits across each half
1525 // of a value, so a right shift simplifies back to just X:
1526 // lshr i[2N] (mul nuw X, (2^N)+1), N --> X
1527 if (ShAmtC * 2 == BitWidth)
1528 return replaceInstUsesWith(I, X);
1529
1530 // lshr (mul nuw (X, 2^N + 1)), N -> add nuw (X, lshr(X, N))
1531 if (Op0->hasOneUse()) {
1532 auto *NewAdd = BinaryOperator::CreateNUWAdd(
1533 X, Builder.CreateLShr(X, ConstantInt::get(Ty, ShAmtC), "",
1534 I.isExact()));
1535 NewAdd->setHasNoSignedWrap(
1537 return NewAdd;
1538 }
1539 }
1540
1541 // The one-use check is not strictly necessary, but codegen may not be
1542 // able to invert the transform and perf may suffer with an extra mul
1543 // instruction.
1544 if (Op0->hasOneUse()) {
1545 APInt NewMulC = MulC->lshr(ShAmtC);
1546 // if c is divisible by (1 << ShAmtC):
1547 // lshr (mul nuw x, MulC), ShAmtC -> mul nuw nsw x, (MulC >> ShAmtC)
1548 if (MulC->eq(NewMulC.shl(ShAmtC))) {
1549 auto *NewMul =
1550 BinaryOperator::CreateNUWMul(X, ConstantInt::get(Ty, NewMulC));
1551 assert(ShAmtC != 0 &&
1552 "lshr X, 0 should be handled by simplifyLShrInst.");
1553 NewMul->setHasNoSignedWrap(true);
1554 return NewMul;
1555 }
1556 }
1557 }
1558
1559 // lshr (mul nsw (X, 2^N + 1)), N -> add nsw (X, lshr(X, N))
1560 if (match(Op0, m_OneUse(m_NSWMul(m_Value(X), m_APInt(MulC))))) {
1561 if (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1562 MulC->logBase2() == ShAmtC) {
1563 return BinaryOperator::CreateNSWAdd(
1564 X, Builder.CreateLShr(X, ConstantInt::get(Ty, ShAmtC), "",
1565 I.isExact()));
1566 }
1567 }
1568
1569 // Try to narrow bswap.
1570 // In the case where the shift amount equals the bitwidth difference, the
1571 // shift is eliminated.
1573 m_OneUse(m_ZExt(m_Value(X))))))) {
1574 unsigned SrcWidth = X->getType()->getScalarSizeInBits();
1575 unsigned WidthDiff = BitWidth - SrcWidth;
1576 if (SrcWidth % 16 == 0) {
1577 Value *NarrowSwap = Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X);
1578 if (ShAmtC >= WidthDiff) {
1579 // (bswap (zext X)) >> C --> zext (bswap X >> C')
1580 Value *NewShift = Builder.CreateLShr(NarrowSwap, ShAmtC - WidthDiff);
1581 return new ZExtInst(NewShift, Ty);
1582 } else {
1583 // (bswap (zext X)) >> C --> (zext (bswap X)) << C'
1584 Value *NewZExt = Builder.CreateZExt(NarrowSwap, Ty);
1585 Constant *ShiftDiff = ConstantInt::get(Ty, WidthDiff - ShAmtC);
1586 return BinaryOperator::CreateShl(NewZExt, ShiftDiff);
1587 }
1588 }
1589 }
1590
1591 // Reduce add-carry of bools to logic:
1592 // ((zext BoolX) + (zext BoolY)) >> 1 --> zext (BoolX && BoolY)
1593 Value *BoolX, *BoolY;
1594 if (ShAmtC == 1 && match(Op0, m_Add(m_Value(X), m_Value(Y))) &&
1595 match(X, m_ZExt(m_Value(BoolX))) && match(Y, m_ZExt(m_Value(BoolY))) &&
1596 BoolX->getType()->isIntOrIntVectorTy(1) &&
1597 BoolY->getType()->isIntOrIntVectorTy(1) &&
1598 (X->hasOneUse() || Y->hasOneUse() || Op0->hasOneUse())) {
1599 Value *And = Builder.CreateAnd(BoolX, BoolY);
1600 return new ZExtInst(And, Ty);
1601 }
1602 }
1603
1604 const SimplifyQuery Q = SQ.getWithInstruction(&I);
1605 if (setShiftFlags(I, Q))
1606 return &I;
1607
1608 // Transform (x << y) >> y to x & (-1 >> y)
1609 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) {
1611 Value *Mask = Builder.CreateLShr(AllOnes, Op1);
1612 return BinaryOperator::CreateAnd(Mask, X);
1613 }
1614
1615 // Transform (-1 << y) >> y to -1 >> y
1616 if (match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1)))) {
1618 return BinaryOperator::CreateLShr(AllOnes, Op1);
1619 }
1620
1621 if (Instruction *Overflow = foldLShrOverflowBit(I))
1622 return Overflow;
1623
1624 // Transform ((pow2 << x) >> cttz(pow2 << y)) -> ((1 << x) >> y)
1625 Value *Shl0_Op0, *Shl0_Op1, *Shl1_Op1;
1626 BinaryOperator *Shl1;
1627 if (match(Op0, m_Shl(m_Value(Shl0_Op0), m_Value(Shl0_Op1))) &&
1629 match(Shl1, m_Shl(m_Specific(Shl0_Op0), m_Value(Shl1_Op1))) &&
1630 isKnownToBeAPowerOfTwo(Shl0_Op0, /*OrZero=*/true, &I)) {
1631 auto *Shl0 = cast<BinaryOperator>(Op0);
1632 bool HasNUW = Shl0->hasNoUnsignedWrap() && Shl1->hasNoUnsignedWrap();
1633 bool HasNSW = Shl0->hasNoSignedWrap() && Shl1->hasNoSignedWrap();
1634 if (HasNUW || HasNSW) {
1635 Value *NewShl = Builder.CreateShl(ConstantInt::get(Shl1->getType(), 1),
1636 Shl0_Op1, "", HasNUW, HasNSW);
1637 return BinaryOperator::CreateLShr(NewShl, Shl1_Op1);
1638 }
1639 }
1640 return nullptr;
1641}
1642
1645 BinaryOperator &OldAShr) {
1646 assert(OldAShr.getOpcode() == Instruction::AShr &&
1647 "Must be called with arithmetic right-shift instruction only.");
1648
1649 // Check that constant C is a splat of the element-wise bitwidth of V.
1650 auto BitWidthSplat = [](Constant *C, Value *V) {
1651 return match(
1653 APInt(C->getType()->getScalarSizeInBits(),
1654 V->getType()->getScalarSizeInBits())));
1655 };
1656
1657 // It should look like variable-length sign-extension on the outside:
1658 // (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits)
1659 Value *NBits;
1660 Instruction *MaybeTrunc;
1661 Constant *C1, *C2;
1662 if (!match(&OldAShr,
1663 m_AShr(m_Shl(m_Instruction(MaybeTrunc),
1665 m_ZExtOrSelf(m_Value(NBits))))),
1667 m_ZExtOrSelf(m_Deferred(NBits)))))) ||
1668 !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr))
1669 return nullptr;
1670
1671 // There may or may not be a truncation after outer two shifts.
1672 Instruction *HighBitExtract;
1673 match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract)));
1674 bool HadTrunc = MaybeTrunc != HighBitExtract;
1675
1676 // And finally, the innermost part of the pattern must be a right-shift.
1677 Value *X, *NumLowBitsToSkip;
1678 if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip))))
1679 return nullptr;
1680
1681 // Said right-shift must extract high NBits bits - C0 must be it's bitwidth.
1682 Constant *C0;
1683 if (!match(NumLowBitsToSkip,
1685 m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) ||
1686 !BitWidthSplat(C0, HighBitExtract))
1687 return nullptr;
1688
1689 // Since the NBits is identical for all shifts, if the outermost and
1690 // innermost shifts are identical, then outermost shifts are redundant.
1691 // If we had truncation, do keep it though.
1692 if (HighBitExtract->getOpcode() == OldAShr.getOpcode())
1693 return replaceInstUsesWith(OldAShr, MaybeTrunc);
1694
1695 // Else, if there was a truncation, then we need to ensure that one
1696 // instruction will go away.
1697 if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1698 return nullptr;
1699
1700 // Finally, bypass two innermost shifts, and perform the outermost shift on
1701 // the operands of the innermost shift.
1702 Instruction *NewAShr =
1703 BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip);
1704 NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness.
1705 if (!HadTrunc)
1706 return NewAShr;
1707
1708 Builder.Insert(NewAShr);
1709 return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType());
1710}
1711
1713 if (Value *V = simplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(),
1714 SQ.getWithInstruction(&I)))
1715 return replaceInstUsesWith(I, V);
1716
1718 return X;
1719
1721 return R;
1722
1723 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1724 Type *Ty = I.getType();
1725 unsigned BitWidth = Ty->getScalarSizeInBits();
1726 const APInt *ShAmtAPInt;
1727 if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) {
1728 unsigned ShAmt = ShAmtAPInt->getZExtValue();
1729
1730 // If the shift amount equals the difference in width of the destination
1731 // and source scalar types:
1732 // ashr (shl (zext X), C), C --> sext X
1733 Value *X;
1734 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) &&
1735 ShAmt == BitWidth - X->getType()->getScalarSizeInBits())
1736 return new SExtInst(X, Ty);
1737
1738 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However,
1739 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits.
1740 const APInt *ShOp1;
1741 if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) &&
1742 ShOp1->ult(BitWidth)) {
1743 unsigned ShlAmt = ShOp1->getZExtValue();
1744 if (ShlAmt < ShAmt) {
1745 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1)
1746 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt);
1747 auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff);
1748 NewAShr->setIsExact(I.isExact());
1749 return NewAShr;
1750 }
1751 if (ShlAmt > ShAmt) {
1752 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2)
1753 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt);
1754 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff);
1755 NewShl->setHasNoSignedWrap(true);
1756 return NewShl;
1757 }
1758 }
1759
1760 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) &&
1761 ShOp1->ult(BitWidth)) {
1762 unsigned AmtSum = ShAmt + ShOp1->getZExtValue();
1763 // Oversized arithmetic shifts replicate the sign bit.
1764 AmtSum = std::min(AmtSum, BitWidth - 1);
1765 // (X >>s C1) >>s C2 --> X >>s (C1 + C2)
1766 return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
1767 }
1768
1769 if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) &&
1770 (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) {
1771 // ashr (sext X), C --> sext (ashr X, C')
1772 Type *SrcTy = X->getType();
1773 ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1);
1774 Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt));
1775 return new SExtInst(NewSh, Ty);
1776 }
1777
1778 if (ShAmt == BitWidth - 1) {
1779 // ashr i32 or(X,-X), 31 --> sext (X != 0)
1780 if (match(Op0, m_OneUse(m_c_Or(m_Neg(m_Value(X)), m_Deferred(X)))))
1781 return new SExtInst(Builder.CreateIsNotNull(X), Ty);
1782
1783 // ashr i32 (X -nsw Y), 31 --> sext (X < Y)
1784 Value *Y;
1785 if (match(Op0, m_OneUse(m_NSWSub(m_Value(X), m_Value(Y)))))
1786 return new SExtInst(Builder.CreateICmpSLT(X, Y), Ty);
1787
1788 // ashr iN (X - 1) & ~X, N-1 --> sext (X == 0)
1790 m_Not(m_Deferred(X))))))
1791 return new SExtInst(Builder.CreateIsNull(X), Ty);
1792 }
1793
1794 const APInt *MulC;
1795 if (match(Op0, m_OneUse(m_NSWMul(m_Value(X), m_APInt(MulC)))) &&
1796 (BitWidth > 2 && (*MulC - 1).isPowerOf2() &&
1797 MulC->logBase2() == ShAmt &&
1798 (ShAmt < BitWidth - 1))) /* Minus 1 for the sign bit */ {
1799
1800 // ashr (mul nsw (X, 2^N + 1)), N -> add nsw (X, ashr(X, N))
1801 auto *NewAdd = BinaryOperator::CreateNSWAdd(
1802 X,
1803 Builder.CreateAShr(X, ConstantInt::get(Ty, ShAmt), "", I.isExact()));
1804 NewAdd->setHasNoUnsignedWrap(
1806 return NewAdd;
1807 }
1808 }
1809
1810 const SimplifyQuery Q = SQ.getWithInstruction(&I);
1811 if (setShiftFlags(I, Q))
1812 return &I;
1813
1814 // Prefer `-(x & 1)` over `(x << (bitwidth(x)-1)) a>> (bitwidth(x)-1)`
1815 // as the pattern to splat the lowest bit.
1816 // FIXME: iff X is already masked, we don't need the one-use check.
1817 Value *X;
1818 if (match(Op1, m_SpecificIntAllowPoison(BitWidth - 1)) &&
1821 Constant *Mask = ConstantInt::get(Ty, 1);
1822 // Retain the knowledge about the ignored lanes.
1825 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)));
1826 X = Builder.CreateAnd(X, Mask);
1828 }
1829
1831 return R;
1832
1833 // See if we can turn a signed shr into an unsigned shr.
1835 Instruction *Lshr = BinaryOperator::CreateLShr(Op0, Op1);
1836 Lshr->setIsExact(I.isExact());
1837 return Lshr;
1838 }
1839
1840 // ashr (xor %x, -1), %y --> xor (ashr %x, %y), -1
1841 if (match(Op0, m_OneUse(m_Not(m_Value(X))))) {
1842 // Note that we must drop 'exact'-ness of the shift!
1843 // Note that we can't keep undef's in -1 vector constant!
1844 auto *NewAShr = Builder.CreateAShr(X, Op1, Op0->getName() + ".not");
1845 return BinaryOperator::CreateNot(NewAShr);
1846 }
1847
1848 return nullptr;
1849}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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 bool setShiftFlags(BinaryOperator &I, const SimplifyQuery &Q)
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 hasNoSignedWrap(BinaryOperator &I)
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
static const MCExpr * MaskShift(const MCExpr *Val, uint32_t Mask, uint32_t Shift, MCContext &Ctx)
#define LLVM_DEBUG(...)
Definition Debug.h:114
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition VPlanSLP.cpp:247
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:450
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1541
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1183
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1112
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
bool eq(const APInt &RHS) const
Equality comparison.
Definition APInt.h:1080
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1640
unsigned logBase2() const
Definition APInt.h:1762
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:874
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:297
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:852
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1222
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
BinaryOps getOpcode() const
Definition InstrTypes.h:374
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:136
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
static LLVM_ABI Constant * mergeUndefsWith(Constant *C, Constant *Other)
Merges undefs of a Constant with another Constant, along with the undefs already present.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1513
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1492
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 * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitAShr(BinaryOperator &I)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
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)
SimplifyQuery SQ
IRBuilder< TargetFolder, IRBuilderCallbackInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
AssumptionCache & AC
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const Instruction *CxtI=nullptr, unsigned Depth=0) const
BuilderTy & Builder
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CxtI=nullptr, unsigned Depth=0)
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI 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.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI 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="", InsertPosition InsertBefore=nullptr, const 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 isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
LLVM_ABI Type * getExtendedType() const
Given scalar/vector integer type, returns a type with elements twice as wide as in the original type.
void setOperand(unsigned i, Value *Val)
Definition User.h:237
Value * getOperand(unsigned i) const
Definition User.h:232
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
This class represents zero extension of integer types.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#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
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
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.
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
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.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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.
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()...
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
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)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
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< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
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.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
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.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Value * simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a AShr, fold the result or return nulll.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI Value * simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Sub, fold the result or return null.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:331
LLVM_ABI 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:279
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI Value * simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact, const SimplifyQuery &Q)
Given operands for a LShr, fold the result or return null.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
@ Add
Sum of integers.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:255
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:242
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:248
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:145
Matching combinators.
const DataLayout & DL
const Instruction * CxtI
const DominatorTree * DT
AssumptionCache * AC