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