LLVM 24.0.0git
InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
1//===- InstCombineSimplifyDemanded.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 contains logic for simplifying instructions based on information
10// about how they are used.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
23
24using namespace llvm;
25using namespace llvm::PatternMatch;
26
27#define DEBUG_TYPE "instcombine"
28
29/// Check to see if the specified operand of the specified instruction is a
30/// constant integer. If so, check to see if there are any bits set in the
31/// constant that are not demanded. If so, shrink the constant and return true.
32static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
33 const APInt &Demanded) {
34 assert(I && "No instruction?");
35 assert(OpNo < I->getNumOperands() && "Operand index too large");
36
37 // The operand must be a constant integer or splat integer.
38 Value *Op = I->getOperand(OpNo);
39 const APInt *C;
40 if (!match(Op, m_APInt(C)))
41 return false;
42
43 // If there are no bits set that aren't demanded, nothing to do.
44 if (C->isSubsetOf(Demanded))
45 return false;
46
47 // This instruction is producing bits that are not demanded. Shrink the RHS.
48 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
49
50 return true;
51}
52
53/// Let N = 2 * M.
54/// Given an N-bit integer representing a pack of two M-bit integers,
55/// we can select one of the packed integers by right-shifting by either
56/// zero or M (which is the most straightforward to check if M is a power
57/// of 2), and then isolating the lower M bits. In this case, we can
58/// represent the shift as a select on whether the shr amount is nonzero.
60 const APInt &DemandedMask,
62 unsigned Depth) {
63 assert(I->getOpcode() == Instruction::LShr &&
64 "Only lshr instruction supported");
65
66 uint64_t ShlAmt;
67 Value *Upper, *Lower;
68 if (!match(I->getOperand(0),
71 m_Value(Lower)))))
72 return nullptr;
73
74 if (!isPowerOf2_64(ShlAmt))
75 return nullptr;
76
77 const uint64_t DemandedBitWidth = DemandedMask.getActiveBits();
78 if (DemandedBitWidth > ShlAmt)
79 return nullptr;
80
81 // Check that upper demanded bits are not lost from lshift.
82 if (Upper->getType()->getScalarSizeInBits() < ShlAmt + DemandedBitWidth)
83 return nullptr;
84
85 KnownBits KnownLowerBits = IC.computeKnownBits(Lower, I, Depth);
86 if (!KnownLowerBits.getMaxValue().isIntN(ShlAmt))
87 return nullptr;
88
89 Value *ShrAmt = I->getOperand(1);
90 KnownBits KnownShrBits = IC.computeKnownBits(ShrAmt, I, Depth);
91
92 // Verify that ShrAmt is either exactly ShlAmt (which is a power of 2) or
93 // zero.
94 if (~KnownShrBits.Zero != ShlAmt)
95 return nullptr;
96
99 Value *ShrAmtZ =
101 ShrAmt->getName() + ".z");
102 // There is no existing !prof metadata we can derive the !prof metadata for
103 // this select.
106 Select->takeName(I);
107 return Select;
108}
109
110/// Returns the bitwidth of the given scalar or pointer type. For vector types,
111/// returns the element type's bitwidth.
112static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
113 if (unsigned BitWidth = Ty->getScalarSizeInBits())
114 return BitWidth;
115
116 return DL.getPointerTypeSizeInBits(Ty);
117}
118
119/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
120/// the instruction has any properties that allow us to simplify its operands.
122 KnownBits &Known) {
123 APInt DemandedMask(APInt::getAllOnes(Known.getBitWidth()));
124 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
125 SQ.getWithInstruction(&Inst));
126 if (!V) return false;
127 if (V == &Inst) return true;
128 replaceInstUsesWith(Inst, V);
129 return true;
130}
131
132/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
133/// the instruction has any properties that allow us to simplify its operands.
138
139/// This form of SimplifyDemandedBits simplifies the specified instruction
140/// operand if possible, updating it in place. It returns true if it made any
141/// change and false otherwise.
143 const APInt &DemandedMask,
145 const SimplifyQuery &Q,
146 unsigned Depth) {
147 Use &U = I->getOperandUse(OpNo);
148 Value *V = U.get();
149 if (isa<Constant>(V)) {
151 return false;
152 }
153
154 Known.resetAll();
155 if (DemandedMask.isZero()) {
156 // Not demanding any bits from V.
157 replaceUse(U, UndefValue::get(V->getType()));
158 return true;
159 }
160
162 if (!VInst) {
164 return false;
165 }
166
168 return false;
169
170 Value *NewVal;
171 if (VInst->hasOneUse()) {
172 // If the instruction has one use, we can directly simplify it.
173 NewVal = SimplifyDemandedUseBits(VInst, DemandedMask, Known, Q, Depth);
174 } else {
175 // If there are multiple uses of this instruction, then we can simplify
176 // VInst to some other value, but not modify the instruction.
177 NewVal =
178 SimplifyMultipleUseDemandedBits(VInst, DemandedMask, Known, Q, Depth);
179 }
180 if (!NewVal) return false;
181 if (Instruction* OpInst = dyn_cast<Instruction>(U))
182 salvageDebugInfo(*OpInst);
183
184 replaceUse(U, NewVal);
185 return true;
186}
187
188/// This function attempts to replace V with a simpler value based on the
189/// demanded bits. When this function is called, it is known that only the bits
190/// set in DemandedMask of the result of V are ever used downstream.
191/// Consequently, depending on the mask and V, it may be possible to replace V
192/// with a constant or one of its operands. In such cases, this function does
193/// the replacement and returns true. In all other cases, it returns false after
194/// analyzing the expression and setting KnownOne and known to be one in the
195/// expression. Known.Zero contains all the bits that are known to be zero in
196/// the expression. These are provided to potentially allow the caller (which
197/// might recursively be SimplifyDemandedBits itself) to simplify the
198/// expression.
199/// Known.One and Known.Zero always follow the invariant that:
200/// Known.One & Known.Zero == 0.
201/// That is, a bit can't be both 1 and 0. The bits in Known.One and Known.Zero
202/// are accurate even for bits not in DemandedMask. Note
203/// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
204/// be the same.
205///
206/// This returns null if it did not change anything and it permits no
207/// simplification. This returns V itself if it did some simplification of V's
208/// operands based on the information about what bits are demanded. This returns
209/// some other non-null value if it found out that V is equal to another value
210/// in the context where the specified bits are demanded, but not for all users.
212 const APInt &DemandedMask,
214 const SimplifyQuery &Q,
215 unsigned Depth) {
216 assert(I != nullptr && "Null pointer of Value???");
217 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
218 uint32_t BitWidth = DemandedMask.getBitWidth();
219 Type *VTy = I->getType();
220 assert(
221 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
222 Known.getBitWidth() == BitWidth &&
223 "Value *V, DemandedMask and Known must have same BitWidth");
224
225 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
226
227 // Update flags after simplifying an operand based on the fact that some high
228 // order bits are not demanded.
229 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
230 unsigned NLZ) {
231 if (NLZ > 0) {
232 // Disable the nsw and nuw flags here: We can no longer guarantee that
233 // we won't wrap after simplification. Removing the nsw/nuw flags is
234 // legal here because the top bit is not demanded.
235 I->setHasNoSignedWrap(false);
236 I->setHasNoUnsignedWrap(false);
237 }
238 return I;
239 };
240
241 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
242 // about the high bits of the operands.
243 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
244 unsigned NLZ = DemandedMask.countl_zero();
245 // Right fill the mask of bits for the operands to demand the most
246 // significant bit and all those below it.
247 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
248 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
249 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Q, Depth + 1) ||
250 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
251 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1)) {
252 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
253 return true;
254 }
255 return false;
256 };
257
258 switch (I->getOpcode()) {
259 default:
261 break;
262 case Instruction::And: {
263 // If either the LHS or the RHS are Zero, the result is zero.
264 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
265 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown, Q,
266 Depth + 1))
267 return I;
268
269 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
270 Q, Depth);
271
272 // If the client is only demanding bits that we know, return the known
273 // constant.
274 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
275 return Constant::getIntegerValue(VTy, Known.One);
276
277 // If all of the demanded bits are known 1 on one side, return the other.
278 // These bits cannot contribute to the result of the 'and'.
279 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
280 return I->getOperand(0);
281 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
282 return I->getOperand(1);
283
284 // If the RHS is a constant, see if we can simplify it.
285 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
286 return I;
287
288 break;
289 }
290 case Instruction::Or: {
291 // If either the LHS or the RHS are One, the result is One.
292 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
293 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown, Q,
294 Depth + 1)) {
295 // Disjoint flag may not longer hold.
296 I->dropPoisonGeneratingFlags();
297 return I;
298 }
299
300 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
301 Q, Depth);
302
303 // If the client is only demanding bits that we know, return the known
304 // constant.
305 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
306 return Constant::getIntegerValue(VTy, Known.One);
307
308 // If all of the demanded bits are known zero on one side, return the other.
309 // These bits cannot contribute to the result of the 'or'.
310 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
311 return I->getOperand(0);
312 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
313 return I->getOperand(1);
314
315 // If the RHS is a constant, see if we can simplify it.
316 if (ShrinkDemandedConstant(I, 1, DemandedMask))
317 return I;
318
319 // Infer disjoint flag if no common bits are set.
320 if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) {
321 WithCache<const Value *> LHSCache(I->getOperand(0), LHSKnown),
322 RHSCache(I->getOperand(1), RHSKnown);
323 if (haveNoCommonBitsSet(LHSCache, RHSCache, Q)) {
324 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
325 return I;
326 }
327 }
328
329 break;
330 }
331 case Instruction::Xor: {
332 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
333 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1))
334 return I;
335 Value *LHS, *RHS;
336 if (DemandedMask == 1 && match(I->getOperand(0), m_Ctpop(m_Value(LHS))) &&
337 match(I->getOperand(1), m_Ctpop(m_Value(RHS)))) {
338 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
340 Builder.SetInsertPoint(I);
341 auto *Xor = Builder.CreateXor(LHS, RHS);
342 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
343 }
344
345 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
346 Q, Depth);
347
348 // If the client is only demanding bits that we know, return the known
349 // constant.
350 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
351 return Constant::getIntegerValue(VTy, Known.One);
352
353 // If all of the demanded bits are known zero on one side, return the other.
354 // These bits cannot contribute to the result of the 'xor'.
355 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
356 return I->getOperand(0);
357 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
358 return I->getOperand(1);
359
360 // If all of the demanded bits are known to be zero on one side or the
361 // other, turn this into an *inclusive* or.
362 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
363 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
364 Instruction *Or =
365 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1));
366 if (DemandedMask.isAllOnes())
367 cast<PossiblyDisjointInst>(Or)->setIsDisjoint(true);
368 Or->takeName(I);
369 return InsertNewInstWith(Or, I->getIterator());
370 }
371
372 // If all of the demanded bits on one side are known, and all of the set
373 // bits on that side are also known to be set on the other side, turn this
374 // into an AND, as we know the bits will be cleared.
375 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
376 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
377 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
379 ~RHSKnown.One & DemandedMask);
380 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
381 return InsertNewInstWith(And, I->getIterator());
382 }
383
384 // If the RHS is a constant, see if we can change it. Don't alter a -1
385 // constant because that's a canonical 'not' op, and that is better for
386 // combining, SCEV, and codegen.
387 const APInt *C;
388 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
389 if ((*C | ~DemandedMask).isAllOnes()) {
390 // Force bits to 1 to create a 'not' op.
391 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
392 return I;
393 }
394 // If we can't turn this into a 'not', try to shrink the constant.
395 if (ShrinkDemandedConstant(I, 1, DemandedMask))
396 return I;
397 }
398
399 // If our LHS is an 'and' and if it has one use, and if any of the bits we
400 // are flipping are known to be set, then the xor is just resetting those
401 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
402 // simplifying both of them.
403 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
404 ConstantInt *AndRHS, *XorRHS;
405 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
406 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
407 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
408 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
409 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
410
411 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
412 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
413 InsertNewInstWith(NewAnd, I->getIterator());
414
415 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
416 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
417 return InsertNewInstWith(NewXor, I->getIterator());
418 }
419 }
420 break;
421 }
422 case Instruction::Select: {
423 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Q, Depth + 1) ||
424 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Q, Depth + 1))
425 return I;
426
427 // If the operands are constants, see if we can simplify them.
428 // This is similar to ShrinkDemandedConstant, but for a select we want to
429 // try to keep the selected constants the same as icmp value constants, if
430 // we can. This helps not break apart (or helps put back together)
431 // canonical patterns like min and max.
432 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
433 const APInt &DemandedMask) {
434 const APInt *SelC;
435 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
436 return false;
437
438 // Get the constant out of the ICmp, if there is one.
439 // Only try this when exactly 1 operand is a constant (if both operands
440 // are constant, the icmp should eventually simplify). Otherwise, we may
441 // invert the transform that reduces set bits and infinite-loop.
442 Value *X;
443 const APInt *CmpC;
444 if (!match(I->getOperand(0), m_ICmp(m_Value(X), m_APInt(CmpC))) ||
445 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
446 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
447
448 // If the constant is already the same as the ICmp, leave it as-is.
449 if (*CmpC == *SelC)
450 return false;
451 // If the constants are not already the same, but can be with the demand
452 // mask, use the constant value from the ICmp.
453 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
454 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
455 return true;
456 }
457 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
458 };
459 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
460 CanonicalizeSelectConstant(I, 2, DemandedMask))
461 return I;
462
463 // Only known if known in both the LHS and RHS.
464 adjustKnownBitsForSelectArm(LHSKnown, I->getOperand(0), I->getOperand(1),
465 /*Invert=*/false, Q, Depth);
466 adjustKnownBitsForSelectArm(RHSKnown, I->getOperand(0), I->getOperand(2),
467 /*Invert=*/true, Q, Depth);
468 Known = LHSKnown.intersectWith(RHSKnown);
469 break;
470 }
471 case Instruction::Trunc: {
472 // If we do not demand the high bits of a right-shifted and truncated value,
473 // then we may be able to truncate it before the shift.
474 Value *X;
475 const APInt *C;
476 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
477 // The shift amount must be valid (not poison) in the narrow type, and
478 // it must not be greater than the high bits demanded of the result.
479 if (C->ult(VTy->getScalarSizeInBits()) &&
480 C->ule(DemandedMask.countl_zero())) {
481 // trunc (lshr X, C) --> lshr (trunc X), C
483 Builder.SetInsertPoint(I);
484 Value *Trunc = Builder.CreateTrunc(X, VTy);
485 return Builder.CreateLShr(Trunc, C->getZExtValue());
486 }
487 }
488 }
489 [[fallthrough]];
490 case Instruction::ZExt: {
491 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
492
493 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
494 KnownBits InputKnown(SrcBitWidth);
495 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Q,
496 Depth + 1)) {
497 // For zext nneg, we may have dropped the instruction which made the
498 // input non-negative.
499 I->dropPoisonGeneratingFlags();
500 return I;
501 }
502 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
503 if (I->getOpcode() == Instruction::ZExt && I->hasNonNeg() &&
504 !InputKnown.isNegative())
505 InputKnown.makeNonNegative();
506 Known = InputKnown.zextOrTrunc(BitWidth);
507
508 break;
509 }
510 case Instruction::SExt: {
511 // Compute the bits in the result that are not present in the input.
512 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
513
514 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
515
516 // If any of the sign extended bits are demanded, we know that the sign
517 // bit is demanded.
518 if (DemandedMask.getActiveBits() > SrcBitWidth)
519 InputDemandedBits.setBit(SrcBitWidth-1);
520
521 KnownBits InputKnown(SrcBitWidth);
522 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Q, Depth + 1))
523 return I;
524
525 // If the input sign bit is known zero, or if the NewBits are not demanded
526 // convert this into a zero extension.
527 if (InputKnown.isNonNegative() ||
528 DemandedMask.getActiveBits() <= SrcBitWidth) {
529 // Convert to ZExt cast.
530 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy);
531 NewCast->takeName(I);
532 return InsertNewInstWith(NewCast, I->getIterator());
533 }
534
535 // If the sign bit of the input is known set or clear, then we know the
536 // top bits of the result.
537 Known = InputKnown.sext(BitWidth);
538 break;
539 }
540 case Instruction::Add: {
541 if ((DemandedMask & 1) == 0) {
542 // If we do not need the low bit, try to convert bool math to logic:
543 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
544 Value *X, *Y;
546 m_OneUse(m_SExt(m_Value(Y))))) &&
547 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
548 // Truth table for inputs and output signbits:
549 // X:0 | X:1
550 // ----------
551 // Y:0 | 0 | 0 |
552 // Y:1 | -1 | 0 |
553 // ----------
555 Builder.SetInsertPoint(I);
556 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
557 return Builder.CreateSExt(AndNot, VTy);
558 }
559
560 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
561 if (match(I, m_Add(m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
562 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
563 (I->getOperand(0)->hasOneUse() || I->getOperand(1)->hasOneUse())) {
564
565 // Truth table for inputs and output signbits:
566 // X:0 | X:1
567 // -----------
568 // Y:0 | 0 | -1 |
569 // Y:1 | -1 | -1 |
570 // -----------
572 Builder.SetInsertPoint(I);
573 Value *Or = Builder.CreateOr(X, Y);
574 return Builder.CreateSExt(Or, VTy);
575 }
576 }
577
578 // Right fill the mask of bits for the operands to demand the most
579 // significant bit and all those below it.
580 unsigned NLZ = DemandedMask.countl_zero();
581 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
582 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
583 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
584 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
585
586 // If low order bits are not demanded and known to be zero in one operand,
587 // then we don't need to demand them from the other operand, since they
588 // can't cause overflow into any bits that are demanded in the result.
589 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
590 APInt DemandedFromLHS = DemandedFromOps;
591 DemandedFromLHS.clearLowBits(NTZ);
592 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
593 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
594 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
595
596 unsigned NtzLHS = (~DemandedMask & LHSKnown.Zero).countr_one();
597 APInt DemandedFromRHS = DemandedFromOps;
598 DemandedFromRHS.clearLowBits(NtzLHS);
599 if (ShrinkDemandedConstant(I, 1, DemandedFromRHS))
600 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
601
602 // If we are known to be adding zeros to every bit below
603 // the highest demanded bit, we just return the other side.
604 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
605 return I->getOperand(0);
606 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
607 return I->getOperand(1);
608
609 // (add X, C) --> (xor X, C) IFF C is equal to the top bit of the DemandMask
610 {
611 const APInt *C;
612 if (match(I->getOperand(1), m_APInt(C)) &&
613 C->isOneBitSet(DemandedMask.getActiveBits() - 1)) {
615 Builder.SetInsertPoint(I);
616 return Builder.CreateXor(I->getOperand(0), ConstantInt::get(VTy, *C));
617 }
618 }
619
620 // Otherwise just compute the known bits of the result.
621 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
622 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
623 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
624 break;
625 }
626 case Instruction::Sub: {
627 // Right fill the mask of bits for the operands to demand the most
628 // significant bit and all those below it.
629 unsigned NLZ = DemandedMask.countl_zero();
630 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
631 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
632 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
633 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
634
635 // If low order bits are not demanded and are known to be zero in RHS,
636 // then we don't need to demand them from LHS, since they can't cause a
637 // borrow from any bits that are demanded in the result.
638 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
639 APInt DemandedFromLHS = DemandedFromOps;
640 DemandedFromLHS.clearLowBits(NTZ);
641 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
642 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
643 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
644
645 // If we are known to be subtracting zeros from every bit below
646 // the highest demanded bit, we just return the other side.
647 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
648 return I->getOperand(0);
649 // We can't do this with the LHS for subtraction, unless we are only
650 // demanding the LSB.
651 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
652 return I->getOperand(1);
653
654 // Canonicalize sub mask, X -> ~X
655 const APInt *LHSC;
656 if (match(I->getOperand(0), m_LowBitMask(LHSC)) &&
657 DemandedFromOps.isSubsetOf(*LHSC)) {
659 Builder.SetInsertPoint(I);
660 return Builder.CreateNot(I->getOperand(1));
661 }
662
663 // Otherwise just compute the known bits of the result.
664 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
665 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
666 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
667 break;
668 }
669 case Instruction::Mul: {
670 APInt DemandedFromOps;
671 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
672 return I;
673
674 if (DemandedMask.isPowerOf2()) {
675 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
676 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
677 // odd (has LSB set), then the left-shifted low bit of X is the answer.
678 unsigned CTZ = DemandedMask.countr_zero();
679 const APInt *C;
680 if (match(I->getOperand(1), m_APInt(C)) && C->countr_zero() == CTZ) {
681 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
682 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
683 return InsertNewInstWith(Shl, I->getIterator());
684 }
685 }
686 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
687 // X * X is odd iff X is odd.
688 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
689 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
690 Constant *One = ConstantInt::get(VTy, 1);
691 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
692 return InsertNewInstWith(And1, I->getIterator());
693 }
694
696 break;
697 }
698 case Instruction::Shl: {
699 const APInt *SA;
700 if (match(I->getOperand(1), m_APInt(SA))) {
701 const APInt *ShrAmt;
702 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
703 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
704 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
705 DemandedMask, Known))
706 return R;
707
708 // Do not simplify if shl is part of funnel-shift pattern
709 if (I->hasOneUse()) {
710 Instruction *Inst = I->user_back();
711 if (Inst->getOpcode() == BinaryOperator::Or) {
712 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
713 auto [IID, FShiftArgs] = *Opt;
714 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
715 FShiftArgs[0] == FShiftArgs[1]) {
717 break;
718 }
719 }
720 }
721 }
722
723 // We only want bits that already match the signbit then we don't
724 // need to shift.
725 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth - 1);
726 if (DemandedMask.countr_zero() >= ShiftAmt) {
727 if (I->hasNoSignedWrap()) {
728 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
729 unsigned SignBits =
730 ComputeNumSignBits(I->getOperand(0), Q.CtxI, Depth + 1);
731 if (SignBits > ShiftAmt && SignBits - ShiftAmt >= NumHiDemandedBits)
732 return I->getOperand(0);
733 }
734
735 // If we can pre-shift a right-shifted constant to the left without
736 // losing any high bits and we don't demand the low bits, then eliminate
737 // the left-shift:
738 // (C >> X) << LeftShiftAmtC --> (C << LeftShiftAmtC) >> X
739 Value *X;
740 Constant *C;
741 if (match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
742 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
743 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::Shl, C,
744 LeftShiftAmtC, DL);
745 if (ConstantFoldBinaryOpOperands(Instruction::LShr, NewC,
746 LeftShiftAmtC, DL) == C) {
747 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
748 return InsertNewInstWith(Lshr, I->getIterator());
749 }
750 }
751 }
752
753 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
754
755 // If the shift is NUW/NSW, then it does demand the high bits.
757 if (IOp->hasNoSignedWrap())
758 DemandedMaskIn.setHighBits(ShiftAmt+1);
759 else if (IOp->hasNoUnsignedWrap())
760 DemandedMaskIn.setHighBits(ShiftAmt);
761
762 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1))
763 return I;
764
767 /* NUW */ IOp->hasNoUnsignedWrap(),
768 /* NSW */ IOp->hasNoSignedWrap());
769 } else {
770 // This is a variable shift, so we can't shift the demand mask by a known
771 // amount. But if we are not demanding high bits, then we are not
772 // demanding those bits from the pre-shifted operand either.
773 if (unsigned CTLZ = DemandedMask.countl_zero()) {
774 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
775 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Q, Depth + 1)) {
776 // We can't guarantee that nsw/nuw hold after simplifying the operand.
777 I->dropPoisonGeneratingFlags();
778 return I;
779 }
780 }
782 }
783 break;
784 }
785 case Instruction::LShr: {
786 const APInt *SA;
787 if (match(I->getOperand(1), m_APInt(SA))) {
788 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
789
790 // Do not simplify if lshr is part of funnel-shift pattern
791 if (I->hasOneUse()) {
792 Instruction *Inst = I->user_back();
793 if (Inst->getOpcode() == BinaryOperator::Or) {
794 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
795 auto [IID, FShiftArgs] = *Opt;
796 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
797 FShiftArgs[0] == FShiftArgs[1]) {
799 break;
800 }
801 }
802 }
803 }
804
805 // If we are just demanding the shifted sign bit and below, then this can
806 // be treated as an ASHR in disguise.
807 if (DemandedMask.countl_zero() >= ShiftAmt) {
808 // If we only want bits that already match the signbit then we don't
809 // need to shift.
810 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
811 unsigned SignBits =
812 ComputeNumSignBits(I->getOperand(0), Q.CtxI, Depth + 1);
813 if (SignBits >= NumHiDemandedBits)
814 return I->getOperand(0);
815
816 // If we can pre-shift a left-shifted constant to the right without
817 // losing any low bits (we already know we don't demand the high bits),
818 // then eliminate the right-shift:
819 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
820 Value *X;
821 Constant *C;
822 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
823 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
824 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::LShr, C,
825 RightShiftAmtC, DL);
826 if (ConstantFoldBinaryOpOperands(Instruction::Shl, NewC,
827 RightShiftAmtC, DL) == C) {
828 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
829 return InsertNewInstWith(Shl, I->getIterator());
830 }
831 }
832
833 const APInt *Factor;
834 if (match(I->getOperand(0),
835 m_OneUse(m_Mul(m_Value(X), m_APInt(Factor)))) &&
836 Factor->countr_zero() >= ShiftAmt) {
837 BinaryOperator *Mul = BinaryOperator::CreateMul(
838 X, ConstantInt::get(X->getType(), Factor->lshr(ShiftAmt)));
839 return InsertNewInstWith(Mul, I->getIterator());
840 }
841 }
842
843 // Unsigned shift right.
844 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
845 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
846 // exact flag may not longer hold.
847 I->dropPoisonGeneratingFlags();
848 return I;
849 }
850 Known >>= ShiftAmt;
851 if (ShiftAmt)
852 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
853 break;
854 }
855 if (Value *V =
856 simplifyShiftSelectingPackedElement(I, DemandedMask, *this, Depth))
857 return V;
858
860 break;
861 }
862 case Instruction::AShr: {
863 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Q.CtxI, Depth + 1);
864
865 // If we only want bits that already match the signbit then we don't need
866 // to shift.
867 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
868 if (SignBits >= NumHiDemandedBits)
869 return I->getOperand(0);
870
871 // If this is an arithmetic shift right and only the low-bit is set, we can
872 // always convert this into a logical shr, even if the shift amount is
873 // variable. The low bit of the shift cannot be an input sign bit unless
874 // the shift amount is >= the size of the datatype, which is undefined.
875 if (DemandedMask.isOne()) {
876 // Perform the logical shift right.
877 Instruction *NewVal = BinaryOperator::CreateLShr(
878 I->getOperand(0), I->getOperand(1), I->getName());
879 return InsertNewInstWith(NewVal, I->getIterator());
880 }
881
882 const APInt *SA;
883 if (match(I->getOperand(1), m_APInt(SA))) {
884 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
885
886 // Signed shift right.
887 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
888 // If any of the bits being shifted in are demanded, then we should set
889 // the sign bit as demanded.
890 bool ShiftedInBitsDemanded = DemandedMask.countl_zero() < ShiftAmt;
891 if (ShiftedInBitsDemanded)
892 DemandedMaskIn.setSignBit();
893 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
894 // exact flag may not longer hold.
895 I->dropPoisonGeneratingFlags();
896 return I;
897 }
898
899 // If the input sign bit is known to be zero, or if none of the shifted in
900 // bits are demanded, turn this into an unsigned shift right.
901 if (Known.Zero[BitWidth - 1] || !ShiftedInBitsDemanded) {
902 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
903 I->getOperand(1));
904 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
905 LShr->takeName(I);
906 return InsertNewInstWith(LShr, I->getIterator());
907 }
908
911 ShiftAmt != 0, I->isExact());
912 } else {
914 }
915 break;
916 }
917 case Instruction::UDiv: {
918 // UDiv doesn't demand low bits that are zero in the divisor.
919 const APInt *SA;
920 if (match(I->getOperand(1), m_APInt(SA))) {
921 // TODO: Take the demanded mask of the result into account.
922 unsigned RHSTrailingZeros = SA->countr_zero();
923 APInt DemandedMaskIn =
924 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
925 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Q, Depth + 1)) {
926 // We can't guarantee that "exact" is still true after changing the
927 // the dividend.
928 I->dropPoisonGeneratingFlags();
929 return I;
930 }
931
933 cast<BinaryOperator>(I)->isExact());
934 } else {
936 }
937 break;
938 }
939 case Instruction::SRem: {
940 const APInt *Rem;
941 if (match(I->getOperand(1), m_APInt(Rem)) && Rem->isPowerOf2()) {
942 if (DemandedMask.ult(*Rem)) // srem won't affect demanded bits
943 return I->getOperand(0);
944
945 APInt LowBits = *Rem - 1;
946 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
947 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Q, Depth + 1))
948 return I;
950 break;
951 }
952
954 break;
955 }
956 case Instruction::Call: {
957 bool KnownBitsComputed = false;
959 switch (II->getIntrinsicID()) {
960 case Intrinsic::abs: {
961 if (DemandedMask == 1)
962 return II->getArgOperand(0);
963 break;
964 }
965 case Intrinsic::ctpop: {
966 // Checking if the number of clear bits is odd (parity)? If the type has
967 // an even number of bits, that's the same as checking if the number of
968 // set bits is odd, so we can eliminate the 'not' op.
969 Value *X;
970 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
971 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
973 II->getModule(), Intrinsic::ctpop, VTy);
974 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), I->getIterator());
975 }
976 break;
977 }
978 case Intrinsic::bswap: {
979 // If the only bits demanded come from one byte of the bswap result,
980 // just shift the input byte into position to eliminate the bswap.
981 unsigned NLZ = DemandedMask.countl_zero();
982 unsigned NTZ = DemandedMask.countr_zero();
983
984 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
985 // we need all the bits down to bit 8. Likewise, round NLZ. If we
986 // have 14 leading zeros, round to 8.
987 NLZ = alignDown(NLZ, 8);
988 NTZ = alignDown(NTZ, 8);
989 // If we need exactly one byte, we can do this transformation.
990 if (BitWidth - NLZ - NTZ == 8) {
991 // Replace this with either a left or right shift to get the byte into
992 // the right place.
993 Instruction *NewVal;
994 if (NLZ > NTZ)
995 NewVal = BinaryOperator::CreateLShr(
996 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
997 else
998 NewVal = BinaryOperator::CreateShl(
999 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
1000 NewVal->takeName(I);
1001 return InsertNewInstWith(NewVal, I->getIterator());
1002 }
1003 break;
1004 }
1005 case Intrinsic::ptrmask: {
1006 unsigned MaskWidth = I->getOperand(1)->getType()->getScalarSizeInBits();
1007 RHSKnown = KnownBits(MaskWidth);
1008 // If either the LHS or the RHS are Zero, the result is zero.
1009 if (SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1) ||
1011 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
1012 RHSKnown, Q, Depth + 1))
1013 return I;
1014
1015 // TODO: Should be 1-extend
1016 RHSKnown = RHSKnown.anyextOrTrunc(BitWidth);
1017
1018 Known = LHSKnown & RHSKnown;
1019 KnownBitsComputed = true;
1020
1021 // If the client is only demanding bits we know to be zero, return
1022 // `llvm.ptrmask(p, 0)`. We can't return `null` here due to pointer
1023 // provenance, but making the mask zero will be easily optimizable in
1024 // the backend.
1025 if (DemandedMask.isSubsetOf(Known.Zero) &&
1026 !match(I->getOperand(1), m_Zero()))
1027 return replaceOperand(
1028 *I, 1, Constant::getNullValue(I->getOperand(1)->getType()));
1029
1030 // Mask in demanded space does nothing.
1031 // NOTE: We may have attributes associated with the return value of the
1032 // llvm.ptrmask intrinsic that will be lost when we just return the
1033 // operand. We should try to preserve them.
1034 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1035 return I->getOperand(0);
1036
1037 // If the RHS is a constant, see if we can simplify it.
1039 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
1040 return I;
1041
1042 // Combine:
1043 // (ptrmask (getelementptr i8, ptr p, imm i), imm mask)
1044 // -> (ptrmask (getelementptr i8, ptr p, imm (i & mask)), imm mask)
1045 // where only the low bits known to be zero in the pointer are changed
1046 Value *InnerPtr;
1047 uint64_t GEPIndex;
1048 uint64_t PtrMaskImmediate;
1049 if (match(I,
1051 m_PtrAdd(DL, m_Value(InnerPtr), m_ConstantInt(GEPIndex)),
1052 m_ConstantInt(PtrMaskImmediate)))) {
1053
1054 LHSKnown = computeKnownBits(InnerPtr, I, Depth + 1);
1055 if (!LHSKnown.isZero()) {
1056 const unsigned trailingZeros = LHSKnown.countMinTrailingZeros();
1057 uint64_t PointerAlignBits = (uint64_t(1) << trailingZeros) - 1;
1058
1059 uint64_t HighBitsGEPIndex = GEPIndex & ~PointerAlignBits;
1060 uint64_t MaskedLowBitsGEPIndex =
1061 GEPIndex & PointerAlignBits & PtrMaskImmediate;
1062
1063 uint64_t MaskedGEPIndex = HighBitsGEPIndex | MaskedLowBitsGEPIndex;
1064
1065 if (MaskedGEPIndex != GEPIndex) {
1066 auto *GEP = cast<GEPOperator>(II->getArgOperand(0));
1067 Builder.SetInsertPoint(I);
1068 Type *GEPIndexType =
1069 DL.getIndexType(GEP->getPointerOperand()->getType());
1070 Value *MaskedGEP = Builder.CreateGEP(
1071 GEP->getSourceElementType(), InnerPtr,
1072 ConstantInt::get(GEPIndexType, MaskedGEPIndex),
1073 GEP->getName(), GEP->isInBounds());
1074
1075 replaceOperand(*I, 0, MaskedGEP);
1076 return I;
1077 }
1078 }
1079 }
1080
1081 break;
1082 }
1083
1084 case Intrinsic::fshr:
1085 case Intrinsic::fshl: {
1086 const APInt *SA;
1087 if (!match(I->getOperand(2), m_APInt(SA)))
1088 break;
1089
1090 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
1091 // defined, so no need to special-case zero shifts here.
1092 uint64_t ShiftAmt = SA->urem(BitWidth);
1093 if (II->getIntrinsicID() == Intrinsic::fshr)
1094 ShiftAmt = BitWidth - ShiftAmt;
1095
1096 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
1097 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
1098 if (I->getOperand(0) != I->getOperand(1)) {
1099 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Q,
1100 Depth + 1) ||
1101 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Q,
1102 Depth + 1)) {
1103 // Range attribute or metadata may no longer hold.
1104 I->dropPoisonGeneratingAnnotations();
1105 return I;
1106 }
1107 } else { // fshl is a rotate
1108 // Avoid converting rotate into funnel shift.
1109 // Only simplify if one operand is constant.
1110 LHSKnown = computeKnownBits(I->getOperand(0), I, Depth + 1);
1111 if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
1112 !match(I->getOperand(0), m_SpecificInt(LHSKnown.One))) {
1113 replaceOperand(*I, 0, Constant::getIntegerValue(VTy, LHSKnown.One));
1114 // Range attribute or metadata may no longer hold.
1115 I->dropPoisonGeneratingAnnotations();
1116 return I;
1117 }
1118
1119 RHSKnown = computeKnownBits(I->getOperand(1), I, Depth + 1);
1120 if (DemandedMaskRHS.isSubsetOf(RHSKnown.Zero | RHSKnown.One) &&
1121 !match(I->getOperand(1), m_SpecificInt(RHSKnown.One))) {
1122 replaceOperand(*I, 1, Constant::getIntegerValue(VTy, RHSKnown.One));
1123 // Range attribute or metadata may no longer hold.
1124 I->dropPoisonGeneratingAnnotations();
1125 return I;
1126 }
1127 }
1128
1129 LHSKnown <<= ShiftAmt;
1130 RHSKnown >>= BitWidth - ShiftAmt;
1131 Known = LHSKnown.unionWith(RHSKnown);
1132 KnownBitsComputed = true;
1133 break;
1134 }
1135 case Intrinsic::umax: {
1136 // UMax(A, C) == A if ...
1137 // The lowest non-zero bit of DemandMask is higher than the highest
1138 // non-zero bit of C.
1139 const APInt *C;
1140 unsigned CTZ = DemandedMask.countr_zero();
1141 if (match(II->getArgOperand(1), m_APInt(C)) &&
1142 CTZ >= C->getActiveBits())
1143 return II->getArgOperand(0);
1144 break;
1145 }
1146 case Intrinsic::umin: {
1147 // UMin(A, C) == A if ...
1148 // The lowest non-zero bit of DemandMask is higher than the highest
1149 // non-one bit of C.
1150 // This comes from using DeMorgans on the above umax example.
1151 const APInt *C;
1152 unsigned CTZ = DemandedMask.countr_zero();
1153 if (match(II->getArgOperand(1), m_APInt(C)) &&
1154 CTZ >= C->getBitWidth() - C->countl_one())
1155 return II->getArgOperand(0);
1156 break;
1157 }
1158 default: {
1159 // Handle target specific intrinsics
1160 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
1161 *II, DemandedMask, Known, KnownBitsComputed);
1162 if (V)
1163 return *V;
1164 break;
1165 }
1166 }
1167 }
1168
1169 if (!KnownBitsComputed)
1171 break;
1172 }
1173 }
1174
1175 if (I->getType()->isPointerTy()) {
1176 Align Alignment = I->getPointerAlignment(DL);
1177 Known.Zero.setLowBits(Log2(Alignment));
1178 }
1179
1180 // If the client is only demanding bits that we know, return the known
1181 // constant. We can't directly simplify pointers as a constant because of
1182 // pointer provenance.
1183 // TODO: We could return `(inttoptr const)` for pointers.
1184 if (!I->getType()->isPointerTy() &&
1185 DemandedMask.isSubsetOf(Known.Zero | Known.One))
1186 return Constant::getIntegerValue(VTy, Known.One);
1187
1188 if (CLOpts.verify_known_bits) {
1189 KnownBits ReferenceKnown = llvm::computeKnownBits(I, Q, Depth);
1190 if (Known != ReferenceKnown) {
1191 errs() << "Mismatched known bits for " << *I << " in "
1192 << I->getFunction()->getName() << "\n";
1193 errs() << "computeKnownBits(): " << ReferenceKnown << "\n";
1194 errs() << "SimplifyDemandedBits(): " << Known << "\n";
1195 std::abort();
1196 }
1197 }
1198
1199 return nullptr;
1200}
1201
1202/// Helper routine of SimplifyDemandedUseBits. It computes Known
1203/// bits. It also tries to handle simplifications that can be done based on
1204/// DemandedMask, but without modifying the Instruction.
1206 Instruction *I, const APInt &DemandedMask, KnownBits &Known,
1207 const SimplifyQuery &Q, unsigned Depth) {
1208 unsigned BitWidth = DemandedMask.getBitWidth();
1209 Type *ITy = I->getType();
1210
1211 KnownBits LHSKnown(BitWidth);
1212 KnownBits RHSKnown(BitWidth);
1213
1214 // Despite the fact that we can't simplify this instruction in all User's
1215 // context, we can at least compute the known bits, and we can
1216 // do simplifications that apply to *just* the one user if we know that
1217 // this instruction has a simpler value in that context.
1218 switch (I->getOpcode()) {
1219 case Instruction::And: {
1220 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1221 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1222 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1223 Q, Depth);
1225
1226 // If the client is only demanding bits that we know, return the known
1227 // constant.
1228 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1229 return Constant::getIntegerValue(ITy, Known.One);
1230
1231 // If all of the demanded bits are known 1 on one side, return the other.
1232 // These bits cannot contribute to the result of the 'and' in this context.
1233 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1234 return I->getOperand(0);
1235 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1236 return I->getOperand(1);
1237
1238 break;
1239 }
1240 case Instruction::Or: {
1241 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1242 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1243 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1244 Q, Depth);
1246
1247 // If the client is only demanding bits that we know, return the known
1248 // constant.
1249 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1250 return Constant::getIntegerValue(ITy, Known.One);
1251
1252 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1253 // only bits from X or Y are demanded.
1254 // If all of the demanded bits are known zero on one side, return the other.
1255 // These bits cannot contribute to the result of the 'or' in this context.
1256 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1257 return I->getOperand(0);
1258 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1259 return I->getOperand(1);
1260
1261 break;
1262 }
1263 case Instruction::Xor: {
1264 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1265 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1266 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1267 Q, Depth);
1269
1270 // If the client is only demanding bits that we know, return the known
1271 // constant.
1272 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1273 return Constant::getIntegerValue(ITy, Known.One);
1274
1275 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1276 // only bits from X or Y are demanded.
1277 // If all of the demanded bits are known zero on one side, return the other.
1278 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1279 return I->getOperand(0);
1280 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1281 return I->getOperand(1);
1282
1283 break;
1284 }
1285 case Instruction::Add: {
1286 unsigned NLZ = DemandedMask.countl_zero();
1287 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1288
1289 // If an operand adds zeros to every bit below the highest demanded bit,
1290 // that operand doesn't change the result. Return the other side.
1291 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1292 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1293 return I->getOperand(0);
1294
1295 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1296 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1297 return I->getOperand(1);
1298
1299 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1300 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1301 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
1303 break;
1304 }
1305 case Instruction::Sub: {
1306 unsigned NLZ = DemandedMask.countl_zero();
1307 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1308
1309 // If an operand subtracts zeros from every bit below the highest demanded
1310 // bit, that operand doesn't change the result. Return the other side.
1311 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1312 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1313 return I->getOperand(0);
1314
1315 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1316 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1317 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1318 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
1320 break;
1321 }
1322 case Instruction::AShr: {
1323 // Compute the Known bits to simplify things downstream.
1325
1326 // If this user is only demanding bits that we know, return the known
1327 // constant.
1328 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1329 return Constant::getIntegerValue(ITy, Known.One);
1330
1331 // If the right shift operand 0 is a result of a left shift by the same
1332 // amount, this is probably a zero/sign extension, which may be unnecessary,
1333 // if we do not demand any of the new sign bits. So, return the original
1334 // operand instead.
1335 const APInt *ShiftRC;
1336 const APInt *ShiftLC;
1337 Value *X;
1338 unsigned BitWidth = DemandedMask.getBitWidth();
1339 if (match(I,
1340 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1341 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1342 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1343 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1344 return X;
1345 }
1346
1347 break;
1348 }
1349 default:
1350 // Compute the Known bits to simplify things downstream.
1352
1353 // If this user is only demanding bits that we know, return the known
1354 // constant.
1355 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1356 return Constant::getIntegerValue(ITy, Known.One);
1357
1358 break;
1359 }
1360
1361 return nullptr;
1362}
1363
1364/// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1365/// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1366/// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1367/// of "C2-C1".
1368///
1369/// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1370/// ..., bn}, without considering the specific value X is holding.
1371/// This transformation is legal iff one of following conditions is hold:
1372/// 1) All the bit in S are 0, in this case E1 == E2.
1373/// 2) We don't care those bits in S, per the input DemandedMask.
1374/// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1375/// rest bits.
1376///
1377/// Currently we only test condition 2).
1378///
1379/// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1380/// not successful.
1382 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1383 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1384 if (!ShlOp1 || !ShrOp1)
1385 return nullptr; // No-op.
1386
1387 Value *VarX = Shr->getOperand(0);
1388 Type *Ty = VarX->getType();
1389 unsigned BitWidth = Ty->getScalarSizeInBits();
1390 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1391 return nullptr; // Undef.
1392
1393 unsigned ShlAmt = ShlOp1.getZExtValue();
1394 unsigned ShrAmt = ShrOp1.getZExtValue();
1395
1396 Known.One.clearAllBits();
1397 Known.Zero.setLowBits(ShlAmt - 1);
1398 Known.Zero &= DemandedMask;
1399
1400 APInt BitMask1(APInt::getAllOnes(BitWidth));
1401 APInt BitMask2(APInt::getAllOnes(BitWidth));
1402
1403 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1404 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1405 (BitMask1.ashr(ShrAmt) << ShlAmt);
1406
1407 if (ShrAmt <= ShlAmt) {
1408 BitMask2 <<= (ShlAmt - ShrAmt);
1409 } else {
1410 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1411 BitMask2.ashr(ShrAmt - ShlAmt);
1412 }
1413
1414 // Check if condition-2 (see the comment to this function) is satified.
1415 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1416 if (ShrAmt == ShlAmt)
1417 return VarX;
1418
1419 if (!Shr->hasOneUse())
1420 return nullptr;
1421
1422 BinaryOperator *New;
1423 if (ShrAmt < ShlAmt) {
1424 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1425 New = BinaryOperator::CreateShl(VarX, Amt);
1427 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1428 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1429 } else {
1430 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1431 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1432 BinaryOperator::CreateAShr(VarX, Amt);
1433 if (cast<BinaryOperator>(Shr)->isExact())
1434 New->setIsExact(true);
1435 }
1436
1437 return InsertNewInstWith(New, Shl->getIterator());
1438 }
1439
1440 return nullptr;
1441}
1442
1443/// Return true if the top-level all-lanes demanded-elements query can be
1444/// skipped for an intermediate insertelement chain node. This is limited to a
1445/// bounded one-use chain with distinct in-range constant indices, where SDVE
1446/// cannot remove a dead insert before hitting its depth limit.
1448 unsigned VWidth,
1449 unsigned DepthLimit) {
1450 // Only skip chain nodes that feed another insertelement; the final chain root
1451 // still runs the full query.
1452 if (!IE.hasOneUse())
1453 return false;
1454 auto *UserIE = dyn_cast<InsertElementInst>(IE.user_back());
1455 if (!UserIE || UserIE->getOperand(0) != &IE)
1456 return false;
1457
1458 SmallBitVector SeenIndices(VWidth);
1459 auto HasNewIndexInRange = [&](InsertElementInst &Insert) {
1460 auto *Idx = dyn_cast<ConstantInt>(Insert.getOperand(2));
1461 // Let the normal SDVE path handle variable or out-of-range indices. The
1462 // latter may simplify the chain and must not be passed to getZExtValue().
1463 if (!Idx || Idx->getValue().uge(VWidth))
1464 return false;
1465
1466 unsigned Index = Idx->getZExtValue();
1467 if (SeenIndices.test(Index))
1468 return false;
1469
1470 SeenIndices.set(Index);
1471 return true;
1472 };
1473
1474 auto *Cur = &IE;
1475 for (unsigned I = 0; I != DepthLimit; ++I) {
1476 // This loop scans the same base-chain window that the SDVE query would
1477 // inspect before hitting its depth limit. With distinct insert indices in
1478 // that window, the all-lanes query cannot remove a dead insert; with
1479 // VWidth > DepthLimit, it also cannot narrow demand to a single lane.
1480 if (!HasNewIndexInRange(*Cur))
1481 return false;
1482
1483 Value *Base = Cur->getOperand(0);
1484 if (match(Base, m_Poison()))
1485 return true;
1486
1488 if (!Cur || !Cur->hasOneUse())
1489 return false;
1490 }
1491
1492 return true;
1493}
1494
1495/// The specified value produces a vector with any number of elements.
1496/// This method analyzes which elements of the operand are poison and
1497/// returns that information in PoisonElts.
1498///
1499/// DemandedElts contains the set of elements that are actually used by the
1500/// caller, and by default (AllowMultipleUsers equals false) the value is
1501/// simplified only if it has a single caller. If AllowMultipleUsers is set
1502/// to true, DemandedElts refers to the union of sets of elements that are
1503/// used by all callers.
1504///
1505/// If the information about demanded elements can be used to simplify the
1506/// operation, the operation is simplified, then the resultant value is
1507/// returned. This returns null if no change was made.
1509 APInt DemandedElts,
1510 APInt &PoisonElts,
1511 unsigned Depth,
1512 bool AllowMultipleUsers) {
1513 // Cannot analyze scalable type. The number of vector elements is not a
1514 // compile-time constant.
1515 if (isa<ScalableVectorType>(V->getType()))
1516 return nullptr;
1517
1518 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1519 APInt EltMask(APInt::getAllOnes(VWidth));
1520 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1521
1522 if (match(V, m_Poison())) {
1523 // If the entire vector is poison, just return this info.
1524 PoisonElts = EltMask;
1525 return nullptr;
1526 }
1527
1528 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1529 PoisonElts = EltMask;
1530 return PoisonValue::get(V->getType());
1531 }
1532
1533 PoisonElts = 0;
1534
1535 if (auto *C = dyn_cast<Constant>(V)) {
1536 // Check if this is identity. If so, return 0 since we are not simplifying
1537 // anything.
1538 if (DemandedElts.isAllOnes())
1539 return nullptr;
1540
1541 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1542 Constant *Poison = PoisonValue::get(EltTy);
1544 for (unsigned i = 0; i != VWidth; ++i) {
1545 if (!DemandedElts[i]) { // If not demanded, set to poison.
1546 Elts.push_back(Poison);
1547 PoisonElts.setBit(i);
1548 continue;
1549 }
1550
1551 Constant *Elt = C->getAggregateElement(i);
1552 if (!Elt) return nullptr;
1553
1554 Elts.push_back(Elt);
1555 if (isa<PoisonValue>(Elt)) // Already poison.
1556 PoisonElts.setBit(i);
1557 }
1558
1559 // If we changed the constant, return it.
1560 Constant *NewCV = ConstantVector::get(Elts);
1561 return NewCV != C ? NewCV : nullptr;
1562 }
1563
1564 // Limit search depth.
1565 if (Depth == CLOpts.simplify_vector_elts_depth)
1566 return nullptr;
1567
1568 if (!AllowMultipleUsers) {
1569 // If multiple users are using the root value, proceed with
1570 // simplification conservatively assuming that all elements
1571 // are needed.
1572 if (!V->hasOneUse()) {
1573 // Quit if we find multiple users of a non-root value though.
1574 // They'll be handled when it's their turn to be visited by
1575 // the main instcombine process.
1576 if (Depth != 0)
1577 // TODO: Just compute the PoisonElts information recursively.
1578 return nullptr;
1579
1580 // Conservatively assume that all elements are needed.
1581 DemandedElts = EltMask;
1582 }
1583 }
1584
1586 if (!I) return nullptr; // Only analyze instructions.
1587
1588 bool MadeChange = false;
1589 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1590 APInt Demanded, APInt &Undef) {
1591 auto *II = dyn_cast<IntrinsicInst>(Inst);
1592 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1593 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1594 replaceOperand(*Inst, OpNum, V);
1595 MadeChange = true;
1596 }
1597 };
1598
1599 APInt PoisonElts2(VWidth, 0);
1600 APInt PoisonElts3(VWidth, 0);
1601 switch (I->getOpcode()) {
1602 default: break;
1603
1604 case Instruction::GetElementPtr: {
1605 // The LangRef requires that struct geps have all constant indices. As
1606 // such, we can't convert any operand to partial undef.
1607 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1608 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1609 I != E; I++)
1610 if (I.isStruct())
1611 return true;
1612 return false;
1613 };
1614 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1615 break;
1616
1617 // Conservatively track the demanded elements back through any vector
1618 // operands we may have. We know there must be at least one, or we
1619 // wouldn't have a vector result to get here. Note that we intentionally
1620 // merge the undef bits here since gepping with either an poison base or
1621 // index results in poison.
1622 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1623 if (i == 0 ? match(I->getOperand(i), m_Undef())
1624 : match(I->getOperand(i), m_Poison())) {
1625 // If the entire vector is undefined, just return this info.
1626 PoisonElts = EltMask;
1627 return nullptr;
1628 }
1629 if (I->getOperand(i)->getType()->isVectorTy()) {
1630 APInt PoisonEltsOp(VWidth, 0);
1631 simplifyAndSetOp(I, i, DemandedElts, PoisonEltsOp);
1632 // gep(x, undef) is not undef, so skip considering idx ops here
1633 // Note that we could propagate poison, but we can't distinguish between
1634 // undef & poison bits ATM
1635 if (i == 0)
1636 PoisonElts |= PoisonEltsOp;
1637 }
1638 }
1639
1640 break;
1641 }
1642 case Instruction::InsertElement: {
1643 unsigned DepthLimit = CLOpts.simplify_vector_elts_depth;
1644 auto *IE = cast<InsertElementInst>(I);
1645 // Skip only when SDVE cannot simplify this insert chain before the limit.
1646 if (Depth == 0 && DemandedElts.isAllOnes() && VWidth > DepthLimit &&
1647 canSkipDemandedEltsInInsertChain(*IE, VWidth, DepthLimit))
1648 return nullptr;
1649
1650 // If this is a variable index, we don't know which element it overwrites.
1651 // demand exactly the same input as we produce.
1652 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1653 if (!Idx) {
1654 // Note that we can't propagate undef elt info, because we don't know
1655 // which elt is getting updated.
1656 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts2);
1657 break;
1658 }
1659
1660 // The element inserted overwrites whatever was there, so the input demanded
1661 // set is simpler than the output set.
1662 unsigned IdxNo = Idx->getZExtValue();
1663 APInt PreInsertDemandedElts = DemandedElts;
1664 if (IdxNo < VWidth)
1665 PreInsertDemandedElts.clearBit(IdxNo);
1666
1667 // If we only demand the element that is being inserted and that element
1668 // was extracted from the same index in another vector with the same type,
1669 // replace this insert with that other vector.
1670 // Note: This is attempted before the call to simplifyAndSetOp because that
1671 // may change PoisonElts to a value that does not match with Vec.
1672 Value *Vec;
1673 if (PreInsertDemandedElts == 0 &&
1674 match(I->getOperand(1),
1675 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1676 Vec->getType() == I->getType()) {
1677 return Vec;
1678 }
1679
1680 simplifyAndSetOp(I, 0, PreInsertDemandedElts, PoisonElts);
1681
1682 // If this is inserting an element that isn't demanded, remove this
1683 // insertelement.
1684 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1685 Worklist.push(I);
1686 return I->getOperand(0);
1687 }
1688
1689 // The inserted element is defined.
1690 PoisonElts.clearBit(IdxNo);
1691 break;
1692 }
1693 case Instruction::ShuffleVector: {
1694 auto *Shuffle = cast<ShuffleVectorInst>(I);
1695 assert(Shuffle->getOperand(0)->getType() ==
1696 Shuffle->getOperand(1)->getType() &&
1697 "Expected shuffle operands to have same type");
1698 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1699 ->getNumElements();
1700 // Handle trivial case of a splat. Only check the first element of LHS
1701 // operand.
1702 if (all_of(Shuffle->getShuffleMask(), equal_to(0)) &&
1703 DemandedElts.isAllOnes()) {
1704 if (!isa<PoisonValue>(I->getOperand(1))) {
1705 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1706 MadeChange = true;
1707 }
1708 APInt LeftDemanded(OpWidth, 1);
1709 APInt LHSPoisonElts(OpWidth, 0);
1710 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1711 if (LHSPoisonElts[0])
1712 PoisonElts = EltMask;
1713 else
1714 PoisonElts.clearAllBits();
1715 break;
1716 }
1717
1718 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1719 for (unsigned i = 0; i < VWidth; i++) {
1720 if (DemandedElts[i]) {
1721 unsigned MaskVal = Shuffle->getMaskValue(i);
1722 if (MaskVal != -1u) {
1723 assert(MaskVal < OpWidth * 2 &&
1724 "shufflevector mask index out of range!");
1725 if (MaskVal < OpWidth)
1726 LeftDemanded.setBit(MaskVal);
1727 else
1728 RightDemanded.setBit(MaskVal - OpWidth);
1729 }
1730 }
1731 }
1732
1733 APInt LHSPoisonElts(OpWidth, 0);
1734 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1735
1736 APInt RHSPoisonElts(OpWidth, 0);
1737 simplifyAndSetOp(I, 1, RightDemanded, RHSPoisonElts);
1738
1739 // If this shuffle does not change the vector length and the elements
1740 // demanded by this shuffle are an identity mask, then this shuffle is
1741 // unnecessary.
1742 //
1743 // We are assuming canonical form for the mask, so the source vector is
1744 // operand 0 and operand 1 is not used.
1745 //
1746 // Note that if an element is demanded and this shuffle mask is undefined
1747 // for that element, then the shuffle is not considered an identity
1748 // operation. The shuffle prevents poison from the operand vector from
1749 // leaking to the result by replacing poison with an undefined value.
1750 if (VWidth == OpWidth) {
1751 bool IsIdentityShuffle = true;
1752 for (unsigned i = 0; i < VWidth; i++) {
1753 unsigned MaskVal = Shuffle->getMaskValue(i);
1754 if (DemandedElts[i] && i != MaskVal) {
1755 IsIdentityShuffle = false;
1756 break;
1757 }
1758 }
1759 if (IsIdentityShuffle)
1760 return Shuffle->getOperand(0);
1761 }
1762
1763 bool NewPoisonElts = false;
1764 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1765 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1766 bool LHSUniform = true;
1767 bool RHSUniform = true;
1768 for (unsigned i = 0; i < VWidth; i++) {
1769 unsigned MaskVal = Shuffle->getMaskValue(i);
1770 if (MaskVal == -1u) {
1771 PoisonElts.setBit(i);
1772 } else if (!DemandedElts[i]) {
1773 NewPoisonElts = true;
1774 PoisonElts.setBit(i);
1775 } else if (MaskVal < OpWidth) {
1776 if (LHSPoisonElts[MaskVal]) {
1777 NewPoisonElts = true;
1778 PoisonElts.setBit(i);
1779 } else {
1780 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1781 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1782 LHSUniform = LHSUniform && (MaskVal == i);
1783 }
1784 } else {
1785 if (RHSPoisonElts[MaskVal - OpWidth]) {
1786 NewPoisonElts = true;
1787 PoisonElts.setBit(i);
1788 } else {
1789 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1790 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1791 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1792 }
1793 }
1794 }
1795
1796 // Try to transform shuffle with constant vector and single element from
1797 // this constant vector to single insertelement instruction.
1798 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1799 // insertelement V, C[ci], ci-n
1800 if (OpWidth ==
1801 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1802 Value *Op = nullptr;
1803 Constant *Value = nullptr;
1804 unsigned Idx = -1u;
1805
1806 // Find constant vector with the single element in shuffle (LHS or RHS).
1807 if (LHSIdx < OpWidth && RHSUniform) {
1808 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1809 Op = Shuffle->getOperand(1);
1810 Value = CV->getOperand(LHSValIdx);
1811 Idx = LHSIdx;
1812 }
1813 }
1814 if (RHSIdx < OpWidth && LHSUniform) {
1815 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1816 Op = Shuffle->getOperand(0);
1817 Value = CV->getOperand(RHSValIdx);
1818 Idx = RHSIdx;
1819 }
1820 }
1821 // Found constant vector with single element - convert to insertelement.
1822 if (Op && Value) {
1824 Op, Value, ConstantInt::get(Type::getInt64Ty(I->getContext()), Idx),
1825 Shuffle->getName());
1826 InsertNewInstWith(New, Shuffle->getIterator());
1827 return New;
1828 }
1829 }
1830 if (NewPoisonElts) {
1831 // Add additional discovered undefs.
1833 for (unsigned i = 0; i < VWidth; ++i) {
1834 if (PoisonElts[i])
1836 else
1837 Elts.push_back(Shuffle->getMaskValue(i));
1838 }
1839 Shuffle->setShuffleMask(Elts);
1840 MadeChange = true;
1841 }
1842 break;
1843 }
1844 case Instruction::Select: {
1845 // If this is a vector select, try to transform the select condition based
1846 // on the current demanded elements.
1848 if (Sel->getCondition()->getType()->isVectorTy()) {
1849 // TODO: We are not doing anything with PoisonElts based on this call.
1850 // It is overwritten below based on the other select operands. If an
1851 // element of the select condition is known undef, then we are free to
1852 // choose the output value from either arm of the select. If we know that
1853 // one of those values is undef, then the output can be undef.
1854 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1855 }
1856
1857 // Next, see if we can transform the arms of the select.
1858 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1859 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1860 for (unsigned i = 0; i < VWidth; i++) {
1861 Constant *CElt = CV->getAggregateElement(i);
1862
1863 // isNullValue() always returns false when called on a ConstantExpr.
1864 if (CElt->isNullValue())
1865 DemandedLHS.clearBit(i);
1866 else if (CElt->isOneValue())
1867 DemandedRHS.clearBit(i);
1868 }
1869 }
1870
1871 simplifyAndSetOp(I, 1, DemandedLHS, PoisonElts2);
1872 simplifyAndSetOp(I, 2, DemandedRHS, PoisonElts3);
1873
1874 // Output elements are undefined if the element from each arm is undefined.
1875 // TODO: This can be improved. See comment in select condition handling.
1876 PoisonElts = PoisonElts2 & PoisonElts3;
1877 break;
1878 }
1879 case Instruction::BitCast: {
1880 // Vector->vector casts only.
1881 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1882 if (!VTy) break;
1883 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1884 APInt InputDemandedElts(InVWidth, 0);
1885 PoisonElts2 = APInt(InVWidth, 0);
1886 unsigned Ratio;
1887
1888 if (VWidth == InVWidth) {
1889 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1890 // elements as are demanded of us.
1891 Ratio = 1;
1892 InputDemandedElts = DemandedElts;
1893 } else if ((VWidth % InVWidth) == 0) {
1894 // If the number of elements in the output is a multiple of the number of
1895 // elements in the input then an input element is live if any of the
1896 // corresponding output elements are live.
1897 Ratio = VWidth / InVWidth;
1898 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1899 if (DemandedElts[OutIdx])
1900 InputDemandedElts.setBit(OutIdx / Ratio);
1901 } else if ((InVWidth % VWidth) == 0) {
1902 // If the number of elements in the input is a multiple of the number of
1903 // elements in the output then an input element is live if the
1904 // corresponding output element is live.
1905 Ratio = InVWidth / VWidth;
1906 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1907 if (DemandedElts[InIdx / Ratio])
1908 InputDemandedElts.setBit(InIdx);
1909 } else {
1910 // Unsupported so far.
1911 break;
1912 }
1913
1914 simplifyAndSetOp(I, 0, InputDemandedElts, PoisonElts2);
1915
1916 if (VWidth == InVWidth) {
1917 PoisonElts = PoisonElts2;
1918 } else if ((VWidth % InVWidth) == 0) {
1919 // If the number of elements in the output is a multiple of the number of
1920 // elements in the input then an output element is undef if the
1921 // corresponding input element is undef.
1922 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1923 if (PoisonElts2[OutIdx / Ratio])
1924 PoisonElts.setBit(OutIdx);
1925 } else if ((InVWidth % VWidth) == 0) {
1926 // If the number of elements in the input is a multiple of the number of
1927 // elements in the output then an output element is undef if all of the
1928 // corresponding input elements are undef.
1929 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1930 APInt SubUndef = PoisonElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1931 if (SubUndef.popcount() == Ratio)
1932 PoisonElts.setBit(OutIdx);
1933 }
1934 } else {
1935 llvm_unreachable("Unimp");
1936 }
1937 break;
1938 }
1939 case Instruction::FPTrunc:
1940 case Instruction::FPExt:
1941 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1942 break;
1943
1944 case Instruction::Call: {
1946 if (!II) break;
1947 switch (II->getIntrinsicID()) {
1948 case Intrinsic::masked_gather: // fallthrough
1949 case Intrinsic::masked_load: {
1950 // Subtlety: If we load from a pointer, the pointer must be valid
1951 // regardless of whether the element is demanded. Doing otherwise risks
1952 // segfaults which didn't exist in the original program.
1953 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1954 DemandedPassThrough(DemandedElts);
1955 if (auto *CMask = dyn_cast<Constant>(II->getOperand(1))) {
1956 for (unsigned i = 0; i < VWidth; i++) {
1957 if (Constant *CElt = CMask->getAggregateElement(i)) {
1958 if (CElt->isNullValue())
1959 DemandedPtrs.clearBit(i);
1960 else if (CElt->isAllOnesValue())
1961 DemandedPassThrough.clearBit(i);
1962 }
1963 }
1964 }
1965
1966 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1967 simplifyAndSetOp(II, 0, DemandedPtrs, PoisonElts2);
1968 simplifyAndSetOp(II, 2, DemandedPassThrough, PoisonElts3);
1969
1970 // Output elements are undefined if the element from both sources are.
1971 // TODO: can strengthen via mask as well.
1972 PoisonElts = PoisonElts2 & PoisonElts3;
1973 break;
1974 }
1975 case Intrinsic::vector_shuffle: {
1976 // Result element i only depends on mask element i, so the elements
1977 // required from the mask are the same as the demanded result elements.
1978 simplifyAndSetOp(II, 1, DemandedElts, PoisonElts);
1979 // Only those source elements are required which are indexed by the
1980 // demanded elements of the mask. So source elements that are not in the
1981 // range specified by the following are not required.
1983 II->getArgOperand(1), /*ForSigned=*/false, SQ.getWithInstruction(II));
1984 // Indexes >= VWidth produce poison, so they don't require any source
1985 // elements.
1986 unsigned Lo = KnownRange.getUnsignedMin().getLimitedValue(VWidth);
1987 unsigned Hi = KnownRange.getUnsignedMax().getLimitedValue(VWidth - 1) + 1;
1988 APInt DemandedSrc = APInt::getBitsSet(VWidth, Lo, Hi);
1989 simplifyAndSetOp(II, 0, DemandedSrc, PoisonElts3);
1990 break;
1991 }
1992 default: {
1993 // Handle target specific intrinsics
1994 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1995 *II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
1996 simplifyAndSetOp);
1997 if (V)
1998 return *V;
1999
2000 // Trivially vectorizable intrinsics operate elementwise: each result lane
2001 // uses only the matching lane of the (vector) operands, so the demand
2002 // passes through unchanged to every vector operand.
2003 Intrinsic::ID IID = II->getIntrinsicID();
2004 if (isTriviallyVectorizable(IID)) {
2005 APInt PoisonEltsAcc(VWidth, 0);
2006 for (Use &Arg : II->args()) {
2007 unsigned OpNo = Arg.getOperandNo();
2008 // Scalar operands do not carry per-lane demand.
2009 if (isVectorIntrinsicWithScalarOpAtArg(IID, OpNo, /*TTI=*/nullptr))
2010 continue;
2011 APInt OpPoisonElts(VWidth, 0);
2012 simplifyAndSetOp(II, OpNo, DemandedElts, OpPoisonElts);
2013 PoisonEltsAcc |= OpPoisonElts;
2014 }
2015 // A result lane is poison if any operand lane is poison, but only for
2016 // intrinsics that are known to propagate poison elementwise.
2018 PoisonElts = PoisonEltsAcc;
2019 }
2020 break;
2021 }
2022 } // switch on IntrinsicID
2023 break;
2024 } // case Call
2025 } // switch on Opcode
2026
2027 // TODO: We bail completely on integer div/rem and shifts because they have
2028 // UB/poison potential, but that should be refined.
2029 BinaryOperator *BO;
2030 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
2031 Value *X = BO->getOperand(0);
2032 Value *Y = BO->getOperand(1);
2033
2034 // Look for an equivalent binop except that one operand has been shuffled.
2035 // If the demand for this binop only includes elements that are the same as
2036 // the other binop, then we may be able to replace this binop with a use of
2037 // the earlier one.
2038 //
2039 // Example:
2040 // %other_bo = bo (shuf X, {0}), Y
2041 // %this_extracted_bo = extelt (bo X, Y), 0
2042 // -->
2043 // %other_bo = bo (shuf X, {0}), Y
2044 // %this_extracted_bo = extelt %other_bo, 0
2045 //
2046 // TODO: Handle demand of an arbitrary single element or more than one
2047 // element instead of just element 0.
2048 // TODO: Unlike general demanded elements transforms, this should be safe
2049 // for any (div/rem/shift) opcode too.
2050 if (DemandedElts == 1 && !X->hasOneUse() && !Y->hasOneUse() &&
2051 BO->hasOneUse() ) {
2052
2053 auto findShufBO = [&](bool MatchShufAsOp0) -> User * {
2054 // Try to use shuffle-of-operand in place of an operand:
2055 // bo X, Y --> bo (shuf X), Y
2056 // bo X, Y --> bo X, (shuf Y)
2057
2058 Value *OtherOp = MatchShufAsOp0 ? Y : X;
2059 if (!OtherOp->hasUseList())
2060 return nullptr;
2061
2062 BinaryOperator::BinaryOps Opcode = BO->getOpcode();
2063 Value *ShufOp = MatchShufAsOp0 ? X : Y;
2064
2065 for (User *U : OtherOp->users()) {
2066 ArrayRef<int> Mask;
2067 auto Shuf = m_Shuffle(m_Specific(ShufOp), m_Value(), m_Mask(Mask));
2068 if (BO->isCommutative()
2069 ? match(U, m_c_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
2070 : MatchShufAsOp0
2071 ? match(U, m_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
2072 : match(U, m_BinOp(Opcode, m_Specific(OtherOp), Shuf)))
2073 if (match(Mask, m_ZeroMask()) && Mask[0] != PoisonMaskElem)
2074 if (DT.dominates(U, I))
2075 return U;
2076 }
2077 return nullptr;
2078 };
2079
2080 User *ShufBO = findShufBO(/* MatchShufAsOp0 */ true);
2081 if (!ShufBO)
2082 ShufBO = findShufBO(/* MatchShufAsOp0 */ false);
2083 if (ShufBO) {
2084 auto *ShufBOI = cast<Instruction>(ShufBO);
2085 ShufBOI->andIRFlags(BO);
2086 Worklist.add(ShufBOI);
2087 return ShufBO;
2088 }
2089 }
2090
2091 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
2092 simplifyAndSetOp(I, 1, DemandedElts, PoisonElts2);
2093
2094 // Output elements are undefined if both are undefined. Consider things
2095 // like undef & 0. The result is known zero, not undef.
2096 PoisonElts &= PoisonElts2;
2097 }
2098
2099 // If we've proven all of the lanes poison, return a poison value.
2100 // TODO: Intersect w/demanded lanes
2101 if (PoisonElts.isAllOnes())
2102 return PoisonValue::get(I->getType());
2103
2104 return MadeChange ? I : nullptr;
2105}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define DEBUG_TYPE
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
static Value * simplifyShiftSelectingPackedElement(Instruction *I, const APInt &DemandedMask, InstCombinerImpl &IC, unsigned Depth)
Let N = 2 * M.
static bool canSkipDemandedEltsInInsertChain(InsertElementInst &IE, unsigned VWidth, unsigned DepthLimit)
Return true if the top-level all-lanes demanded-elements query can be skipped for an intermediate ins...
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
This file implements the SmallBitVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
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:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1411
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1360
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1416
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1455
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:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:428
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a range of values.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:83
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2458
LLVM_ABI Value * CreateSelectWithUnknownProfile(Value *C, Value *True, Value *False, StringRef PassName, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
This instruction inserts a single (scalar) element into a VectorType value.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
std::optional< std::pair< Intrinsic::ID, SmallVector< Value *, 3 > > > convertOrOfShiftsToFunnelShift(Instruction &Or)
const InstCombineCLOptions & CLOpts
Value * simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known)
Helper routine of SimplifyDemandedUseBits.
Value * SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Attempts to replace I with a simpler value based on the demanded bits.
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Value * SimplifyMultipleUseDemandedBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Helper routine of SimplifyDemandedUseBits.
SimplifyQuery SQ
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
LLVM_ABI std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
LLVM_ABI std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
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 bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
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.
bool isShift() const
bool isIntDivRem() const
A wrapper class for inspecting calls to intrinsic functions.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool test(unsigned Idx) const
Returns true if bit Idx is set.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
iterator_range< user_iterator > users()
Definition Value.h:428
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
Base class of all SIMD vector types.
This class represents zero extension of integer types.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
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_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
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.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
DisjointOr_match< LHS, RHS, true > m_c_DisjointOr(const LHS &L, const RHS &R)
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.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
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)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1836
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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...
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
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 bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
DWARFExpression::Operation Op
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
Matching combinators.
const Instruction * CtxI