LLVM 24.0.0git
InstCombineSimplifyDemanded.cpp
Go to the documentation of this file.
1//===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains logic for simplifying instructions based on information
10// about how they are used.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
22
23using namespace llvm;
24using namespace llvm::PatternMatch;
25
26#define DEBUG_TYPE "instcombine"
27
28static cl::opt<bool>
29 VerifyKnownBits("instcombine-verify-known-bits",
30 cl::desc("Verify that computeKnownBits() and "
31 "SimplifyDemandedBits() are consistent"),
32 cl::Hidden, cl::init(false));
33
35 "instcombine-simplify-vector-elts-depth",
37 "Depth limit when simplifying vector instructions and their operands"),
38 cl::Hidden, cl::init(10));
39
40/// Check to see if the specified operand of the specified instruction is a
41/// constant integer. If so, check to see if there are any bits set in the
42/// constant that are not demanded. If so, shrink the constant and return true.
43static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
44 const APInt &Demanded) {
45 assert(I && "No instruction?");
46 assert(OpNo < I->getNumOperands() && "Operand index too large");
47
48 // The operand must be a constant integer or splat integer.
49 Value *Op = I->getOperand(OpNo);
50 const APInt *C;
51 if (!match(Op, m_APInt(C)))
52 return false;
53
54 // If there are no bits set that aren't demanded, nothing to do.
55 if (C->isSubsetOf(Demanded))
56 return false;
57
58 // This instruction is producing bits that are not demanded. Shrink the RHS.
59 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
60
61 return true;
62}
63
64/// Let N = 2 * M.
65/// Given an N-bit integer representing a pack of two M-bit integers,
66/// we can select one of the packed integers by right-shifting by either
67/// zero or M (which is the most straightforward to check if M is a power
68/// of 2), and then isolating the lower M bits. In this case, we can
69/// represent the shift as a select on whether the shr amount is nonzero.
71 const APInt &DemandedMask,
73 unsigned Depth) {
74 assert(I->getOpcode() == Instruction::LShr &&
75 "Only lshr instruction supported");
76
77 uint64_t ShlAmt;
78 Value *Upper, *Lower;
79 if (!match(I->getOperand(0),
82 m_Value(Lower)))))
83 return nullptr;
84
85 if (!isPowerOf2_64(ShlAmt))
86 return nullptr;
87
88 const uint64_t DemandedBitWidth = DemandedMask.getActiveBits();
89 if (DemandedBitWidth > ShlAmt)
90 return nullptr;
91
92 // Check that upper demanded bits are not lost from lshift.
93 if (Upper->getType()->getScalarSizeInBits() < ShlAmt + DemandedBitWidth)
94 return nullptr;
95
96 KnownBits KnownLowerBits = IC.computeKnownBits(Lower, I, Depth);
97 if (!KnownLowerBits.getMaxValue().isIntN(ShlAmt))
98 return nullptr;
99
100 Value *ShrAmt = I->getOperand(1);
101 KnownBits KnownShrBits = IC.computeKnownBits(ShrAmt, I, Depth);
102
103 // Verify that ShrAmt is either exactly ShlAmt (which is a power of 2) or
104 // zero.
105 if (~KnownShrBits.Zero != ShlAmt)
106 return nullptr;
107
110 Value *ShrAmtZ =
112 ShrAmt->getName() + ".z");
113 // There is no existing !prof metadata we can derive the !prof metadata for
114 // this select.
117 Select->takeName(I);
118 return Select;
119}
120
121/// Returns the bitwidth of the given scalar or pointer type. For vector types,
122/// returns the element type's bitwidth.
123static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
124 if (unsigned BitWidth = Ty->getScalarSizeInBits())
125 return BitWidth;
126
127 return DL.getPointerTypeSizeInBits(Ty);
128}
129
130/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
131/// the instruction has any properties that allow us to simplify its operands.
133 KnownBits &Known) {
134 APInt DemandedMask(APInt::getAllOnes(Known.getBitWidth()));
135 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
136 SQ.getWithInstruction(&Inst));
137 if (!V) return false;
138 if (V == &Inst) return true;
139 replaceInstUsesWith(Inst, V);
140 return true;
141}
142
143/// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
144/// the instruction has any properties that allow us to simplify its operands.
149
152
154 SQ.getWithInstruction(&Inst));
155 if (!V)
156 return false;
157 if (V == &Inst)
158 return true;
159 replaceInstUsesWith(Inst, V);
160 return true;
161}
162
163/// This form of SimplifyDemandedBits simplifies the specified instruction
164/// operand if possible, updating it in place. It returns true if it made any
165/// change and false otherwise.
167 const APInt &DemandedMask,
169 const SimplifyQuery &Q,
170 unsigned Depth) {
171 Use &U = I->getOperandUse(OpNo);
172 Value *V = U.get();
173 if (isa<Constant>(V)) {
175 return false;
176 }
177
178 Known.resetAll();
179 if (DemandedMask.isZero()) {
180 // Not demanding any bits from V.
181 replaceUse(U, UndefValue::get(V->getType()));
182 return true;
183 }
184
186 if (!VInst) {
188 return false;
189 }
190
192 return false;
193
194 Value *NewVal;
195 if (VInst->hasOneUse()) {
196 // If the instruction has one use, we can directly simplify it.
197 NewVal = SimplifyDemandedUseBits(VInst, DemandedMask, Known, Q, Depth);
198 } else {
199 // If there are multiple uses of this instruction, then we can simplify
200 // VInst to some other value, but not modify the instruction.
201 NewVal =
202 SimplifyMultipleUseDemandedBits(VInst, DemandedMask, Known, Q, Depth);
203 }
204 if (!NewVal) return false;
205 if (Instruction* OpInst = dyn_cast<Instruction>(U))
206 salvageDebugInfo(*OpInst);
207
208 replaceUse(U, NewVal);
209 return true;
210}
211
212/// This function attempts to replace V with a simpler value based on the
213/// demanded bits. When this function is called, it is known that only the bits
214/// set in DemandedMask of the result of V are ever used downstream.
215/// Consequently, depending on the mask and V, it may be possible to replace V
216/// with a constant or one of its operands. In such cases, this function does
217/// the replacement and returns true. In all other cases, it returns false after
218/// analyzing the expression and setting KnownOne and known to be one in the
219/// expression. Known.Zero contains all the bits that are known to be zero in
220/// the expression. These are provided to potentially allow the caller (which
221/// might recursively be SimplifyDemandedBits itself) to simplify the
222/// expression.
223/// Known.One and Known.Zero always follow the invariant that:
224/// Known.One & Known.Zero == 0.
225/// That is, a bit can't be both 1 and 0. The bits in Known.One and Known.Zero
226/// are accurate even for bits not in DemandedMask. Note
227/// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
228/// be the same.
229///
230/// This returns null if it did not change anything and it permits no
231/// simplification. This returns V itself if it did some simplification of V's
232/// operands based on the information about what bits are demanded. This returns
233/// some other non-null value if it found out that V is equal to another value
234/// in the context where the specified bits are demanded, but not for all users.
236 const APInt &DemandedMask,
238 const SimplifyQuery &Q,
239 unsigned Depth) {
240 assert(I != nullptr && "Null pointer of Value???");
241 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
242 uint32_t BitWidth = DemandedMask.getBitWidth();
243 Type *VTy = I->getType();
244 assert(
245 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
246 Known.getBitWidth() == BitWidth &&
247 "Value *V, DemandedMask and Known must have same BitWidth");
248
249 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
250
251 // Update flags after simplifying an operand based on the fact that some high
252 // order bits are not demanded.
253 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
254 unsigned NLZ) {
255 if (NLZ > 0) {
256 // Disable the nsw and nuw flags here: We can no longer guarantee that
257 // we won't wrap after simplification. Removing the nsw/nuw flags is
258 // legal here because the top bit is not demanded.
259 I->setHasNoSignedWrap(false);
260 I->setHasNoUnsignedWrap(false);
261 }
262 return I;
263 };
264
265 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
266 // about the high bits of the operands.
267 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
268 unsigned NLZ = DemandedMask.countl_zero();
269 // Right fill the mask of bits for the operands to demand the most
270 // significant bit and all those below it.
271 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
272 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
273 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Q, Depth + 1) ||
274 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
275 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1)) {
276 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
277 return true;
278 }
279 return false;
280 };
281
282 switch (I->getOpcode()) {
283 default:
285 break;
286 case Instruction::And: {
287 // If either the LHS or the RHS are Zero, the result is zero.
288 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
289 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown, Q,
290 Depth + 1))
291 return I;
292
293 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
294 Q, Depth);
295
296 // If the client is only demanding bits that we know, return the known
297 // constant.
298 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
299 return Constant::getIntegerValue(VTy, Known.One);
300
301 // If all of the demanded bits are known 1 on one side, return the other.
302 // These bits cannot contribute to the result of the 'and'.
303 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
304 return I->getOperand(0);
305 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
306 return I->getOperand(1);
307
308 // If the RHS is a constant, see if we can simplify it.
309 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
310 return I;
311
312 break;
313 }
314 case Instruction::Or: {
315 // If either the LHS or the RHS are One, the result is One.
316 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
317 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown, Q,
318 Depth + 1)) {
319 // Disjoint flag may not longer hold.
320 I->dropPoisonGeneratingFlags();
321 return I;
322 }
323
324 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
325 Q, Depth);
326
327 // If the client is only demanding bits that we know, return the known
328 // constant.
329 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
330 return Constant::getIntegerValue(VTy, Known.One);
331
332 // If all of the demanded bits are known zero on one side, return the other.
333 // These bits cannot contribute to the result of the 'or'.
334 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
335 return I->getOperand(0);
336 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
337 return I->getOperand(1);
338
339 // If the RHS is a constant, see if we can simplify it.
340 if (ShrinkDemandedConstant(I, 1, DemandedMask))
341 return I;
342
343 // Infer disjoint flag if no common bits are set.
344 if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) {
345 WithCache<const Value *> LHSCache(I->getOperand(0), LHSKnown),
346 RHSCache(I->getOperand(1), RHSKnown);
347 if (haveNoCommonBitsSet(LHSCache, RHSCache, Q)) {
348 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
349 return I;
350 }
351 }
352
353 break;
354 }
355 case Instruction::Xor: {
356 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Q, Depth + 1) ||
357 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1))
358 return I;
359 Value *LHS, *RHS;
360 if (DemandedMask == 1 && match(I->getOperand(0), m_Ctpop(m_Value(LHS))) &&
361 match(I->getOperand(1), m_Ctpop(m_Value(RHS)))) {
362 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
364 Builder.SetInsertPoint(I);
365 auto *Xor = Builder.CreateXor(LHS, RHS);
366 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
367 }
368
369 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
370 Q, Depth);
371
372 // If the client is only demanding bits that we know, return the known
373 // constant.
374 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
375 return Constant::getIntegerValue(VTy, Known.One);
376
377 // If all of the demanded bits are known zero on one side, return the other.
378 // These bits cannot contribute to the result of the 'xor'.
379 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
380 return I->getOperand(0);
381 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
382 return I->getOperand(1);
383
384 // If all of the demanded bits are known to be zero on one side or the
385 // other, turn this into an *inclusive* or.
386 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
387 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
388 Instruction *Or =
389 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1));
390 if (DemandedMask.isAllOnes())
391 cast<PossiblyDisjointInst>(Or)->setIsDisjoint(true);
392 Or->takeName(I);
393 return InsertNewInstWith(Or, I->getIterator());
394 }
395
396 // If all of the demanded bits on one side are known, and all of the set
397 // bits on that side are also known to be set on the other side, turn this
398 // into an AND, as we know the bits will be cleared.
399 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
400 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
401 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
403 ~RHSKnown.One & DemandedMask);
404 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
405 return InsertNewInstWith(And, I->getIterator());
406 }
407
408 // If the RHS is a constant, see if we can change it. Don't alter a -1
409 // constant because that's a canonical 'not' op, and that is better for
410 // combining, SCEV, and codegen.
411 const APInt *C;
412 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
413 if ((*C | ~DemandedMask).isAllOnes()) {
414 // Force bits to 1 to create a 'not' op.
415 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
416 return I;
417 }
418 // If we can't turn this into a 'not', try to shrink the constant.
419 if (ShrinkDemandedConstant(I, 1, DemandedMask))
420 return I;
421 }
422
423 // If our LHS is an 'and' and if it has one use, and if any of the bits we
424 // are flipping are known to be set, then the xor is just resetting those
425 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
426 // simplifying both of them.
427 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
428 ConstantInt *AndRHS, *XorRHS;
429 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
430 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
431 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
432 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
433 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
434
435 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
436 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
437 InsertNewInstWith(NewAnd, I->getIterator());
438
439 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
440 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
441 return InsertNewInstWith(NewXor, I->getIterator());
442 }
443 }
444 break;
445 }
446 case Instruction::Select: {
447 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Q, Depth + 1) ||
448 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Q, Depth + 1))
449 return I;
450
451 // If the operands are constants, see if we can simplify them.
452 // This is similar to ShrinkDemandedConstant, but for a select we want to
453 // try to keep the selected constants the same as icmp value constants, if
454 // we can. This helps not break apart (or helps put back together)
455 // canonical patterns like min and max.
456 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
457 const APInt &DemandedMask) {
458 const APInt *SelC;
459 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
460 return false;
461
462 // Get the constant out of the ICmp, if there is one.
463 // Only try this when exactly 1 operand is a constant (if both operands
464 // are constant, the icmp should eventually simplify). Otherwise, we may
465 // invert the transform that reduces set bits and infinite-loop.
466 Value *X;
467 const APInt *CmpC;
468 if (!match(I->getOperand(0), m_ICmp(m_Value(X), m_APInt(CmpC))) ||
469 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
470 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
471
472 // If the constant is already the same as the ICmp, leave it as-is.
473 if (*CmpC == *SelC)
474 return false;
475 // If the constants are not already the same, but can be with the demand
476 // mask, use the constant value from the ICmp.
477 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
478 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
479 return true;
480 }
481 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
482 };
483 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
484 CanonicalizeSelectConstant(I, 2, DemandedMask))
485 return I;
486
487 // Only known if known in both the LHS and RHS.
488 adjustKnownBitsForSelectArm(LHSKnown, I->getOperand(0), I->getOperand(1),
489 /*Invert=*/false, Q, Depth);
490 adjustKnownBitsForSelectArm(RHSKnown, I->getOperand(0), I->getOperand(2),
491 /*Invert=*/true, Q, Depth);
492 Known = LHSKnown.intersectWith(RHSKnown);
493 break;
494 }
495 case Instruction::Trunc: {
496 // If we do not demand the high bits of a right-shifted and truncated value,
497 // then we may be able to truncate it before the shift.
498 Value *X;
499 const APInt *C;
500 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
501 // The shift amount must be valid (not poison) in the narrow type, and
502 // it must not be greater than the high bits demanded of the result.
503 if (C->ult(VTy->getScalarSizeInBits()) &&
504 C->ule(DemandedMask.countl_zero())) {
505 // trunc (lshr X, C) --> lshr (trunc X), C
507 Builder.SetInsertPoint(I);
508 Value *Trunc = Builder.CreateTrunc(X, VTy);
509 return Builder.CreateLShr(Trunc, C->getZExtValue());
510 }
511 }
512 }
513 [[fallthrough]];
514 case Instruction::ZExt: {
515 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
516
517 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
518 KnownBits InputKnown(SrcBitWidth);
519 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Q,
520 Depth + 1)) {
521 // For zext nneg, we may have dropped the instruction which made the
522 // input non-negative.
523 I->dropPoisonGeneratingFlags();
524 return I;
525 }
526 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
527 if (I->getOpcode() == Instruction::ZExt && I->hasNonNeg() &&
528 !InputKnown.isNegative())
529 InputKnown.makeNonNegative();
530 Known = InputKnown.zextOrTrunc(BitWidth);
531
532 break;
533 }
534 case Instruction::SExt: {
535 // Compute the bits in the result that are not present in the input.
536 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
537
538 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
539
540 // If any of the sign extended bits are demanded, we know that the sign
541 // bit is demanded.
542 if (DemandedMask.getActiveBits() > SrcBitWidth)
543 InputDemandedBits.setBit(SrcBitWidth-1);
544
545 KnownBits InputKnown(SrcBitWidth);
546 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Q, Depth + 1))
547 return I;
548
549 // If the input sign bit is known zero, or if the NewBits are not demanded
550 // convert this into a zero extension.
551 if (InputKnown.isNonNegative() ||
552 DemandedMask.getActiveBits() <= SrcBitWidth) {
553 // Convert to ZExt cast.
554 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy);
555 NewCast->takeName(I);
556 return InsertNewInstWith(NewCast, I->getIterator());
557 }
558
559 // If the sign bit of the input is known set or clear, then we know the
560 // top bits of the result.
561 Known = InputKnown.sext(BitWidth);
562 break;
563 }
564 case Instruction::Add: {
565 if ((DemandedMask & 1) == 0) {
566 // If we do not need the low bit, try to convert bool math to logic:
567 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
568 Value *X, *Y;
570 m_OneUse(m_SExt(m_Value(Y))))) &&
571 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
572 // Truth table for inputs and output signbits:
573 // X:0 | X:1
574 // ----------
575 // Y:0 | 0 | 0 |
576 // Y:1 | -1 | 0 |
577 // ----------
579 Builder.SetInsertPoint(I);
580 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
581 return Builder.CreateSExt(AndNot, VTy);
582 }
583
584 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
585 if (match(I, m_Add(m_SExt(m_Value(X)), m_SExt(m_Value(Y)))) &&
586 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType() &&
587 (I->getOperand(0)->hasOneUse() || I->getOperand(1)->hasOneUse())) {
588
589 // Truth table for inputs and output signbits:
590 // X:0 | X:1
591 // -----------
592 // Y:0 | 0 | -1 |
593 // Y:1 | -1 | -1 |
594 // -----------
596 Builder.SetInsertPoint(I);
597 Value *Or = Builder.CreateOr(X, Y);
598 return Builder.CreateSExt(Or, VTy);
599 }
600 }
601
602 // Right fill the mask of bits for the operands to demand the most
603 // significant bit and all those below it.
604 unsigned NLZ = DemandedMask.countl_zero();
605 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
606 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
607 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
608 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
609
610 // If low order bits are not demanded and known to be zero in one operand,
611 // then we don't need to demand them from the other operand, since they
612 // can't cause overflow into any bits that are demanded in the result.
613 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
614 APInt DemandedFromLHS = DemandedFromOps;
615 DemandedFromLHS.clearLowBits(NTZ);
616 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
617 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
618 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
619
620 unsigned NtzLHS = (~DemandedMask & LHSKnown.Zero).countr_one();
621 APInt DemandedFromRHS = DemandedFromOps;
622 DemandedFromRHS.clearLowBits(NtzLHS);
623 if (ShrinkDemandedConstant(I, 1, DemandedFromRHS))
624 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
625
626 // If we are known to be adding zeros to every bit below
627 // the highest demanded bit, we just return the other side.
628 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
629 return I->getOperand(0);
630 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
631 return I->getOperand(1);
632
633 // (add X, C) --> (xor X, C) IFF C is equal to the top bit of the DemandMask
634 {
635 const APInt *C;
636 if (match(I->getOperand(1), m_APInt(C)) &&
637 C->isOneBitSet(DemandedMask.getActiveBits() - 1)) {
639 Builder.SetInsertPoint(I);
640 return Builder.CreateXor(I->getOperand(0), ConstantInt::get(VTy, *C));
641 }
642 }
643
644 // Otherwise just compute the known bits of the result.
645 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
646 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
647 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
648 break;
649 }
650 case Instruction::Sub: {
651 // Right fill the mask of bits for the operands to demand the most
652 // significant bit and all those below it.
653 unsigned NLZ = DemandedMask.countl_zero();
654 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
655 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
656 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Q, Depth + 1))
657 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
658
659 // If low order bits are not demanded and are known to be zero in RHS,
660 // then we don't need to demand them from LHS, since they can't cause a
661 // borrow from any bits that are demanded in the result.
662 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
663 APInt DemandedFromLHS = DemandedFromOps;
664 DemandedFromLHS.clearLowBits(NTZ);
665 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
666 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Q, Depth + 1))
667 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
668
669 // If we are known to be subtracting zeros from every bit below
670 // the highest demanded bit, we just return the other side.
671 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
672 return I->getOperand(0);
673 // We can't do this with the LHS for subtraction, unless we are only
674 // demanding the LSB.
675 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
676 return I->getOperand(1);
677
678 // Canonicalize sub mask, X -> ~X
679 const APInt *LHSC;
680 if (match(I->getOperand(0), m_LowBitMask(LHSC)) &&
681 DemandedFromOps.isSubsetOf(*LHSC)) {
683 Builder.SetInsertPoint(I);
684 return Builder.CreateNot(I->getOperand(1));
685 }
686
687 // Otherwise just compute the known bits of the result.
688 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
689 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
690 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
691 break;
692 }
693 case Instruction::Mul: {
694 APInt DemandedFromOps;
695 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
696 return I;
697
698 if (DemandedMask.isPowerOf2()) {
699 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
700 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
701 // odd (has LSB set), then the left-shifted low bit of X is the answer.
702 unsigned CTZ = DemandedMask.countr_zero();
703 const APInt *C;
704 if (match(I->getOperand(1), m_APInt(C)) && C->countr_zero() == CTZ) {
705 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
706 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
707 return InsertNewInstWith(Shl, I->getIterator());
708 }
709 }
710 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
711 // X * X is odd iff X is odd.
712 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
713 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
714 Constant *One = ConstantInt::get(VTy, 1);
715 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
716 return InsertNewInstWith(And1, I->getIterator());
717 }
718
720 break;
721 }
722 case Instruction::Shl: {
723 const APInt *SA;
724 if (match(I->getOperand(1), m_APInt(SA))) {
725 const APInt *ShrAmt;
726 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
727 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
728 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
729 DemandedMask, Known))
730 return R;
731
732 // Do not simplify if shl is part of funnel-shift pattern
733 if (I->hasOneUse()) {
734 Instruction *Inst = I->user_back();
735 if (Inst->getOpcode() == BinaryOperator::Or) {
736 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
737 auto [IID, FShiftArgs] = *Opt;
738 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
739 FShiftArgs[0] == FShiftArgs[1]) {
741 break;
742 }
743 }
744 }
745 }
746
747 // We only want bits that already match the signbit then we don't
748 // need to shift.
749 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth - 1);
750 if (DemandedMask.countr_zero() >= ShiftAmt) {
751 if (I->hasNoSignedWrap()) {
752 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
753 unsigned SignBits =
754 ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
755 if (SignBits > ShiftAmt && SignBits - ShiftAmt >= NumHiDemandedBits)
756 return I->getOperand(0);
757 }
758
759 // If we can pre-shift a right-shifted constant to the left without
760 // losing any high bits and we don't demand the low bits, then eliminate
761 // the left-shift:
762 // (C >> X) << LeftShiftAmtC --> (C << LeftShiftAmtC) >> X
763 Value *X;
764 Constant *C;
765 if (match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
766 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
767 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::Shl, C,
768 LeftShiftAmtC, DL);
769 if (ConstantFoldBinaryOpOperands(Instruction::LShr, NewC,
770 LeftShiftAmtC, DL) == C) {
771 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
772 return InsertNewInstWith(Lshr, I->getIterator());
773 }
774 }
775 }
776
777 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
778
779 // If the shift is NUW/NSW, then it does demand the high bits.
781 if (IOp->hasNoSignedWrap())
782 DemandedMaskIn.setHighBits(ShiftAmt+1);
783 else if (IOp->hasNoUnsignedWrap())
784 DemandedMaskIn.setHighBits(ShiftAmt);
785
786 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1))
787 return I;
788
791 /* NUW */ IOp->hasNoUnsignedWrap(),
792 /* NSW */ IOp->hasNoSignedWrap());
793 } else {
794 // This is a variable shift, so we can't shift the demand mask by a known
795 // amount. But if we are not demanding high bits, then we are not
796 // demanding those bits from the pre-shifted operand either.
797 if (unsigned CTLZ = DemandedMask.countl_zero()) {
798 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
799 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Q, Depth + 1)) {
800 // We can't guarantee that nsw/nuw hold after simplifying the operand.
801 I->dropPoisonGeneratingFlags();
802 return I;
803 }
804 }
806 }
807 break;
808 }
809 case Instruction::LShr: {
810 const APInt *SA;
811 if (match(I->getOperand(1), m_APInt(SA))) {
812 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
813
814 // Do not simplify if lshr is part of funnel-shift pattern
815 if (I->hasOneUse()) {
816 Instruction *Inst = I->user_back();
817 if (Inst->getOpcode() == BinaryOperator::Or) {
818 if (auto Opt = convertOrOfShiftsToFunnelShift(*Inst)) {
819 auto [IID, FShiftArgs] = *Opt;
820 if ((IID == Intrinsic::fshl || IID == Intrinsic::fshr) &&
821 FShiftArgs[0] == FShiftArgs[1]) {
823 break;
824 }
825 }
826 }
827 }
828
829 // If we are just demanding the shifted sign bit and below, then this can
830 // be treated as an ASHR in disguise.
831 if (DemandedMask.countl_zero() >= ShiftAmt) {
832 // If we only want bits that already match the signbit then we don't
833 // need to shift.
834 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
835 unsigned SignBits =
836 ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
837 if (SignBits >= NumHiDemandedBits)
838 return I->getOperand(0);
839
840 // If we can pre-shift a left-shifted constant to the right without
841 // losing any low bits (we already know we don't demand the high bits),
842 // then eliminate the right-shift:
843 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
844 Value *X;
845 Constant *C;
846 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
847 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
848 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::LShr, C,
849 RightShiftAmtC, DL);
850 if (ConstantFoldBinaryOpOperands(Instruction::Shl, NewC,
851 RightShiftAmtC, DL) == C) {
852 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
853 return InsertNewInstWith(Shl, I->getIterator());
854 }
855 }
856
857 const APInt *Factor;
858 if (match(I->getOperand(0),
859 m_OneUse(m_Mul(m_Value(X), m_APInt(Factor)))) &&
860 Factor->countr_zero() >= ShiftAmt) {
861 BinaryOperator *Mul = BinaryOperator::CreateMul(
862 X, ConstantInt::get(X->getType(), Factor->lshr(ShiftAmt)));
863 return InsertNewInstWith(Mul, I->getIterator());
864 }
865 }
866
867 // Unsigned shift right.
868 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
869 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
870 // exact flag may not longer hold.
871 I->dropPoisonGeneratingFlags();
872 return I;
873 }
874 Known >>= ShiftAmt;
875 if (ShiftAmt)
876 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
877 break;
878 }
879 if (Value *V =
880 simplifyShiftSelectingPackedElement(I, DemandedMask, *this, Depth))
881 return V;
882
884 break;
885 }
886 case Instruction::AShr: {
887 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Q.CxtI, Depth + 1);
888
889 // If we only want bits that already match the signbit then we don't need
890 // to shift.
891 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
892 if (SignBits >= NumHiDemandedBits)
893 return I->getOperand(0);
894
895 // If this is an arithmetic shift right and only the low-bit is set, we can
896 // always convert this into a logical shr, even if the shift amount is
897 // variable. The low bit of the shift cannot be an input sign bit unless
898 // the shift amount is >= the size of the datatype, which is undefined.
899 if (DemandedMask.isOne()) {
900 // Perform the logical shift right.
901 Instruction *NewVal = BinaryOperator::CreateLShr(
902 I->getOperand(0), I->getOperand(1), I->getName());
903 return InsertNewInstWith(NewVal, I->getIterator());
904 }
905
906 const APInt *SA;
907 if (match(I->getOperand(1), m_APInt(SA))) {
908 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
909
910 // Signed shift right.
911 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
912 // If any of the bits being shifted in are demanded, then we should set
913 // the sign bit as demanded.
914 bool ShiftedInBitsDemanded = DemandedMask.countl_zero() < ShiftAmt;
915 if (ShiftedInBitsDemanded)
916 DemandedMaskIn.setSignBit();
917 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Q, Depth + 1)) {
918 // exact flag may not longer hold.
919 I->dropPoisonGeneratingFlags();
920 return I;
921 }
922
923 // If the input sign bit is known to be zero, or if none of the shifted in
924 // bits are demanded, turn this into an unsigned shift right.
925 if (Known.Zero[BitWidth - 1] || !ShiftedInBitsDemanded) {
926 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
927 I->getOperand(1));
928 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
929 LShr->takeName(I);
930 return InsertNewInstWith(LShr, I->getIterator());
931 }
932
935 ShiftAmt != 0, I->isExact());
936 } else {
938 }
939 break;
940 }
941 case Instruction::UDiv: {
942 // UDiv doesn't demand low bits that are zero in the divisor.
943 const APInt *SA;
944 if (match(I->getOperand(1), m_APInt(SA))) {
945 // TODO: Take the demanded mask of the result into account.
946 unsigned RHSTrailingZeros = SA->countr_zero();
947 APInt DemandedMaskIn =
948 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
949 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Q, Depth + 1)) {
950 // We can't guarantee that "exact" is still true after changing the
951 // the dividend.
952 I->dropPoisonGeneratingFlags();
953 return I;
954 }
955
957 cast<BinaryOperator>(I)->isExact());
958 } else {
960 }
961 break;
962 }
963 case Instruction::SRem: {
964 const APInt *Rem;
965 if (match(I->getOperand(1), m_APInt(Rem)) && Rem->isPowerOf2()) {
966 if (DemandedMask.ult(*Rem)) // srem won't affect demanded bits
967 return I->getOperand(0);
968
969 APInt LowBits = *Rem - 1;
970 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
971 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Q, Depth + 1))
972 return I;
974 break;
975 }
976
978 break;
979 }
980 case Instruction::Call: {
981 bool KnownBitsComputed = false;
983 switch (II->getIntrinsicID()) {
984 case Intrinsic::abs: {
985 if (DemandedMask == 1)
986 return II->getArgOperand(0);
987 break;
988 }
989 case Intrinsic::ctpop: {
990 // Checking if the number of clear bits is odd (parity)? If the type has
991 // an even number of bits, that's the same as checking if the number of
992 // set bits is odd, so we can eliminate the 'not' op.
993 Value *X;
994 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
995 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
997 II->getModule(), Intrinsic::ctpop, VTy);
998 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), I->getIterator());
999 }
1000 break;
1001 }
1002 case Intrinsic::bswap: {
1003 // If the only bits demanded come from one byte of the bswap result,
1004 // just shift the input byte into position to eliminate the bswap.
1005 unsigned NLZ = DemandedMask.countl_zero();
1006 unsigned NTZ = DemandedMask.countr_zero();
1007
1008 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1009 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1010 // have 14 leading zeros, round to 8.
1011 NLZ = alignDown(NLZ, 8);
1012 NTZ = alignDown(NTZ, 8);
1013 // If we need exactly one byte, we can do this transformation.
1014 if (BitWidth - NLZ - NTZ == 8) {
1015 // Replace this with either a left or right shift to get the byte into
1016 // the right place.
1017 Instruction *NewVal;
1018 if (NLZ > NTZ)
1019 NewVal = BinaryOperator::CreateLShr(
1020 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
1021 else
1022 NewVal = BinaryOperator::CreateShl(
1023 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
1024 NewVal->takeName(I);
1025 return InsertNewInstWith(NewVal, I->getIterator());
1026 }
1027 break;
1028 }
1029 case Intrinsic::ptrmask: {
1030 unsigned MaskWidth = I->getOperand(1)->getType()->getScalarSizeInBits();
1031 RHSKnown = KnownBits(MaskWidth);
1032 // If either the LHS or the RHS are Zero, the result is zero.
1033 if (SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Q, Depth + 1) ||
1035 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
1036 RHSKnown, Q, Depth + 1))
1037 return I;
1038
1039 // TODO: Should be 1-extend
1040 RHSKnown = RHSKnown.anyextOrTrunc(BitWidth);
1041
1042 Known = LHSKnown & RHSKnown;
1043 KnownBitsComputed = true;
1044
1045 // If the client is only demanding bits we know to be zero, return
1046 // `llvm.ptrmask(p, 0)`. We can't return `null` here due to pointer
1047 // provenance, but making the mask zero will be easily optimizable in
1048 // the backend.
1049 if (DemandedMask.isSubsetOf(Known.Zero) &&
1050 !match(I->getOperand(1), m_Zero()))
1051 return replaceOperand(
1052 *I, 1, Constant::getNullValue(I->getOperand(1)->getType()));
1053
1054 // Mask in demanded space does nothing.
1055 // NOTE: We may have attributes associated with the return value of the
1056 // llvm.ptrmask intrinsic that will be lost when we just return the
1057 // operand. We should try to preserve them.
1058 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1059 return I->getOperand(0);
1060
1061 // If the RHS is a constant, see if we can simplify it.
1063 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
1064 return I;
1065
1066 // Combine:
1067 // (ptrmask (getelementptr i8, ptr p, imm i), imm mask)
1068 // -> (ptrmask (getelementptr i8, ptr p, imm (i & mask)), imm mask)
1069 // where only the low bits known to be zero in the pointer are changed
1070 Value *InnerPtr;
1071 uint64_t GEPIndex;
1072 uint64_t PtrMaskImmediate;
1074 m_PtrAdd(m_Value(InnerPtr), m_ConstantInt(GEPIndex)),
1075 m_ConstantInt(PtrMaskImmediate)))) {
1076
1077 LHSKnown = computeKnownBits(InnerPtr, I, Depth + 1);
1078 if (!LHSKnown.isZero()) {
1079 const unsigned trailingZeros = LHSKnown.countMinTrailingZeros();
1080 uint64_t PointerAlignBits = (uint64_t(1) << trailingZeros) - 1;
1081
1082 uint64_t HighBitsGEPIndex = GEPIndex & ~PointerAlignBits;
1083 uint64_t MaskedLowBitsGEPIndex =
1084 GEPIndex & PointerAlignBits & PtrMaskImmediate;
1085
1086 uint64_t MaskedGEPIndex = HighBitsGEPIndex | MaskedLowBitsGEPIndex;
1087
1088 if (MaskedGEPIndex != GEPIndex) {
1089 auto *GEP = cast<GEPOperator>(II->getArgOperand(0));
1090 Builder.SetInsertPoint(I);
1091 Type *GEPIndexType =
1092 DL.getIndexType(GEP->getPointerOperand()->getType());
1093 Value *MaskedGEP = Builder.CreateGEP(
1094 GEP->getSourceElementType(), InnerPtr,
1095 ConstantInt::get(GEPIndexType, MaskedGEPIndex),
1096 GEP->getName(), GEP->isInBounds());
1097
1098 replaceOperand(*I, 0, MaskedGEP);
1099 return I;
1100 }
1101 }
1102 }
1103
1104 break;
1105 }
1106
1107 case Intrinsic::fshr:
1108 case Intrinsic::fshl: {
1109 const APInt *SA;
1110 if (!match(I->getOperand(2), m_APInt(SA)))
1111 break;
1112
1113 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
1114 // defined, so no need to special-case zero shifts here.
1115 uint64_t ShiftAmt = SA->urem(BitWidth);
1116 if (II->getIntrinsicID() == Intrinsic::fshr)
1117 ShiftAmt = BitWidth - ShiftAmt;
1118
1119 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
1120 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
1121 if (I->getOperand(0) != I->getOperand(1)) {
1122 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Q,
1123 Depth + 1) ||
1124 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Q,
1125 Depth + 1)) {
1126 // Range attribute or metadata may no longer hold.
1127 I->dropPoisonGeneratingAnnotations();
1128 return I;
1129 }
1130 } else { // fshl is a rotate
1131 // Avoid converting rotate into funnel shift.
1132 // Only simplify if one operand is constant.
1133 LHSKnown = computeKnownBits(I->getOperand(0), I, Depth + 1);
1134 if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
1135 !match(I->getOperand(0), m_SpecificInt(LHSKnown.One))) {
1136 replaceOperand(*I, 0, Constant::getIntegerValue(VTy, LHSKnown.One));
1137 return I;
1138 }
1139
1140 RHSKnown = computeKnownBits(I->getOperand(1), I, Depth + 1);
1141 if (DemandedMaskRHS.isSubsetOf(RHSKnown.Zero | RHSKnown.One) &&
1142 !match(I->getOperand(1), m_SpecificInt(RHSKnown.One))) {
1143 replaceOperand(*I, 1, Constant::getIntegerValue(VTy, RHSKnown.One));
1144 return I;
1145 }
1146 }
1147
1148 LHSKnown <<= ShiftAmt;
1149 RHSKnown >>= BitWidth - ShiftAmt;
1150 Known = LHSKnown.unionWith(RHSKnown);
1151 KnownBitsComputed = true;
1152 break;
1153 }
1154 case Intrinsic::umax: {
1155 // UMax(A, C) == A if ...
1156 // The lowest non-zero bit of DemandMask is higher than the highest
1157 // non-zero bit of C.
1158 const APInt *C;
1159 unsigned CTZ = DemandedMask.countr_zero();
1160 if (match(II->getArgOperand(1), m_APInt(C)) &&
1161 CTZ >= C->getActiveBits())
1162 return II->getArgOperand(0);
1163 break;
1164 }
1165 case Intrinsic::umin: {
1166 // UMin(A, C) == A if ...
1167 // The lowest non-zero bit of DemandMask is higher than the highest
1168 // non-one bit of C.
1169 // This comes from using DeMorgans on the above umax example.
1170 const APInt *C;
1171 unsigned CTZ = DemandedMask.countr_zero();
1172 if (match(II->getArgOperand(1), m_APInt(C)) &&
1173 CTZ >= C->getBitWidth() - C->countl_one())
1174 return II->getArgOperand(0);
1175 break;
1176 }
1177 default: {
1178 // Handle target specific intrinsics
1179 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
1180 *II, DemandedMask, Known, KnownBitsComputed);
1181 if (V)
1182 return *V;
1183 break;
1184 }
1185 }
1186 }
1187
1188 if (!KnownBitsComputed)
1190 break;
1191 }
1192 }
1193
1194 if (I->getType()->isPointerTy()) {
1195 Align Alignment = I->getPointerAlignment(DL);
1196 Known.Zero.setLowBits(Log2(Alignment));
1197 }
1198
1199 // If the client is only demanding bits that we know, return the known
1200 // constant. We can't directly simplify pointers as a constant because of
1201 // pointer provenance.
1202 // TODO: We could return `(inttoptr const)` for pointers.
1203 if (!I->getType()->isPointerTy() &&
1204 DemandedMask.isSubsetOf(Known.Zero | Known.One))
1205 return Constant::getIntegerValue(VTy, Known.One);
1206
1207 if (VerifyKnownBits) {
1208 KnownBits ReferenceKnown = llvm::computeKnownBits(I, Q, Depth);
1209 if (Known != ReferenceKnown) {
1210 errs() << "Mismatched known bits for " << *I << " in "
1211 << I->getFunction()->getName() << "\n";
1212 errs() << "computeKnownBits(): " << ReferenceKnown << "\n";
1213 errs() << "SimplifyDemandedBits(): " << Known << "\n";
1214 std::abort();
1215 }
1216 }
1217
1218 return nullptr;
1219}
1220
1221/// Helper routine of SimplifyDemandedUseBits. It computes Known
1222/// bits. It also tries to handle simplifications that can be done based on
1223/// DemandedMask, but without modifying the Instruction.
1225 Instruction *I, const APInt &DemandedMask, KnownBits &Known,
1226 const SimplifyQuery &Q, unsigned Depth) {
1227 unsigned BitWidth = DemandedMask.getBitWidth();
1228 Type *ITy = I->getType();
1229
1230 KnownBits LHSKnown(BitWidth);
1231 KnownBits RHSKnown(BitWidth);
1232
1233 // Despite the fact that we can't simplify this instruction in all User's
1234 // context, we can at least compute the known bits, and we can
1235 // do simplifications that apply to *just* the one user if we know that
1236 // this instruction has a simpler value in that context.
1237 switch (I->getOpcode()) {
1238 case Instruction::And: {
1239 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1240 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1241 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1242 Q, Depth);
1244
1245 // If the client is only demanding bits that we know, return the known
1246 // constant.
1247 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1248 return Constant::getIntegerValue(ITy, Known.One);
1249
1250 // If all of the demanded bits are known 1 on one side, return the other.
1251 // These bits cannot contribute to the result of the 'and' in this context.
1252 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1253 return I->getOperand(0);
1254 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1255 return I->getOperand(1);
1256
1257 break;
1258 }
1259 case Instruction::Or: {
1260 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1261 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1262 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1263 Q, Depth);
1265
1266 // If the client is only demanding bits that we know, return the known
1267 // constant.
1268 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1269 return Constant::getIntegerValue(ITy, Known.One);
1270
1271 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1272 // only bits from X or Y are demanded.
1273 // If all of the demanded bits are known zero on one side, return the other.
1274 // These bits cannot contribute to the result of the 'or' in this context.
1275 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1276 return I->getOperand(0);
1277 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1278 return I->getOperand(1);
1279
1280 break;
1281 }
1282 case Instruction::Xor: {
1283 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1284 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1285 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1286 Q, Depth);
1288
1289 // If the client 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 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1295 // only bits from X or Y are demanded.
1296 // If all of the demanded bits are known zero on one side, return the other.
1297 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1298 return I->getOperand(0);
1299 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1300 return I->getOperand(1);
1301
1302 break;
1303 }
1304 case Instruction::Add: {
1305 unsigned NLZ = DemandedMask.countl_zero();
1306 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1307
1308 // If an operand adds zeros to every bit below the highest demanded bit,
1309 // that operand doesn't change the result. Return the other side.
1310 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1311 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1312 return I->getOperand(0);
1313
1314 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1315 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1316 return I->getOperand(1);
1317
1318 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1319 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1320 Known = KnownBits::add(LHSKnown, RHSKnown, NSW, NUW);
1322 break;
1323 }
1324 case Instruction::Sub: {
1325 unsigned NLZ = DemandedMask.countl_zero();
1326 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1327
1328 // If an operand subtracts zeros from every bit below the highest demanded
1329 // bit, that operand doesn't change the result. Return the other side.
1330 llvm::computeKnownBits(I->getOperand(1), RHSKnown, Q, Depth + 1);
1331 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1332 return I->getOperand(0);
1333
1334 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1335 bool NUW = cast<OverflowingBinaryOperator>(I)->hasNoUnsignedWrap();
1336 llvm::computeKnownBits(I->getOperand(0), LHSKnown, Q, Depth + 1);
1337 Known = KnownBits::sub(LHSKnown, RHSKnown, NSW, NUW);
1339 break;
1340 }
1341 case Instruction::AShr: {
1342 // Compute the Known bits to simplify things downstream.
1344
1345 // If this user is only demanding bits that we know, return the known
1346 // constant.
1347 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1348 return Constant::getIntegerValue(ITy, Known.One);
1349
1350 // If the right shift operand 0 is a result of a left shift by the same
1351 // amount, this is probably a zero/sign extension, which may be unnecessary,
1352 // if we do not demand any of the new sign bits. So, return the original
1353 // operand instead.
1354 const APInt *ShiftRC;
1355 const APInt *ShiftLC;
1356 Value *X;
1357 unsigned BitWidth = DemandedMask.getBitWidth();
1358 if (match(I,
1359 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1360 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1361 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1362 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1363 return X;
1364 }
1365
1366 break;
1367 }
1368 default:
1369 // Compute the Known bits to simplify things downstream.
1371
1372 // If this user is only demanding bits that we know, return the known
1373 // constant.
1374 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1375 return Constant::getIntegerValue(ITy, Known.One);
1376
1377 break;
1378 }
1379
1380 return nullptr;
1381}
1382
1383/// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1384/// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1385/// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1386/// of "C2-C1".
1387///
1388/// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1389/// ..., bn}, without considering the specific value X is holding.
1390/// This transformation is legal iff one of following conditions is hold:
1391/// 1) All the bit in S are 0, in this case E1 == E2.
1392/// 2) We don't care those bits in S, per the input DemandedMask.
1393/// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1394/// rest bits.
1395///
1396/// Currently we only test condition 2).
1397///
1398/// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1399/// not successful.
1401 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1402 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1403 if (!ShlOp1 || !ShrOp1)
1404 return nullptr; // No-op.
1405
1406 Value *VarX = Shr->getOperand(0);
1407 Type *Ty = VarX->getType();
1408 unsigned BitWidth = Ty->getScalarSizeInBits();
1409 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1410 return nullptr; // Undef.
1411
1412 unsigned ShlAmt = ShlOp1.getZExtValue();
1413 unsigned ShrAmt = ShrOp1.getZExtValue();
1414
1415 Known.One.clearAllBits();
1416 Known.Zero.setLowBits(ShlAmt - 1);
1417 Known.Zero &= DemandedMask;
1418
1419 APInt BitMask1(APInt::getAllOnes(BitWidth));
1420 APInt BitMask2(APInt::getAllOnes(BitWidth));
1421
1422 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1423 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1424 (BitMask1.ashr(ShrAmt) << ShlAmt);
1425
1426 if (ShrAmt <= ShlAmt) {
1427 BitMask2 <<= (ShlAmt - ShrAmt);
1428 } else {
1429 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1430 BitMask2.ashr(ShrAmt - ShlAmt);
1431 }
1432
1433 // Check if condition-2 (see the comment to this function) is satified.
1434 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1435 if (ShrAmt == ShlAmt)
1436 return VarX;
1437
1438 if (!Shr->hasOneUse())
1439 return nullptr;
1440
1441 BinaryOperator *New;
1442 if (ShrAmt < ShlAmt) {
1443 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1444 New = BinaryOperator::CreateShl(VarX, Amt);
1446 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1447 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1448 } else {
1449 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1450 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1451 BinaryOperator::CreateAShr(VarX, Amt);
1452 if (cast<BinaryOperator>(Shr)->isExact())
1453 New->setIsExact(true);
1454 }
1455
1456 return InsertNewInstWith(New, Shl->getIterator());
1457 }
1458
1459 return nullptr;
1460}
1461
1462/// Return true if the top-level all-lanes demanded-elements query can be
1463/// skipped for an intermediate insertelement chain node. This is limited to a
1464/// bounded one-use chain with distinct in-range constant indices, where SDVE
1465/// cannot remove a dead insert before hitting its depth limit.
1467 unsigned VWidth,
1468 unsigned DepthLimit) {
1469 // Only skip chain nodes that feed another insertelement; the final chain root
1470 // still runs the full query.
1471 if (!IE.hasOneUse())
1472 return false;
1473 auto *UserIE = dyn_cast<InsertElementInst>(IE.user_back());
1474 if (!UserIE || UserIE->getOperand(0) != &IE)
1475 return false;
1476
1477 SmallBitVector SeenIndices(VWidth);
1478 auto HasNewIndexInRange = [&](InsertElementInst &Insert) {
1479 auto *Idx = dyn_cast<ConstantInt>(Insert.getOperand(2));
1480 // Let the normal SDVE path handle variable or out-of-range indices. The
1481 // latter may simplify the chain and must not be passed to getZExtValue().
1482 if (!Idx || Idx->getValue().uge(VWidth))
1483 return false;
1484
1485 unsigned Index = Idx->getZExtValue();
1486 if (SeenIndices.test(Index))
1487 return false;
1488
1489 SeenIndices.set(Index);
1490 return true;
1491 };
1492
1493 auto *Cur = &IE;
1494 for (unsigned I = 0; I != DepthLimit; ++I) {
1495 // This loop scans the same base-chain window that the SDVE query would
1496 // inspect before hitting its depth limit. With distinct insert indices in
1497 // that window, the all-lanes query cannot remove a dead insert; with
1498 // VWidth > DepthLimit, it also cannot narrow demand to a single lane.
1499 if (!HasNewIndexInRange(*Cur))
1500 return false;
1501
1502 Value *Base = Cur->getOperand(0);
1503 if (match(Base, m_Poison()))
1504 return true;
1505
1507 if (!Cur || !Cur->hasOneUse())
1508 return false;
1509 }
1510
1511 return true;
1512}
1513
1514/// The specified value produces a vector with any number of elements.
1515/// This method analyzes which elements of the operand are poison and
1516/// returns that information in PoisonElts.
1517///
1518/// DemandedElts contains the set of elements that are actually used by the
1519/// caller, and by default (AllowMultipleUsers equals false) the value is
1520/// simplified only if it has a single caller. If AllowMultipleUsers is set
1521/// to true, DemandedElts refers to the union of sets of elements that are
1522/// used by all callers.
1523///
1524/// If the information about demanded elements can be used to simplify the
1525/// operation, the operation is simplified, then the resultant value is
1526/// returned. This returns null if no change was made.
1528 APInt DemandedElts,
1529 APInt &PoisonElts,
1530 unsigned Depth,
1531 bool AllowMultipleUsers) {
1532 // Cannot analyze scalable type. The number of vector elements is not a
1533 // compile-time constant.
1534 if (isa<ScalableVectorType>(V->getType()))
1535 return nullptr;
1536
1537 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1538 APInt EltMask(APInt::getAllOnes(VWidth));
1539 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1540
1541 if (match(V, m_Poison())) {
1542 // If the entire vector is poison, just return this info.
1543 PoisonElts = EltMask;
1544 return nullptr;
1545 }
1546
1547 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1548 PoisonElts = EltMask;
1549 return PoisonValue::get(V->getType());
1550 }
1551
1552 PoisonElts = 0;
1553
1554 if (auto *C = dyn_cast<Constant>(V)) {
1555 // Check if this is identity. If so, return 0 since we are not simplifying
1556 // anything.
1557 if (DemandedElts.isAllOnes())
1558 return nullptr;
1559
1560 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1563 for (unsigned i = 0; i != VWidth; ++i) {
1564 if (!DemandedElts[i]) { // If not demanded, set to poison.
1565 Elts.push_back(Poison);
1566 PoisonElts.setBit(i);
1567 continue;
1568 }
1569
1570 Constant *Elt = C->getAggregateElement(i);
1571 if (!Elt) return nullptr;
1572
1573 Elts.push_back(Elt);
1574 if (isa<PoisonValue>(Elt)) // Already poison.
1575 PoisonElts.setBit(i);
1576 }
1577
1578 // If we changed the constant, return it.
1579 Constant *NewCV = ConstantVector::get(Elts);
1580 return NewCV != C ? NewCV : nullptr;
1581 }
1582
1583 // Limit search depth.
1585 return nullptr;
1586
1587 if (!AllowMultipleUsers) {
1588 // If multiple users are using the root value, proceed with
1589 // simplification conservatively assuming that all elements
1590 // are needed.
1591 if (!V->hasOneUse()) {
1592 // Quit if we find multiple users of a non-root value though.
1593 // They'll be handled when it's their turn to be visited by
1594 // the main instcombine process.
1595 if (Depth != 0)
1596 // TODO: Just compute the PoisonElts information recursively.
1597 return nullptr;
1598
1599 // Conservatively assume that all elements are needed.
1600 DemandedElts = EltMask;
1601 }
1602 }
1603
1605 if (!I) return nullptr; // Only analyze instructions.
1606
1607 bool MadeChange = false;
1608 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1609 APInt Demanded, APInt &Undef) {
1610 auto *II = dyn_cast<IntrinsicInst>(Inst);
1611 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1612 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1613 replaceOperand(*Inst, OpNum, V);
1614 MadeChange = true;
1615 }
1616 };
1617
1618 APInt PoisonElts2(VWidth, 0);
1619 APInt PoisonElts3(VWidth, 0);
1620 switch (I->getOpcode()) {
1621 default: break;
1622
1623 case Instruction::GetElementPtr: {
1624 // The LangRef requires that struct geps have all constant indices. As
1625 // such, we can't convert any operand to partial undef.
1626 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1627 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1628 I != E; I++)
1629 if (I.isStruct())
1630 return true;
1631 return false;
1632 };
1633 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1634 break;
1635
1636 // Conservatively track the demanded elements back through any vector
1637 // operands we may have. We know there must be at least one, or we
1638 // wouldn't have a vector result to get here. Note that we intentionally
1639 // merge the undef bits here since gepping with either an poison base or
1640 // index results in poison.
1641 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1642 if (i == 0 ? match(I->getOperand(i), m_Undef())
1643 : match(I->getOperand(i), m_Poison())) {
1644 // If the entire vector is undefined, just return this info.
1645 PoisonElts = EltMask;
1646 return nullptr;
1647 }
1648 if (I->getOperand(i)->getType()->isVectorTy()) {
1649 APInt PoisonEltsOp(VWidth, 0);
1650 simplifyAndSetOp(I, i, DemandedElts, PoisonEltsOp);
1651 // gep(x, undef) is not undef, so skip considering idx ops here
1652 // Note that we could propagate poison, but we can't distinguish between
1653 // undef & poison bits ATM
1654 if (i == 0)
1655 PoisonElts |= PoisonEltsOp;
1656 }
1657 }
1658
1659 break;
1660 }
1661 case Instruction::InsertElement: {
1662 unsigned DepthLimit = SimplifyDemandedVectorEltsDepthLimit;
1663 auto *IE = cast<InsertElementInst>(I);
1664 // Skip only when SDVE cannot simplify this insert chain before the limit.
1665 if (Depth == 0 && DemandedElts.isAllOnes() && VWidth > DepthLimit &&
1666 canSkipDemandedEltsInInsertChain(*IE, VWidth, DepthLimit))
1667 return nullptr;
1668
1669 // If this is a variable index, we don't know which element it overwrites.
1670 // demand exactly the same input as we produce.
1671 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1672 if (!Idx) {
1673 // Note that we can't propagate undef elt info, because we don't know
1674 // which elt is getting updated.
1675 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts2);
1676 break;
1677 }
1678
1679 // The element inserted overwrites whatever was there, so the input demanded
1680 // set is simpler than the output set.
1681 unsigned IdxNo = Idx->getZExtValue();
1682 APInt PreInsertDemandedElts = DemandedElts;
1683 if (IdxNo < VWidth)
1684 PreInsertDemandedElts.clearBit(IdxNo);
1685
1686 // If we only demand the element that is being inserted and that element
1687 // was extracted from the same index in another vector with the same type,
1688 // replace this insert with that other vector.
1689 // Note: This is attempted before the call to simplifyAndSetOp because that
1690 // may change PoisonElts to a value that does not match with Vec.
1691 Value *Vec;
1692 if (PreInsertDemandedElts == 0 &&
1693 match(I->getOperand(1),
1694 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1695 Vec->getType() == I->getType()) {
1696 return Vec;
1697 }
1698
1699 simplifyAndSetOp(I, 0, PreInsertDemandedElts, PoisonElts);
1700
1701 // If this is inserting an element that isn't demanded, remove this
1702 // insertelement.
1703 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1704 Worklist.push(I);
1705 return I->getOperand(0);
1706 }
1707
1708 // The inserted element is defined.
1709 PoisonElts.clearBit(IdxNo);
1710 break;
1711 }
1712 case Instruction::ShuffleVector: {
1713 auto *Shuffle = cast<ShuffleVectorInst>(I);
1714 assert(Shuffle->getOperand(0)->getType() ==
1715 Shuffle->getOperand(1)->getType() &&
1716 "Expected shuffle operands to have same type");
1717 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1718 ->getNumElements();
1719 // Handle trivial case of a splat. Only check the first element of LHS
1720 // operand.
1721 if (all_of(Shuffle->getShuffleMask(), equal_to(0)) &&
1722 DemandedElts.isAllOnes()) {
1723 if (!isa<PoisonValue>(I->getOperand(1))) {
1724 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1725 MadeChange = true;
1726 }
1727 APInt LeftDemanded(OpWidth, 1);
1728 APInt LHSPoisonElts(OpWidth, 0);
1729 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1730 if (LHSPoisonElts[0])
1731 PoisonElts = EltMask;
1732 else
1733 PoisonElts.clearAllBits();
1734 break;
1735 }
1736
1737 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1738 for (unsigned i = 0; i < VWidth; i++) {
1739 if (DemandedElts[i]) {
1740 unsigned MaskVal = Shuffle->getMaskValue(i);
1741 if (MaskVal != -1u) {
1742 assert(MaskVal < OpWidth * 2 &&
1743 "shufflevector mask index out of range!");
1744 if (MaskVal < OpWidth)
1745 LeftDemanded.setBit(MaskVal);
1746 else
1747 RightDemanded.setBit(MaskVal - OpWidth);
1748 }
1749 }
1750 }
1751
1752 APInt LHSPoisonElts(OpWidth, 0);
1753 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1754
1755 APInt RHSPoisonElts(OpWidth, 0);
1756 simplifyAndSetOp(I, 1, RightDemanded, RHSPoisonElts);
1757
1758 // If this shuffle does not change the vector length and the elements
1759 // demanded by this shuffle are an identity mask, then this shuffle is
1760 // unnecessary.
1761 //
1762 // We are assuming canonical form for the mask, so the source vector is
1763 // operand 0 and operand 1 is not used.
1764 //
1765 // Note that if an element is demanded and this shuffle mask is undefined
1766 // for that element, then the shuffle is not considered an identity
1767 // operation. The shuffle prevents poison from the operand vector from
1768 // leaking to the result by replacing poison with an undefined value.
1769 if (VWidth == OpWidth) {
1770 bool IsIdentityShuffle = true;
1771 for (unsigned i = 0; i < VWidth; i++) {
1772 unsigned MaskVal = Shuffle->getMaskValue(i);
1773 if (DemandedElts[i] && i != MaskVal) {
1774 IsIdentityShuffle = false;
1775 break;
1776 }
1777 }
1778 if (IsIdentityShuffle)
1779 return Shuffle->getOperand(0);
1780 }
1781
1782 bool NewPoisonElts = false;
1783 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1784 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1785 bool LHSUniform = true;
1786 bool RHSUniform = true;
1787 for (unsigned i = 0; i < VWidth; i++) {
1788 unsigned MaskVal = Shuffle->getMaskValue(i);
1789 if (MaskVal == -1u) {
1790 PoisonElts.setBit(i);
1791 } else if (!DemandedElts[i]) {
1792 NewPoisonElts = true;
1793 PoisonElts.setBit(i);
1794 } else if (MaskVal < OpWidth) {
1795 if (LHSPoisonElts[MaskVal]) {
1796 NewPoisonElts = true;
1797 PoisonElts.setBit(i);
1798 } else {
1799 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1800 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1801 LHSUniform = LHSUniform && (MaskVal == i);
1802 }
1803 } else {
1804 if (RHSPoisonElts[MaskVal - OpWidth]) {
1805 NewPoisonElts = true;
1806 PoisonElts.setBit(i);
1807 } else {
1808 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1809 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1810 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1811 }
1812 }
1813 }
1814
1815 // Try to transform shuffle with constant vector and single element from
1816 // this constant vector to single insertelement instruction.
1817 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1818 // insertelement V, C[ci], ci-n
1819 if (OpWidth ==
1820 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1821 Value *Op = nullptr;
1822 Constant *Value = nullptr;
1823 unsigned Idx = -1u;
1824
1825 // Find constant vector with the single element in shuffle (LHS or RHS).
1826 if (LHSIdx < OpWidth && RHSUniform) {
1827 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1828 Op = Shuffle->getOperand(1);
1829 Value = CV->getOperand(LHSValIdx);
1830 Idx = LHSIdx;
1831 }
1832 }
1833 if (RHSIdx < OpWidth && LHSUniform) {
1834 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1835 Op = Shuffle->getOperand(0);
1836 Value = CV->getOperand(RHSValIdx);
1837 Idx = RHSIdx;
1838 }
1839 }
1840 // Found constant vector with single element - convert to insertelement.
1841 if (Op && Value) {
1843 Op, Value, ConstantInt::get(Type::getInt64Ty(I->getContext()), Idx),
1844 Shuffle->getName());
1845 InsertNewInstWith(New, Shuffle->getIterator());
1846 return New;
1847 }
1848 }
1849 if (NewPoisonElts) {
1850 // Add additional discovered undefs.
1852 for (unsigned i = 0; i < VWidth; ++i) {
1853 if (PoisonElts[i])
1855 else
1856 Elts.push_back(Shuffle->getMaskValue(i));
1857 }
1858 Shuffle->setShuffleMask(Elts);
1859 MadeChange = true;
1860 }
1861 break;
1862 }
1863 case Instruction::Select: {
1864 // If this is a vector select, try to transform the select condition based
1865 // on the current demanded elements.
1867 if (Sel->getCondition()->getType()->isVectorTy()) {
1868 // TODO: We are not doing anything with PoisonElts based on this call.
1869 // It is overwritten below based on the other select operands. If an
1870 // element of the select condition is known undef, then we are free to
1871 // choose the output value from either arm of the select. If we know that
1872 // one of those values is undef, then the output can be undef.
1873 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1874 }
1875
1876 // Next, see if we can transform the arms of the select.
1877 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1878 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1879 for (unsigned i = 0; i < VWidth; i++) {
1880 Constant *CElt = CV->getAggregateElement(i);
1881
1882 // isNullValue() always returns false when called on a ConstantExpr.
1883 if (CElt->isNullValue())
1884 DemandedLHS.clearBit(i);
1885 else if (CElt->isOneValue())
1886 DemandedRHS.clearBit(i);
1887 }
1888 }
1889
1890 simplifyAndSetOp(I, 1, DemandedLHS, PoisonElts2);
1891 simplifyAndSetOp(I, 2, DemandedRHS, PoisonElts3);
1892
1893 // Output elements are undefined if the element from each arm is undefined.
1894 // TODO: This can be improved. See comment in select condition handling.
1895 PoisonElts = PoisonElts2 & PoisonElts3;
1896 break;
1897 }
1898 case Instruction::BitCast: {
1899 // Vector->vector casts only.
1900 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1901 if (!VTy) break;
1902 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1903 APInt InputDemandedElts(InVWidth, 0);
1904 PoisonElts2 = APInt(InVWidth, 0);
1905 unsigned Ratio;
1906
1907 if (VWidth == InVWidth) {
1908 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1909 // elements as are demanded of us.
1910 Ratio = 1;
1911 InputDemandedElts = DemandedElts;
1912 } else if ((VWidth % InVWidth) == 0) {
1913 // If the number of elements in the output is a multiple of the number of
1914 // elements in the input then an input element is live if any of the
1915 // corresponding output elements are live.
1916 Ratio = VWidth / InVWidth;
1917 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1918 if (DemandedElts[OutIdx])
1919 InputDemandedElts.setBit(OutIdx / Ratio);
1920 } else if ((InVWidth % VWidth) == 0) {
1921 // If the number of elements in the input is a multiple of the number of
1922 // elements in the output then an input element is live if the
1923 // corresponding output element is live.
1924 Ratio = InVWidth / VWidth;
1925 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1926 if (DemandedElts[InIdx / Ratio])
1927 InputDemandedElts.setBit(InIdx);
1928 } else {
1929 // Unsupported so far.
1930 break;
1931 }
1932
1933 simplifyAndSetOp(I, 0, InputDemandedElts, PoisonElts2);
1934
1935 if (VWidth == InVWidth) {
1936 PoisonElts = PoisonElts2;
1937 } else if ((VWidth % InVWidth) == 0) {
1938 // If the number of elements in the output is a multiple of the number of
1939 // elements in the input then an output element is undef if the
1940 // corresponding input element is undef.
1941 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1942 if (PoisonElts2[OutIdx / Ratio])
1943 PoisonElts.setBit(OutIdx);
1944 } else if ((InVWidth % VWidth) == 0) {
1945 // If the number of elements in the input is a multiple of the number of
1946 // elements in the output then an output element is undef if all of the
1947 // corresponding input elements are undef.
1948 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1949 APInt SubUndef = PoisonElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1950 if (SubUndef.popcount() == Ratio)
1951 PoisonElts.setBit(OutIdx);
1952 }
1953 } else {
1954 llvm_unreachable("Unimp");
1955 }
1956 break;
1957 }
1958 case Instruction::FPTrunc:
1959 case Instruction::FPExt:
1960 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1961 break;
1962
1963 case Instruction::Call: {
1965 if (!II) break;
1966 switch (II->getIntrinsicID()) {
1967 case Intrinsic::masked_gather: // fallthrough
1968 case Intrinsic::masked_load: {
1969 // Subtlety: If we load from a pointer, the pointer must be valid
1970 // regardless of whether the element is demanded. Doing otherwise risks
1971 // segfaults which didn't exist in the original program.
1972 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1973 DemandedPassThrough(DemandedElts);
1974 if (auto *CMask = dyn_cast<Constant>(II->getOperand(1))) {
1975 for (unsigned i = 0; i < VWidth; i++) {
1976 if (Constant *CElt = CMask->getAggregateElement(i)) {
1977 if (CElt->isNullValue())
1978 DemandedPtrs.clearBit(i);
1979 else if (CElt->isAllOnesValue())
1980 DemandedPassThrough.clearBit(i);
1981 }
1982 }
1983 }
1984
1985 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1986 simplifyAndSetOp(II, 0, DemandedPtrs, PoisonElts2);
1987 simplifyAndSetOp(II, 2, DemandedPassThrough, PoisonElts3);
1988
1989 // Output elements are undefined if the element from both sources are.
1990 // TODO: can strengthen via mask as well.
1991 PoisonElts = PoisonElts2 & PoisonElts3;
1992 break;
1993 }
1994 default: {
1995 // Handle target specific intrinsics
1996 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1997 *II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
1998 simplifyAndSetOp);
1999 if (V)
2000 return *V;
2001 break;
2002 }
2003 } // switch on IntrinsicID
2004 break;
2005 } // case Call
2006 } // switch on Opcode
2007
2008 // TODO: We bail completely on integer div/rem and shifts because they have
2009 // UB/poison potential, but that should be refined.
2010 BinaryOperator *BO;
2011 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
2012 Value *X = BO->getOperand(0);
2013 Value *Y = BO->getOperand(1);
2014
2015 // Look for an equivalent binop except that one operand has been shuffled.
2016 // If the demand for this binop only includes elements that are the same as
2017 // the other binop, then we may be able to replace this binop with a use of
2018 // the earlier one.
2019 //
2020 // Example:
2021 // %other_bo = bo (shuf X, {0}), Y
2022 // %this_extracted_bo = extelt (bo X, Y), 0
2023 // -->
2024 // %other_bo = bo (shuf X, {0}), Y
2025 // %this_extracted_bo = extelt %other_bo, 0
2026 //
2027 // TODO: Handle demand of an arbitrary single element or more than one
2028 // element instead of just element 0.
2029 // TODO: Unlike general demanded elements transforms, this should be safe
2030 // for any (div/rem/shift) opcode too.
2031 if (DemandedElts == 1 && !X->hasOneUse() && !Y->hasOneUse() &&
2032 BO->hasOneUse() ) {
2033
2034 auto findShufBO = [&](bool MatchShufAsOp0) -> User * {
2035 // Try to use shuffle-of-operand in place of an operand:
2036 // bo X, Y --> bo (shuf X), Y
2037 // bo X, Y --> bo X, (shuf Y)
2038
2039 Value *OtherOp = MatchShufAsOp0 ? Y : X;
2040 if (!OtherOp->hasUseList())
2041 return nullptr;
2042
2043 BinaryOperator::BinaryOps Opcode = BO->getOpcode();
2044 Value *ShufOp = MatchShufAsOp0 ? X : Y;
2045
2046 for (User *U : OtherOp->users()) {
2047 ArrayRef<int> Mask;
2048 auto Shuf = m_Shuffle(m_Specific(ShufOp), m_Value(), m_Mask(Mask));
2049 if (BO->isCommutative()
2050 ? match(U, m_c_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
2051 : MatchShufAsOp0
2052 ? match(U, m_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
2053 : match(U, m_BinOp(Opcode, m_Specific(OtherOp), Shuf)))
2054 if (match(Mask, m_ZeroMask()) && Mask[0] != PoisonMaskElem)
2055 if (DT.dominates(U, I))
2056 return U;
2057 }
2058 return nullptr;
2059 };
2060
2061 User *ShufBO = findShufBO(/* MatchShufAsOp0 */ true);
2062 if (!ShufBO)
2063 ShufBO = findShufBO(/* MatchShufAsOp0 */ false);
2064 if (ShufBO) {
2065 auto *ShufBOI = cast<Instruction>(ShufBO);
2066 ShufBOI->andIRFlags(BO);
2067 Worklist.add(ShufBOI);
2068 return ShufBO;
2069 }
2070 }
2071
2072 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
2073 simplifyAndSetOp(I, 1, DemandedElts, PoisonElts2);
2074
2075 // Output elements are undefined if both are undefined. Consider things
2076 // like undef & 0. The result is known zero, not undef.
2077 PoisonElts &= PoisonElts2;
2078 }
2079
2080 // If we've proven all of the lanes poison, return a poison value.
2081 // TODO: Intersect w/demanded lanes
2082 if (PoisonElts.isAllOnes())
2083 return PoisonValue::get(I->getType());
2084
2085 return MadeChange ? I : nullptr;
2086}
2087
2088/// For floating-point classes that resolve to a single bit pattern, return that
2089/// value.
2091 bool IsCanonicalizing = false) {
2092 if (Mask == fcNone)
2093 return PoisonValue::get(Ty);
2094
2095 if (Mask == fcPosZero)
2096 return Constant::getNullValue(Ty);
2097
2098 // TODO: Support aggregate types that are allowed by FPMathOperator.
2099 if (Ty->isAggregateType())
2100 return nullptr;
2101
2102 // Turn any possible snans into quiet if we can.
2103 if (Mask == fcNan && IsCanonicalizing)
2104 return ConstantFP::getQNaN(Ty);
2105
2106 switch (Mask) {
2107 case fcNegZero:
2108 return ConstantFP::getZero(Ty, true);
2109 case fcPosInf:
2110 return ConstantFP::getInfinity(Ty);
2111 case fcNegInf:
2112 return ConstantFP::getInfinity(Ty, true);
2113 case fcQNan:
2114 // Payload bits cannot be dropped for pure signbit operations.
2115 return IsCanonicalizing ? ConstantFP::getQNaN(Ty) : nullptr;
2116 default:
2117 return nullptr;
2118 }
2119}
2120
2121/// Perform multiple-use aware simplfications for fabs(\p Src). Returns a
2122/// replacement value if it's simplified, otherwise nullptr. Updates \p Known
2123/// with the known fpclass if not simplified.
2125 FPClassTest DemandedMask,
2126 KnownFPClass KnownSrc, bool NSZ) {
2127 if ((DemandedMask & fcNan) == fcNone)
2128 KnownSrc.knownNot(fcNan);
2129 if ((DemandedMask & fcInf) == fcNone)
2130 KnownSrc.knownNot(fcInf);
2131
2132 if (KnownSrc.getSignBit() == false ||
2133 ((DemandedMask & fcNan) == fcNone && KnownSrc.isKnownNever(fcNegative)))
2134 return Src;
2135
2136 // If the only sign bit difference is due to -0, ignore it with nsz
2137 if (NSZ &&
2139 return Src;
2140
2141 Known = KnownFPClass::fabs(KnownSrc);
2142 Known.knownNot(~DemandedMask);
2143 return nullptr;
2144}
2145
2146/// Try to set an inferred no-nans or no-infs in \p FMF. \p ValidResults is a
2147/// mask of known valid results for the operator (already computed from the
2148/// result, and the known operand inputs in \p Known)
2150 FPClassTest ValidResults,
2152 if (!FMF.noNaNs() && (ValidResults & fcNan) == fcNone) {
2153 if (all_of(Known, [](const KnownFPClass KnownSrc) {
2154 return KnownSrc.isKnownNeverNaN();
2155 }))
2156 FMF.setNoNaNs();
2157 }
2158
2159 if (!FMF.noInfs() && (ValidResults & fcInf) == fcNone) {
2160 if (all_of(Known, [](const KnownFPClass KnownSrc) {
2161 return KnownSrc.isKnownNeverInfinity();
2162 }))
2163 FMF.setNoInfs();
2164 }
2165
2166 return FMF;
2167}
2168
2170 FastMathFlags FMF) {
2171 if (FMF.noNaNs())
2172 DemandedMask &= ~fcNan;
2173
2174 if (FMF.noInfs())
2175 DemandedMask &= ~fcInf;
2176 return DemandedMask;
2177}
2178
2179/// Apply epilog fixups to a floating-point intrinsic. See if the result can
2180/// fold to a constant, or apply fast math flags.
2182 FastMathFlags FMF,
2183 FPClassTest DemandedMask,
2185 ArrayRef<KnownFPClass> KnownSrcs) {
2186 FPClassTest ValidResults = DemandedMask & Known.getKnownFPClasses();
2187 Constant *SingleVal = getFPClassConstant(FPOp->getType(), ValidResults,
2188 /*IsCanonicalizing=*/true);
2189 if (SingleVal)
2190 return SingleVal;
2191
2192 FastMathFlags InferredFMF =
2193 inferFastMathValueFlags(FMF, ValidResults, KnownSrcs);
2194 if (InferredFMF != FMF) {
2196 FPOp->setFastMathFlags(InferredFMF);
2197 return FPOp;
2198 }
2199
2200 return nullptr;
2201}
2202
2203/// Perform multiple-use aware simplfications for fneg(fabs(\p Src)). Returns a
2204/// replacement value if it's simplified, otherwise nullptr. Updates \p Known
2205/// with the known fpclass if not simplified.
2207 FPClassTest DemandedMask,
2208 KnownFPClass KnownSrc, bool NSZ) {
2209 if ((DemandedMask & fcNan) == fcNone)
2210 KnownSrc.knownNot(fcNan);
2211 if ((DemandedMask & fcInf) == fcNone)
2212 KnownSrc.knownNot(fcInf);
2213
2214 // If the source value is known negative, we can directly fold to it.
2215 if (KnownSrc.getSignBit() == true)
2216 return Src;
2217
2218 // If the only sign bit difference is for 0, ignore it with nsz.
2219 if (NSZ &&
2221 return Src;
2222
2224 Known.knownNot(~DemandedMask);
2225 return nullptr;
2226}
2227
2229 FPClassTest DemandedMask,
2230 KnownFPClass KnownSrc,
2231 bool NSZ) {
2232 if (NSZ) {
2233 constexpr FPClassTest NegOrZero = fcNegative | fcPosZero;
2234 constexpr FPClassTest PosOrZero = fcPositive | fcNegZero;
2235
2236 if ((DemandedMask & ~NegOrZero) == fcNone &&
2237 KnownSrc.isKnownAlways(NegOrZero))
2238 return MagSrc;
2239
2240 if ((DemandedMask & ~PosOrZero) == fcNone &&
2241 KnownSrc.isKnownAlways(PosOrZero))
2242 return MagSrc;
2243 } else {
2244 if ((DemandedMask & ~fcNegative) == fcNone && KnownSrc.getSignBit() == true)
2245 return MagSrc;
2246
2247 if ((DemandedMask & ~fcPositive) == fcNone &&
2248 KnownSrc.getSignBit() == false)
2249 return MagSrc;
2250 }
2251
2252 return nullptr;
2253}
2254
2255static Value *
2257 const CallInst *CI, FPClassTest DemandedMask,
2258 KnownFPClass KnownLHS, KnownFPClass KnownRHS,
2259 const Function &F, bool NSZ) {
2260 bool OrderedZeroSign = !NSZ;
2261
2263 switch (IID) {
2264 case Intrinsic::maximum: {
2266
2267 // If one operand is known greater than the other, it must be that
2268 // operand unless the other is a nan.
2270 KnownRHS.getKnownFPClasses(),
2271 OrderedZeroSign) &&
2272 KnownRHS.isKnownNever(fcNan))
2273 return CI->getArgOperand(0);
2274
2276 KnownRHS.getKnownFPClasses(),
2277 OrderedZeroSign) &&
2278 KnownLHS.isKnownNever(fcNan))
2279 return CI->getArgOperand(1);
2280
2281 break;
2282 }
2283 case Intrinsic::minimum: {
2285
2286 // If one operand is known less than the other, it must be that operand
2287 // unless the other is a nan.
2289 KnownRHS.getKnownFPClasses(),
2290 OrderedZeroSign) &&
2291 KnownRHS.isKnownNever(fcNan))
2292 return CI->getArgOperand(0);
2293
2295 KnownRHS.getKnownFPClasses(),
2296 OrderedZeroSign) &&
2297 KnownLHS.isKnownNever(fcNan))
2298 return CI->getArgOperand(1);
2299
2300 break;
2301 }
2302 case Intrinsic::maxnum:
2303 case Intrinsic::maximumnum: {
2304 OpKind = IID == Intrinsic::maxnum ? KnownFPClass::MinMaxKind::maxnum
2306
2308 KnownRHS.getKnownFPClasses(),
2309 OrderedZeroSign) &&
2310 KnownLHS.isKnownNever(fcNan))
2311 return CI->getArgOperand(0);
2312
2314 KnownRHS.getKnownFPClasses(),
2315 OrderedZeroSign) &&
2316 KnownRHS.isKnownNever(fcNan))
2317 return CI->getArgOperand(1);
2318
2319 break;
2320 }
2321 case Intrinsic::minnum:
2322 case Intrinsic::minimumnum: {
2323 OpKind = IID == Intrinsic::minnum ? KnownFPClass::MinMaxKind::minnum
2325
2327 KnownRHS.getKnownFPClasses(),
2328 OrderedZeroSign) &&
2329 KnownLHS.isKnownNever(fcNan))
2330 return CI->getArgOperand(0);
2331
2333 KnownRHS.getKnownFPClasses(),
2334 OrderedZeroSign) &&
2335 KnownRHS.isKnownNever(fcNan))
2336 return CI->getArgOperand(1);
2337
2338 break;
2339 }
2340 default:
2341 llvm_unreachable("not a min/max intrinsic");
2342 }
2343
2344 Type *EltTy = CI->getType()->getScalarType();
2345 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2346 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, OpKind, Mode);
2347 Known.knownNot(~DemandedMask);
2348
2349 return getFPClassConstant(CI->getType(), Known.getKnownFPClasses(),
2350 /*IsCanonicalizing=*/true);
2351}
2352
2353static Value *
2355 FastMathFlags FMF, FPClassTest DemandedMask,
2356 KnownFPClass &Known, const SimplifyQuery &SQ,
2357 unsigned Depth) {
2358
2359 FPClassTest SrcDemandedMask = DemandedMask;
2360 if (DemandedMask & fcNan)
2361 SrcDemandedMask |= fcNan;
2362
2363 // Zero results may have been rounded from subnormal or normal sources.
2364 if (DemandedMask & fcNegZero)
2365 SrcDemandedMask |= fcNegSubnormal | fcNegNormal;
2366 if (DemandedMask & fcPosZero)
2367 SrcDemandedMask |= fcPosSubnormal | fcPosNormal;
2368
2369 // Subnormal results may have been normal in the source type
2370 if (DemandedMask & fcNegSubnormal)
2371 SrcDemandedMask |= fcNegNormal;
2372 if (DemandedMask & fcPosSubnormal)
2373 SrcDemandedMask |= fcPosNormal;
2374
2375 if (DemandedMask & fcPosInf)
2376 SrcDemandedMask |= fcPosNormal;
2377 if (DemandedMask & fcNegInf)
2378 SrcDemandedMask |= fcNegNormal;
2379
2380 KnownFPClass KnownSrc;
2381 if (IC.SimplifyDemandedFPClass(&I, 0, SrcDemandedMask, KnownSrc, SQ,
2382 Depth + 1))
2383 return &I;
2384
2385 Known = KnownFPClass::fptrunc(KnownSrc);
2386 Known.knownNot(~DemandedMask);
2387
2388 return simplifyDemandedFPClassResult(&I, FMF, DemandedMask, Known,
2389 {KnownSrc});
2390}
2391
2393 FPClassTest DemandedMask,
2395 const SimplifyQuery &SQ,
2396 unsigned Depth) {
2397 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2398 assert(Known == KnownFPClass() && "expected uninitialized state");
2399
2400 Type *VTy = I->getType();
2401
2402 FastMathFlags FMF;
2403 if (auto *FPOp = dyn_cast<FPMathOperator>(I)) {
2404 FMF = FPOp->getFastMathFlags();
2405 DemandedMask = adjustDemandedMaskFromFlags(DemandedMask, FMF);
2406 }
2407
2408 switch (I->getOpcode()) {
2409 case Instruction::FNeg: {
2410 // Special case fneg(fabs(x))
2411
2412 Value *FNegSrc = I->getOperand(0);
2413 Value *FNegFAbsSrc;
2414 if (match(FNegSrc, m_OneUse(m_FAbs(m_Value(FNegFAbsSrc))))) {
2415 KnownFPClass KnownSrc;
2417 llvm::unknown_sign(DemandedMask), KnownSrc,
2418 SQ, Depth + 1))
2419 return I;
2420
2421 FastMathFlags FabsFMF = cast<FPMathOperator>(FNegSrc)->getFastMathFlags();
2422 FPClassTest ThisDemandedMask =
2423 adjustDemandedMaskFromFlags(DemandedMask, FabsFMF);
2424
2425 bool IsNSZ = FMF.noSignedZeros() || FabsFMF.noSignedZeros();
2426 if (Value *Simplified = simplifyDemandedFPClassFnegFabs(
2427 Known, FNegFAbsSrc, ThisDemandedMask, KnownSrc, IsNSZ))
2428 return Simplified;
2429
2430 if ((ThisDemandedMask & fcNan) == fcNone)
2431 KnownSrc.knownNot(fcNan);
2432 if ((ThisDemandedMask & fcInf) == fcNone)
2433 KnownSrc.knownNot(fcInf);
2434
2435 // fneg(fabs(x)) => fneg(x)
2436 if (KnownSrc.getSignBit() == false)
2437 return replaceOperand(*I, 0, FNegFAbsSrc);
2438
2439 // fneg(fabs(x)) => fneg(x), ignoring -0 if nsz.
2440 if (IsNSZ &&
2442 return replaceOperand(*I, 0, FNegFAbsSrc);
2443
2444 break;
2445 }
2446
2447 if (SimplifyDemandedFPClass(I, 0, llvm::fneg(DemandedMask), Known, SQ,
2448 Depth + 1))
2449 return I;
2450 Known.fneg();
2451 Known.knownNot(~DemandedMask);
2452 break;
2453 }
2454 case Instruction::FAdd:
2455 case Instruction::FSub: {
2456 KnownFPClass KnownLHS, KnownRHS;
2457
2458 // fadd x, x can be handled more aggressively.
2459 if (I->getOperand(0) == I->getOperand(1) &&
2460 I->getOpcode() == Instruction::FAdd &&
2461 isGuaranteedNotToBeUndef(I->getOperand(0), SQ.AC, SQ.CxtI, SQ.DT,
2462 Depth + 1)) {
2463 Type *EltTy = VTy->getScalarType();
2464 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2465
2466 FPClassTest SrcDemandedMask = DemandedMask;
2467 if (DemandedMask & fcNan)
2468 SrcDemandedMask |= fcNan;
2469
2470 // Doubling a subnormal could have resulted in a normal value.
2471 if (DemandedMask & fcPosNormal)
2472 SrcDemandedMask |= fcPosSubnormal;
2473 if (DemandedMask & fcNegNormal)
2474 SrcDemandedMask |= fcNegSubnormal;
2475
2476 // Doubling a subnormal may produce 0 if FTZ/DAZ.
2477 if (Mode != DenormalMode::getIEEE()) {
2478 if (DemandedMask & fcPosZero) {
2479 SrcDemandedMask |= fcPosSubnormal;
2480
2481 if (Mode.inputsMayBePositiveZero() || Mode.outputsMayBePositiveZero())
2482 SrcDemandedMask |= fcNegSubnormal;
2483 }
2484
2485 if (DemandedMask & fcNegZero)
2486 SrcDemandedMask |= fcNegSubnormal;
2487 }
2488
2489 // Doubling a normal could have resulted in an infinity.
2490 if (DemandedMask & fcPosInf)
2491 SrcDemandedMask |= fcPosNormal;
2492 if (DemandedMask & fcNegInf)
2493 SrcDemandedMask |= fcNegNormal;
2494
2495 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ,
2496 Depth + 1))
2497 return I;
2498
2499 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
2500 KnownRHS = KnownLHS;
2501 } else {
2502 FPClassTest SrcDemandedMask = fcFinite;
2503
2504 // inf + (-inf) = nan
2505 if (DemandedMask & fcNan)
2506 SrcDemandedMask |= fcNan | fcInf;
2507
2508 if (DemandedMask & fcInf)
2509 SrcDemandedMask |= fcInf;
2510
2511 if (SimplifyDemandedFPClass(I, 1, SrcDemandedMask, KnownRHS, SQ,
2512 Depth + 1) ||
2513 SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ,
2514 Depth + 1))
2515 return I;
2516
2517 Type *EltTy = VTy->getScalarType();
2518 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2519
2520 Known = I->getOpcode() == Instruction::FAdd
2521 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
2522 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
2523 }
2524
2525 Known.knownNot(~DemandedMask);
2526
2527 if (Constant *SingleVal = getFPClassConstant(VTy, Known.getKnownFPClasses(),
2528 /*IsCanonicalizing=*/true))
2529 return SingleVal;
2530
2531 // Propagate known result to simplify edge case checks.
2532 bool ResultNotNan = (DemandedMask & fcNan) == fcNone;
2533
2534 // With nnan: X + {+/-}Inf --> {+/-}Inf
2535 if (ResultNotNan && I->getOpcode() == Instruction::FAdd &&
2536 KnownRHS.isKnownAlways(fcInf | fcNan) && KnownLHS.isKnownNever(fcNan))
2537 return I->getOperand(1);
2538
2539 // With nnan: {+/-}Inf + X --> {+/-}Inf
2540 // With nnan: {+/-}Inf - X --> {+/-}Inf
2541 if (ResultNotNan && KnownLHS.isKnownAlways(fcInf | fcNan) &&
2542 KnownRHS.isKnownNever(fcNan))
2543 return I->getOperand(0);
2544
2546 FMF, Known.getKnownFPClasses(), {KnownLHS, KnownRHS});
2547 if (InferredFMF != FMF) {
2548 I->setFastMathFlags(InferredFMF);
2549 return I;
2550 }
2551
2552 return nullptr;
2553 }
2554 case Instruction::FMul: {
2555 KnownFPClass KnownLHS, KnownRHS;
2556
2557 Value *X = I->getOperand(0);
2558 Value *Y = I->getOperand(1);
2559
2560 FPClassTest SrcDemandedMask =
2561 DemandedMask & (fcNan | fcZero | fcSubnormal | fcNormal);
2562
2563 if (DemandedMask & fcInf) {
2564 // mul x, inf = inf
2565 // mul large_x, large_y = inf
2566 SrcDemandedMask |= fcSubnormal | fcNormal | fcInf;
2567 }
2568
2569 if (DemandedMask & fcNan) {
2570 // mul +/-inf, 0 => nan
2571 SrcDemandedMask |= fcZero | fcInf | fcNan;
2572
2573 // TODO: Mode check
2574 // mul +/-inf, sub => nan if daz
2575 SrcDemandedMask |= fcSubnormal;
2576 }
2577
2578 // mul normal, subnormal = normal
2579 // Normal inputs may result in underflow.
2580 if (DemandedMask & (fcNormal | fcSubnormal))
2581 SrcDemandedMask |= fcNormal | fcSubnormal;
2582
2583 if (DemandedMask & fcZero)
2584 SrcDemandedMask |= fcNormal | fcSubnormal;
2585
2586 if (X == Y &&
2587 isGuaranteedNotToBeUndef(X, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1)) {
2588 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ,
2589 Depth + 1))
2590 return I;
2591 Type *EltTy = VTy->getScalarType();
2592
2593 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2594 Known = KnownFPClass::square(KnownLHS, Mode);
2595 Known.knownNot(~DemandedMask);
2596
2597 if (Constant *Folded = getFPClassConstant(VTy, Known.getKnownFPClasses(),
2598 /*IsCanonicalizing=*/true))
2599 return Folded;
2600
2601 if (Known.isKnownAlways(fcPosZero | fcPosInf | fcNan) &&
2602 KnownLHS.isKnownNever(fcSubnormal | fcNormal)) {
2603 // We can skip the fabs if the source was already known positive.
2604 if (KnownLHS.isKnownAlways(fcPositive))
2605 return X;
2606
2607 // => fabs(x), in case this was a -inf or -0.
2608 // Note: Dropping canonicalize.
2610 Builder.SetInsertPoint(I);
2611 Value *Fabs = Builder.CreateFAbs(X, FMF);
2612 Fabs->takeName(I);
2613 return Fabs;
2614 }
2615
2616 return nullptr;
2617 }
2618
2619 if (SimplifyDemandedFPClass(I, 1, SrcDemandedMask, KnownRHS, SQ,
2620 Depth + 1) ||
2621 SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownLHS, SQ, Depth + 1))
2622 return I;
2623
2624 if (FMF.noInfs()) {
2625 // Flag implies inputs cannot be infinity.
2626 KnownLHS.knownNot(fcInf);
2627 KnownRHS.knownNot(fcInf);
2628 }
2629
2630 bool NonNanResult = (DemandedMask & fcNan) == fcNone;
2631
2632 // With no-nans/no-infs:
2633 // X * 0.0 --> copysign(0.0, X)
2634 // X * -0.0 --> copysign(0.0, -X)
2635 if ((NonNanResult || KnownLHS.isKnownNeverInfOrNaN()) &&
2636 KnownRHS.isKnownAlways(fcPosZero | fcNan)) {
2638 Builder.SetInsertPoint(I);
2639
2640 // => copysign(+0, lhs)
2641 // Note: Dropping canonicalize
2642 Value *Copysign = Builder.CreateCopySign(Y, X, FMF);
2643 Copysign->takeName(I);
2644 return Copysign;
2645 }
2646
2647 if (KnownLHS.isKnownAlways(fcPosZero | fcNan) &&
2648 (NonNanResult || KnownRHS.isKnownNeverInfOrNaN())) {
2650 Builder.SetInsertPoint(I);
2651
2652 // => copysign(+0, rhs)
2653 // Note: Dropping canonicalize
2654 Value *Copysign = Builder.CreateCopySign(X, Y, FMF);
2655 Copysign->takeName(I);
2656 return Copysign;
2657 }
2658
2659 if ((NonNanResult || KnownLHS.isKnownNeverInfOrNaN()) &&
2660 KnownRHS.isKnownAlways(fcNegZero | fcNan)) {
2662 Builder.SetInsertPoint(I);
2663
2664 // => copysign(0, fneg(lhs))
2665 // Note: Dropping canonicalize
2666 Value *Copysign =
2667 Builder.CreateCopySign(Y, Builder.CreateFNegFMF(X, FMF), FMF);
2668 Copysign->takeName(I);
2669 return Copysign;
2670 }
2671
2672 if (KnownLHS.isKnownAlways(fcNegZero | fcNan) &&
2673 (NonNanResult || KnownRHS.isKnownNeverInfOrNaN())) {
2675 Builder.SetInsertPoint(I);
2676
2677 // => copysign(+0, fneg(rhs))
2678 // Note: Dropping canonicalize
2679 Value *Copysign =
2680 Builder.CreateCopySign(X, Builder.CreateFNegFMF(Y, FMF), FMF);
2681 Copysign->takeName(I);
2682 return Copysign;
2683 }
2684
2685 Type *EltTy = VTy->getScalarType();
2686 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2687
2688 if (KnownLHS.isKnownAlways(fcInf | fcNan) &&
2689 (KnownRHS.isKnownNeverNaN() &&
2690 KnownRHS.cannotBeOrderedGreaterEqZero(Mode))) {
2692 Builder.SetInsertPoint(I);
2693
2694 // Note: Dropping canonicalize
2695 Value *Neg = Builder.CreateFNegFMF(X, FMF);
2696 Neg->takeName(I);
2697 return Neg;
2698 }
2699
2700 if (KnownRHS.isKnownAlways(fcInf | fcNan) &&
2701 (KnownLHS.isKnownNeverNaN() &&
2702 KnownLHS.cannotBeOrderedGreaterEqZero(Mode))) {
2704 Builder.SetInsertPoint(I);
2705
2706 // Note: Dropping canonicalize
2707 Value *Neg = Builder.CreateFNegFMF(Y, FMF);
2708 Neg->takeName(I);
2709 return Neg;
2710 }
2711
2712 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
2713 Known.knownNot(~DemandedMask);
2714
2715 if (Constant *SingleVal = getFPClassConstant(VTy, Known.getKnownFPClasses(),
2716 /*IsCanonicalizing=*/true))
2717 return SingleVal;
2718
2720 FMF, Known.getKnownFPClasses(), {KnownLHS, KnownRHS});
2721 if (InferredFMF != FMF) {
2722 I->setFastMathFlags(InferredFMF);
2723 return I;
2724 }
2725
2726 return nullptr;
2727 }
2728 case Instruction::FDiv: {
2729 Value *X = I->getOperand(0);
2730 Value *Y = I->getOperand(1);
2731 if (X == Y &&
2732 isGuaranteedNotToBeUndef(X, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1)) {
2733 // If the source is 0, inf or nan, the result is a nan
2735 Builder.SetInsertPoint(I);
2736
2737 Value *IsZeroOrNan = Builder.CreateFCmpFMF(
2738 FCmpInst::FCMP_UEQ, I->getOperand(0), ConstantFP::getZero(VTy), FMF);
2739
2740 Value *Fabs = Builder.CreateFAbs(I->getOperand(0), FMF);
2741 Value *IsInfOrNan = Builder.CreateFCmpFMF(
2743
2744 Value *IsInfOrZeroOrNan = Builder.CreateOr(IsInfOrNan, IsZeroOrNan);
2745
2746 return Builder.CreateSelectFMFWithUnknownProfile(
2747 IsInfOrZeroOrNan, ConstantFP::getQNaN(VTy),
2748 ConstantFP::get(
2750 FMF, DEBUG_TYPE);
2751 }
2752
2753 Type *EltTy = VTy->getScalarType();
2754 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2755
2756 // Every output class could require denormal inputs (except for the
2757 // degenerate case of only-nan results, without DAZ).
2758 FPClassTest SrcDemandedMask = (DemandedMask & fcNan) | fcSubnormal;
2759
2760 // Normal inputs may result in underflow.
2761 // x / x = 1.0 for non0/inf/nan
2762 // -x = +y / -z
2763 // -x = -y / +z
2764 if (DemandedMask & (fcSubnormal | fcNormal))
2765 SrcDemandedMask |= fcNormal;
2766
2767 if (DemandedMask & fcNan) {
2768 // 0 / 0 = nan
2769 // inf / inf = nan
2770
2771 // Subnormal is added in case of DAZ, but this isn't strictly
2772 // necessary. Every other input class implies a possible subnormal source,
2773 // so this only could matter in the degenerate case of only-nan results.
2774 SrcDemandedMask |= fcZero | fcInf | fcNan;
2775 }
2776
2777 // Zero outputs may be the result of underflow.
2778 if (DemandedMask & fcZero)
2779 SrcDemandedMask |= fcNormal | fcSubnormal;
2780
2781 FPClassTest LHSDemandedMask = SrcDemandedMask;
2782 FPClassTest RHSDemandedMask = SrcDemandedMask;
2783
2784 // 0 / inf = 0
2785 if (DemandedMask & fcZero) {
2786 assert((LHSDemandedMask & fcSubnormal) &&
2787 "should not have to worry about daz here");
2788 LHSDemandedMask |= fcZero;
2789 RHSDemandedMask |= fcInf;
2790 }
2791
2792 // x / 0 = inf
2793 // large_normal / small_normal = inf
2794 // inf / 1 = inf
2795 // large_normal / subnormal = inf
2796 if (DemandedMask & fcInf) {
2797 LHSDemandedMask |= fcInf | fcNormal | fcSubnormal;
2798 RHSDemandedMask |= fcZero | fcSubnormal | fcNormal;
2799 }
2800
2801 KnownFPClass KnownLHS, KnownRHS;
2802 if (SimplifyDemandedFPClass(I, 0, LHSDemandedMask, KnownLHS, SQ,
2803 Depth + 1) ||
2804 SimplifyDemandedFPClass(I, 1, RHSDemandedMask, KnownRHS, SQ, Depth + 1))
2805 return I;
2806
2807 bool ResultNotNan = (DemandedMask & fcNan) == fcNone;
2808 bool ResultNotInf = (DemandedMask & fcInf) == fcNone;
2809
2810 // Replacing 0/x with a zero is only valid when the divisor can't be
2811 // (logical) zero, since 0/0 is NaN -- unless NaN results aren't demanded. A
2812 // subnormal divisor can flush to zero under a flushing denormal mode.
2813 bool CanIgnoreZeroByZeroNan =
2814 ResultNotNan || KnownRHS.isKnownNeverLogicalZero(Mode);
2815
2816 // nsz [+-]0 / x -> 0
2817 if (FMF.noSignedZeros() && KnownLHS.isKnownAlways(fcZero) &&
2818 KnownRHS.isKnownNeverNaN() && CanIgnoreZeroByZeroNan)
2819 return ConstantFP::getZero(VTy);
2820
2821 if (KnownLHS.isKnownAlways(fcPosZero) && KnownRHS.isKnownNeverNaN() &&
2822 CanIgnoreZeroByZeroNan) {
2824 Builder.SetInsertPoint(I);
2825
2826 // nnan +0 / x -> copysign(0, rhs)
2827 // TODO: -0 / x => copysign(0, fneg(rhs))
2828 Value *Copysign = Builder.CreateCopySign(X, Y, FMF);
2829 Copysign->takeName(I);
2830 return Copysign;
2831 }
2832
2833 if (!ResultNotInf &&
2834 ((ResultNotNan || (KnownLHS.isKnownNeverNaN() &&
2835 KnownLHS.isKnownNeverLogicalZero(Mode))) &&
2836 (KnownRHS.isKnownAlways(fcPosZero) ||
2837 (FMF.noSignedZeros() && KnownRHS.isKnownAlways(fcZero))))) {
2839 Builder.SetInsertPoint(I);
2840
2841 // nnan x / 0 => copysign(inf, x);
2842 // nnan nsz x / -0 => copysign(inf, x);
2843 Value *Copysign =
2844 Builder.CreateCopySign(ConstantFP::getInfinity(VTy), X, FMF);
2845 Copysign->takeName(I);
2846 return Copysign;
2847 }
2848
2849 // nnan ninf X / [-]0.0 -> poison
2850 if (ResultNotNan && ResultNotInf && KnownRHS.isKnownAlways(fcZero))
2851 return PoisonValue::get(VTy);
2852
2853 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
2854 Known.knownNot(~DemandedMask);
2855
2856 if (Constant *SingleVal = getFPClassConstant(VTy, Known.getKnownFPClasses(),
2857 /*IsCanonicalizing=*/true))
2858 return SingleVal;
2859
2861 FMF, Known.getKnownFPClasses(), {KnownLHS, KnownRHS});
2862 if (InferredFMF != FMF) {
2863 I->setFastMathFlags(InferredFMF);
2864 return I;
2865 }
2866
2867 return nullptr;
2868 }
2869 case Instruction::FPTrunc:
2870 return simplifyDemandedUseFPClassFPTrunc(*this, *I, FMF, DemandedMask,
2871 Known, SQ, Depth);
2872 case Instruction::FPExt: {
2873 FPClassTest SrcDemandedMask = DemandedMask;
2874 if (DemandedMask & fcNan)
2875 SrcDemandedMask |= fcNan;
2876
2877 // No subnormal result does not imply not-subnormal in the source type.
2878 if ((DemandedMask & fcNegNormal) != fcNone)
2879 SrcDemandedMask |= fcNegSubnormal;
2880 if ((DemandedMask & fcPosNormal) != fcNone)
2881 SrcDemandedMask |= fcPosSubnormal;
2882
2883 KnownFPClass KnownSrc;
2884 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownSrc, SQ, Depth + 1))
2885 return I;
2886
2887 const fltSemantics &DstTy = VTy->getScalarType()->getFltSemantics();
2888 const fltSemantics &SrcTy =
2889 I->getOperand(0)->getType()->getScalarType()->getFltSemantics();
2890
2891 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
2892 Known.knownNot(~DemandedMask);
2893
2894 return simplifyDemandedFPClassResult(I, FMF, DemandedMask, Known,
2895 {KnownSrc});
2896 }
2897 case Instruction::Call: {
2898 CallInst *CI = cast<CallInst>(I);
2899 const Intrinsic::ID IID = CI->getIntrinsicID();
2900 switch (IID) {
2901 case Intrinsic::fabs: {
2902 KnownFPClass KnownSrc;
2903 if (SimplifyDemandedFPClass(I, 0, llvm::inverse_fabs(DemandedMask),
2904 KnownSrc, SQ, Depth + 1))
2905 return I;
2906
2907 if (Value *Simplified = simplifyDemandedFPClassFabs(
2908 Known, CI->getArgOperand(0), DemandedMask, KnownSrc,
2909 FMF.noSignedZeros()))
2910 return Simplified;
2911 break;
2912 }
2913 case Intrinsic::arithmetic_fence:
2914 if (SimplifyDemandedFPClass(I, 0, DemandedMask, Known, SQ, Depth + 1))
2915 return I;
2916 break;
2917 case Intrinsic::copysign: {
2918 // Flip on more potentially demanded classes
2919 const FPClassTest DemandedMaskAnySign = llvm::unknown_sign(DemandedMask);
2920 KnownFPClass KnownMag;
2921 if (SimplifyDemandedFPClass(CI, 0, DemandedMaskAnySign, KnownMag, SQ,
2922 Depth + 1))
2923 return I;
2924
2925 if ((DemandedMask & fcNegative) == DemandedMask) {
2926 // Roundabout way of replacing with fneg(fabs)
2927 CI->setOperand(1, ConstantFP::get(VTy, -1.0));
2928 return I;
2929 }
2930
2931 if ((DemandedMask & fcPositive) == DemandedMask) {
2932 // Roundabout way of replacing with fabs
2933 CI->setOperand(1, ConstantFP::getZero(VTy));
2934 return I;
2935 }
2936
2937 if (Value *Simplified = simplifyDemandedFPClassCopysignMag(
2938 CI->getArgOperand(0), DemandedMask, KnownMag,
2939 FMF.noSignedZeros()))
2940 return Simplified;
2941
2942 KnownFPClass KnownSign =
2944 if (KnownMag.getSignBit() && KnownSign.getSignBit() &&
2945 *KnownMag.getSignBit() == *KnownSign.getSignBit())
2946 return CI->getOperand(0);
2947
2948 // TODO: Call argument attribute not considered
2949 // Input implied not-nan from flag.
2950 if (FMF.noNaNs())
2951 KnownSign.knownNot(fcNan);
2952
2953 if (KnownSign.getSignBit() == false) {
2955 CI->setOperand(1, ConstantFP::getZero(VTy));
2956 return I;
2957 }
2958
2959 if (KnownSign.getSignBit() == true) {
2961 CI->setOperand(1, ConstantFP::get(VTy, -1.0));
2962 return I;
2963 }
2964
2965 Known = KnownFPClass::copysign(KnownMag, KnownSign);
2966 Known.knownNot(~DemandedMask);
2967 break;
2968 }
2969 case Intrinsic::fma:
2970 case Intrinsic::fmuladd: {
2971 // We can't do any simplification on the source besides stripping out
2972 // unneeded nans.
2973 FPClassTest SrcDemandedMask = DemandedMask | ~fcNan;
2974 if (DemandedMask & fcNan)
2975 SrcDemandedMask |= fcNan;
2976
2977 KnownFPClass KnownSrc[3];
2978
2979 Type *EltTy = VTy->getScalarType();
2980 if (CI->getArgOperand(0) == CI->getArgOperand(1) &&
2981 isGuaranteedNotToBeUndef(CI->getArgOperand(0), SQ.AC, SQ.CxtI, SQ.DT,
2982 Depth + 1)) {
2983 if (SimplifyDemandedFPClass(CI, 0, SrcDemandedMask, KnownSrc[0], SQ,
2984 Depth + 1) ||
2985 SimplifyDemandedFPClass(CI, 2, SrcDemandedMask, KnownSrc[2], SQ,
2986 Depth + 1))
2987 return I;
2988
2989 KnownSrc[1] = KnownSrc[0];
2990 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
2991 Known = KnownFPClass::fma_square(KnownSrc[0], KnownSrc[2], Mode);
2992 } else {
2993 for (int OpIdx = 0; OpIdx != 3; ++OpIdx) {
2994 if (SimplifyDemandedFPClass(CI, OpIdx, SrcDemandedMask,
2995 KnownSrc[OpIdx], SQ, Depth + 1))
2996 return CI;
2997 }
2998
2999 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3000 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
3001 }
3002
3003 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3004 {KnownSrc});
3005 }
3006 case Intrinsic::maximum:
3007 case Intrinsic::minimum:
3008 case Intrinsic::maximumnum:
3009 case Intrinsic::minimumnum:
3010 case Intrinsic::maxnum:
3011 case Intrinsic::minnum: {
3012 const bool PropagateNaN =
3013 IID == Intrinsic::maximum || IID == Intrinsic::minimum;
3014
3015 // We can't tell much based on the demanded result without inspecting the
3016 // operands (e.g., a known-positive result could have been clamped), but
3017 // we can still prune known-nan inputs.
3018 FPClassTest SrcDemandedMask =
3019 PropagateNaN && ((DemandedMask & fcNan) == fcNone)
3020 ? DemandedMask | ~fcNan
3021 : fcAllFlags;
3022
3023 KnownFPClass KnownLHS, KnownRHS;
3024 if (SimplifyDemandedFPClass(CI, 1, SrcDemandedMask, KnownRHS, SQ,
3025 Depth + 1) ||
3026 SimplifyDemandedFPClass(CI, 0, SrcDemandedMask, KnownLHS, SQ,
3027 Depth + 1))
3028 return I;
3029
3030 Value *Simplified =
3031 simplifyDemandedFPClassMinMax(Known, IID, CI, DemandedMask, KnownLHS,
3032 KnownRHS, F, FMF.noSignedZeros());
3033 if (Simplified)
3034 return Simplified;
3035
3036 auto *FPOp = cast<FPMathOperator>(CI);
3037
3038 FPClassTest ValidResults = DemandedMask & Known.getKnownFPClasses();
3039 FastMathFlags InferredFMF = FMF;
3040
3041 if (!FMF.noSignedZeros()) {
3042 // Add NSZ flag if we know the result will not be sensitive to the sign
3043 // of 0.
3044 FPClassTest ZeroMask = fcZero;
3045
3046 Type *EltTy = VTy->getScalarType();
3047 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3048 if (Mode != DenormalMode::getIEEE())
3049 ZeroMask |= fcSubnormal;
3050
3051 bool ResultNotLogical0 = (ValidResults & ZeroMask) == fcNone;
3052 if (ResultNotLogical0 || ((KnownLHS.isKnownNeverLogicalNegZero(Mode) ||
3053 KnownRHS.isKnownNeverLogicalPosZero(Mode)) &&
3054 (KnownLHS.isKnownNeverLogicalPosZero(Mode) ||
3055 KnownRHS.isKnownNeverLogicalNegZero(Mode))))
3056 InferredFMF.setNoSignedZeros(true);
3057 }
3058
3059 if (!FMF.noNaNs() &&
3060 ((PropagateNaN && (ValidResults & fcNan) == fcNone) ||
3061 (KnownLHS.isKnownNeverNaN() && KnownRHS.isKnownNeverNaN()))) {
3063 InferredFMF.setNoNaNs(true);
3064 }
3065
3066 if (InferredFMF != FMF) {
3067 CI->setFastMathFlags(InferredFMF);
3068 return FPOp;
3069 }
3070
3071 return nullptr;
3072 }
3073 case Intrinsic::exp:
3074 case Intrinsic::exp2:
3075 case Intrinsic::exp10: {
3076 if ((DemandedMask & fcPositive) == fcNone) {
3077 // Only returns positive values or nans.
3078 if ((DemandedMask & fcNan) == fcNone)
3079 return PoisonValue::get(VTy);
3080
3081 // Only need nan propagation.
3082 if ((DemandedMask & ~fcNan) == fcNone)
3083 return ConstantFP::getQNaN(VTy);
3084
3085 return CI->getArgOperand(0);
3086 }
3087
3088 FPClassTest SrcDemandedMask = DemandedMask & fcNan;
3089 if (DemandedMask & fcNan)
3090 SrcDemandedMask |= fcNan;
3091
3092 if (DemandedMask & fcZero) {
3093 // exp(-infinity) = 0
3094 SrcDemandedMask |= fcNegInf;
3095
3096 // exp(-largest_normal) = 0
3097 //
3098 // Negative numbers of sufficiently large magnitude underflow to 0. No
3099 // subnormal input has a 0 result.
3100 SrcDemandedMask |= fcNegNormal;
3101 }
3102
3103 if (DemandedMask & fcPosSubnormal) {
3104 // Negative numbers of sufficiently large magnitude underflow to 0. No
3105 // subnormal input has a 0 result.
3106 SrcDemandedMask |= fcNegNormal;
3107 }
3108
3109 if (DemandedMask & fcPosNormal) {
3110 // exp(0) = 1
3111 // exp(+/- smallest_normal) = 1
3112 // exp(+/- largest_denormal) = 1
3113 // exp(+/- smallest_denormal) = 1
3114 // exp(-1) = pos normal
3115 SrcDemandedMask |= fcNormal | fcSubnormal | fcZero;
3116 }
3117
3118 // exp(inf), exp(largest_normal) = inf
3119 if (DemandedMask & fcPosInf)
3120 SrcDemandedMask |= fcPosInf | fcPosNormal;
3121
3122 KnownFPClass KnownSrc;
3123
3124 // TODO: This could really make use of KnownFPClass of specific value
3125 // range, (i.e., close enough to 1)
3126 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownSrc, SQ,
3127 Depth + 1))
3128 return I;
3129
3130 // exp(+/-0) = 1
3131 if (KnownSrc.isKnownAlways(fcZero))
3132 return ConstantFP::get(VTy, 1.0);
3133
3134 // Only perform nan propagation.
3135 // Note: Dropping canonicalize / quiet of signaling nan.
3136 if (KnownSrc.isKnownAlways(fcNan))
3137 return CI->getArgOperand(0);
3138
3139 // exp(0 | nan) => x == 0.0 ? 1.0 : x
3140 if (KnownSrc.isKnownAlways(fcZero | fcNan)) {
3142 Builder.SetInsertPoint(CI);
3143
3144 // fadd +/-0, 1.0 => 1.0
3145 // fadd nan, 1.0 => nan
3146 return Builder.CreateFAddFMF(CI->getArgOperand(0),
3147 ConstantFP::get(VTy, 1.0), FMF);
3148 }
3149
3150 if (KnownSrc.isKnownAlways(fcInf | fcNan)) {
3151 // exp(-inf) = 0
3152 // exp(+inf) = +inf
3154 Builder.SetInsertPoint(CI);
3155
3156 // Note: Dropping canonicalize / quiet of signaling nan.
3157 Value *X = CI->getArgOperand(0);
3158 Value *IsPosInfOrNan = Builder.CreateFCmpFMF(
3160 // We do not know whether an infinity or a NaN is more likely here,
3161 // so mark the branch weights as unkown.
3162 Value *ZeroOrInf = Builder.CreateSelectFMFWithUnknownProfile(
3163 IsPosInfOrNan, X, ConstantFP::getZero(VTy), FMF, DEBUG_TYPE);
3164 return ZeroOrInf;
3165 }
3166
3167 Known = KnownFPClass::exp(KnownSrc);
3168 Known.knownNot(~DemandedMask);
3169
3170 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3171 KnownSrc);
3172 }
3173 case Intrinsic::log:
3174 case Intrinsic::log2:
3175 case Intrinsic::log10: {
3176 FPClassTest DemandedSrcMask = DemandedMask & (fcNan | fcPosInf);
3177 if (DemandedMask & fcNan)
3178 DemandedSrcMask |= fcNan;
3179
3180 Type *EltTy = VTy->getScalarType();
3181 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3182
3183 // log(x < 0) = nan
3184 if (DemandedMask & fcNan)
3185 DemandedSrcMask |= (fcNegative & ~fcNegZero);
3186
3187 // log(0) = -inf
3188 if (DemandedMask & fcNegInf) {
3189 DemandedSrcMask |= fcZero;
3190
3191 // No value produces subnormal result.
3192 if (Mode.inputsMayBeZero())
3193 DemandedSrcMask |= fcSubnormal;
3194 }
3195
3196 if (DemandedMask & fcNormal)
3197 DemandedSrcMask |= fcNormal | fcSubnormal;
3198
3199 // log(1) = 0
3200 if (DemandedMask & fcZero)
3201 DemandedSrcMask |= fcPosNormal;
3202
3203 KnownFPClass KnownSrc;
3204 if (SimplifyDemandedFPClass(I, 0, DemandedSrcMask, KnownSrc, SQ,
3205 Depth + 1))
3206 return I;
3207
3208 Known = KnownFPClass::log(KnownSrc, Mode);
3209 Known.knownNot(~DemandedMask);
3210
3211 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3212 KnownSrc);
3213 }
3214 case Intrinsic::sqrt: {
3215 FPClassTest DemandedSrcMask =
3216 DemandedMask & (fcNegZero | fcPositive | fcNan);
3217
3218 if (DemandedMask & fcNan)
3219 DemandedSrcMask |= fcNan | (fcNegative & ~fcNegZero);
3220
3221 // sqrt(max_subnormal) is a normal value
3222 if (DemandedMask & fcPosNormal)
3223 DemandedSrcMask |= fcPosSubnormal;
3224
3225 KnownFPClass KnownSrc;
3226 if (SimplifyDemandedFPClass(I, 0, DemandedSrcMask, KnownSrc, SQ,
3227 Depth + 1))
3228 return I;
3229
3230 // Infer the source cannot be negative if the result cannot be nan.
3231 if ((DemandedMask & fcNan) == fcNone)
3232 KnownSrc.knownNot((fcNegative & ~fcNegZero) | fcNan);
3233
3234 // Infer the source cannot be +inf if the result is not +nf
3235 if ((DemandedMask & fcPosInf) == fcNone)
3236 KnownSrc.knownNot(fcPosInf);
3237
3238 Type *EltTy = VTy->getScalarType();
3239 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3240
3241 // sqrt(-x) = nan, but be careful of negative subnormals flushed to 0.
3242 if (KnownSrc.isKnownNever(fcPositive) &&
3243 KnownSrc.isKnownNeverLogicalZero(Mode))
3244 return ConstantFP::getQNaN(VTy);
3245
3246 Known = KnownFPClass::sqrt(KnownSrc, Mode);
3247 Known.knownNot(~DemandedMask);
3248
3249 if (Known.getKnownFPClasses() == fcZero) {
3250 if (FMF.noSignedZeros())
3251 return ConstantFP::getZero(VTy);
3253 Builder.SetInsertPoint(CI);
3254
3255 Value *Copysign = Builder.CreateCopySign(ConstantFP::getZero(VTy),
3256 CI->getArgOperand(0), FMF);
3257 Copysign->takeName(CI);
3258 return Copysign;
3259 }
3260
3261 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3262 {KnownSrc});
3263 }
3264 case Intrinsic::ldexp: {
3265 FPClassTest SrcDemandedMask = DemandedMask & fcInf;
3266 if (DemandedMask & fcNan)
3267 SrcDemandedMask |= fcNan;
3268
3269 if (DemandedMask & fcPosInf)
3270 SrcDemandedMask |= fcPosNormal | fcPosSubnormal;
3271 if (DemandedMask & fcNegInf)
3272 SrcDemandedMask |= fcNegNormal | fcNegSubnormal;
3273
3274 if (DemandedMask & (fcPosNormal | fcPosSubnormal))
3275 SrcDemandedMask |= fcPosNormal | fcPosSubnormal;
3276 if (DemandedMask & (fcNegNormal | fcNegSubnormal))
3277 SrcDemandedMask |= fcNegNormal | fcNegSubnormal;
3278
3279 if (DemandedMask & fcPosZero)
3280 SrcDemandedMask |= fcPosFinite;
3281 if (DemandedMask & fcNegZero)
3282 SrcDemandedMask |= fcNegFinite;
3283
3284 KnownFPClass KnownSrc;
3285 if (SimplifyDemandedFPClass(CI, 0, SrcDemandedMask, KnownSrc, SQ,
3286 Depth + 1))
3287 return CI;
3288
3289 Type *EltTy = VTy->getScalarType();
3290 const fltSemantics &FltSem = EltTy->getFltSemantics();
3291 DenormalMode Mode = F.getDenormalMode(FltSem);
3292
3293 KnownBits KnownExpBits =
3295
3296 Known = KnownFPClass::ldexp(KnownSrc, KnownExpBits, FltSem, Mode);
3297 Known.knownNot(~DemandedMask);
3298
3299 return simplifyDemandedFPClassResult(CI, FMF, DemandedMask, Known,
3300 {KnownSrc});
3301 }
3302 case Intrinsic::trunc:
3303 case Intrinsic::floor:
3304 case Intrinsic::ceil:
3305 case Intrinsic::rint:
3306 case Intrinsic::nearbyint:
3307 case Intrinsic::round:
3308 case Intrinsic::roundeven: {
3309 FPClassTest DemandedSrcMask = DemandedMask;
3310 if (DemandedMask & fcNan)
3311 DemandedSrcMask |= fcNan;
3312
3313 // Zero results imply valid subnormal sources.
3314 if (DemandedMask & fcNegZero)
3315 DemandedSrcMask |= fcNegSubnormal | fcNegNormal;
3316
3317 if (DemandedMask & fcPosZero)
3318 DemandedSrcMask |= fcPosSubnormal | fcPosNormal;
3319
3320 KnownFPClass KnownSrc;
3321 if (SimplifyDemandedFPClass(CI, 0, DemandedSrcMask, KnownSrc, SQ,
3322 Depth + 1))
3323 return I;
3324
3325 // Note: Possibly dropping snan quiet.
3326 if (KnownSrc.isKnownAlways(fcInf | fcNan | fcZero))
3327 return CI->getArgOperand(0);
3328
3329 bool IsRoundNearestOrTrunc =
3330 IID == Intrinsic::round || IID == Intrinsic::roundeven ||
3331 IID == Intrinsic::nearbyint || IID == Intrinsic::rint ||
3332 IID == Intrinsic::trunc;
3333
3334 // Ignore denormals-as-zero, as canonicalization is not mandated.
3335 if ((IID == Intrinsic::floor || IsRoundNearestOrTrunc) &&
3337 return ConstantFP::getZero(VTy);
3338
3339 if ((IID == Intrinsic::ceil || IsRoundNearestOrTrunc) &&
3341 return ConstantFP::getZero(VTy, true);
3342
3343 if (IID == Intrinsic::floor && KnownSrc.isKnownAlways(fcNegSubnormal))
3344 return ConstantFP::get(VTy, -1.0);
3345
3346 if (IID == Intrinsic::ceil && KnownSrc.isKnownAlways(fcPosSubnormal))
3347 return ConstantFP::get(VTy, 1.0);
3348
3350 KnownSrc, IID == Intrinsic::trunc,
3352
3353 Known.knownNot(~DemandedMask);
3354
3355 if (Constant *SingleVal =
3356 getFPClassConstant(VTy, Known.getKnownFPClasses(),
3357 /*IsCanonicalizing=*/true))
3358 return SingleVal;
3359
3360 if ((IID == Intrinsic::trunc || IsRoundNearestOrTrunc) &&
3361 KnownSrc.isKnownAlways(fcZero | fcSubnormal)) {
3363 Builder.SetInsertPoint(CI);
3364
3365 Value *Copysign = Builder.CreateCopySign(ConstantFP::getZero(VTy),
3366 CI->getArgOperand(0));
3367 Copysign->takeName(CI);
3368 return Copysign;
3369 }
3370
3371 FastMathFlags InferredFMF =
3372 inferFastMathValueFlags(FMF, Known.getKnownFPClasses(), KnownSrc);
3373 if (InferredFMF != FMF) {
3375 CI->setFastMathFlags(InferredFMF);
3376 return CI;
3377 }
3378
3379 return nullptr;
3380 }
3381 case Intrinsic::fptrunc_round:
3382 return simplifyDemandedUseFPClassFPTrunc(*this, *CI, FMF, DemandedMask,
3383 Known, SQ, Depth);
3384 case Intrinsic::canonicalize: {
3385 Type *EltTy = VTy->getScalarType();
3386
3387 // TODO: This could have more refined support for PositiveZero denormal
3388 // mode.
3389 if (EltTy->isIEEELikeFPTy()) {
3390 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3391
3392 FPClassTest SrcDemandedMask = DemandedMask;
3393
3394 // A demanded quiet nan result may have come from a signaling nan, so we
3395 // need to expand the demanded mask.
3396 if ((DemandedMask & fcQNan) != fcNone)
3397 SrcDemandedMask |= fcSNan;
3398
3399 if (Mode != DenormalMode::getIEEE()) {
3400 // Any zero results may have come from flushed denormals.
3401 if (DemandedMask & fcPosZero)
3402 SrcDemandedMask |= fcPosSubnormal;
3403 if (DemandedMask & fcNegZero)
3404 SrcDemandedMask |= fcNegSubnormal;
3405 }
3406
3407 if (Mode == DenormalMode::getPreserveSign()) {
3408 // If a denormal input will be flushed, and we don't need zeros, we
3409 // don't need denormals either.
3410 if ((DemandedMask & fcPosZero) == fcNone)
3411 SrcDemandedMask &= ~fcPosSubnormal;
3412
3413 if ((DemandedMask & fcNegZero) == fcNone)
3414 SrcDemandedMask &= ~fcNegSubnormal;
3415 }
3416
3417 KnownFPClass KnownSrc;
3418
3419 // Simplify upstream operations before trying to simplify this call.
3420 if (SimplifyDemandedFPClass(I, 0, SrcDemandedMask, KnownSrc, SQ,
3421 Depth + 1))
3422 return I;
3423
3424 // Perform the canonicalization to see if this folded to a constant.
3425 Known = KnownFPClass::canonicalize(KnownSrc, Mode);
3426 Known.knownNot(~DemandedMask);
3427
3428 if (Constant *SingleVal =
3429 getFPClassConstant(VTy, Known.getKnownFPClasses()))
3430 return SingleVal;
3431
3432 // For IEEE handling, there is only a bit change for nan inputs, so we
3433 // can drop it if we do not demand nan results or we know the input
3434 // isn't a nan.
3435 // Otherwise, we also need to avoid denormal inputs to drop the
3436 // canonicalize.
3437 if (KnownSrc.isKnownNeverNaN() && (Mode == DenormalMode::getIEEE() ||
3438 KnownSrc.isKnownNeverSubnormal()))
3439 return CI->getArgOperand(0);
3440
3441 FastMathFlags InferredFMF =
3442 inferFastMathValueFlags(FMF, Known.getKnownFPClasses(), KnownSrc);
3443 if (InferredFMF != FMF) {
3445 CI->setFastMathFlags(InferredFMF);
3446 return CI;
3447 }
3448
3449 return nullptr;
3450 }
3451
3452 [[fallthrough]];
3453 }
3454 default:
3455 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3456 Known.knownNot(~DemandedMask);
3457 break;
3458 }
3459
3460 break;
3461 }
3462 case Instruction::Select: {
3463 KnownFPClass KnownLHS, KnownRHS;
3464 if (SimplifyDemandedFPClass(I, 2, DemandedMask, KnownRHS, SQ, Depth + 1) ||
3465 SimplifyDemandedFPClass(I, 1, DemandedMask, KnownLHS, SQ, Depth + 1))
3466 return I;
3467
3468 if (KnownLHS.isKnownNever(DemandedMask))
3469 return I->getOperand(2);
3470 if (KnownRHS.isKnownNever(DemandedMask))
3471 return I->getOperand(1);
3472
3473 adjustKnownFPClassForSelectArm(KnownLHS, I->getOperand(0), I->getOperand(1),
3474 /*Invert=*/false, SQ, Depth);
3475 adjustKnownFPClassForSelectArm(KnownRHS, I->getOperand(0), I->getOperand(2),
3476 /*Invert=*/true, SQ, Depth);
3477 Known = KnownLHS.intersectWith(KnownRHS);
3478 Known.knownNot(~DemandedMask);
3479 break;
3480 }
3481 case Instruction::ExtractElement: {
3482 // TODO: Handle demanded element mask
3483 if (SimplifyDemandedFPClass(I, 0, DemandedMask, Known, SQ, Depth + 1))
3484 return I;
3485 Known.knownNot(~DemandedMask);
3486 break;
3487 }
3488 case Instruction::InsertElement: {
3489 KnownFPClass KnownInserted, KnownVec;
3490 if (SimplifyDemandedFPClass(I, 1, DemandedMask, KnownInserted, SQ,
3491 Depth + 1) ||
3492 SimplifyDemandedFPClass(I, 0, DemandedMask, KnownVec, SQ, Depth + 1))
3493 return I;
3494
3495 // TODO: Use demanded elements logic from computeKnownFPClass
3496 Known = KnownVec | KnownInserted;
3497 Known.knownNot(~DemandedMask);
3498 break;
3499 }
3500 case Instruction::ShuffleVector: {
3501 KnownFPClass KnownLHS, KnownRHS;
3502 if (SimplifyDemandedFPClass(I, 1, DemandedMask, KnownRHS, SQ, Depth + 1) ||
3503 SimplifyDemandedFPClass(I, 0, DemandedMask, KnownLHS, SQ, Depth + 1))
3504 return I;
3505
3506 // TODO: This is overly conservative and should consider demanded elements,
3507 // and splats.
3508 Known = KnownLHS | KnownRHS;
3509 Known.knownNot(~DemandedMask);
3510 break;
3511 }
3512 case Instruction::InsertValue: {
3513 KnownFPClass KnownAgg, KnownElt;
3514 if (SimplifyDemandedFPClass(I, 0, DemandedMask, KnownAgg, SQ, Depth + 1) ||
3515 SimplifyDemandedFPClass(I, 1, DemandedMask, KnownElt, SQ, Depth + 1))
3516 return I;
3517
3518 Known = KnownAgg | KnownElt;
3519 break;
3520 }
3521 case Instruction::ExtractValue: {
3522 Value *ExtractSrc;
3523 if (match(I, m_ExtractValue<0>(m_OneUse(m_Value(ExtractSrc))))) {
3524 if (auto *II = dyn_cast<IntrinsicInst>(ExtractSrc)) {
3525 const Intrinsic::ID IID = II->getIntrinsicID();
3526 switch (IID) {
3527 case Intrinsic::frexp: {
3528 FPClassTest SrcDemandedMask = fcNone;
3529 if (DemandedMask & fcNan)
3530 SrcDemandedMask |= fcNan;
3531 if (DemandedMask & fcNegFinite)
3532 SrcDemandedMask |= fcNegFinite;
3533 if (DemandedMask & fcPosFinite)
3534 SrcDemandedMask |= fcPosFinite;
3535 if (DemandedMask & fcPosInf)
3536 SrcDemandedMask |= fcPosInf;
3537 if (DemandedMask & fcNegInf)
3538 SrcDemandedMask |= fcNegInf;
3539
3540 KnownFPClass KnownSrc;
3541 if (SimplifyDemandedFPClass(II, 0, SrcDemandedMask, KnownSrc, SQ,
3542 Depth + 1))
3543 return I;
3544
3545 Type *EltTy = VTy->getScalarType();
3546 DenormalMode Mode = F.getDenormalMode(EltTy->getFltSemantics());
3547
3548 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
3549 Known.setKnownFPClasses(Known.getKnownFPClasses() & DemandedMask);
3550
3551 if (Constant *SingleVal =
3552 getFPClassConstant(VTy, Known.getKnownFPClasses(),
3553 /*IsCanonicalizing=*/true))
3554 return SingleVal;
3555
3556 if (Known.isKnownAlways(fcInf | fcNan))
3557 return II->getArgOperand(0);
3558
3559 return nullptr;
3560 }
3561 default:
3562 break;
3563 }
3564 }
3565 }
3566
3567 KnownFPClass KnownSrc;
3568 if (SimplifyDemandedFPClass(I, 0, DemandedMask, KnownSrc, SQ, Depth + 1))
3569 return I;
3570 Known = KnownSrc;
3571 break;
3572 }
3573 case Instruction::PHI: {
3574 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
3575 if (Depth >= PhiRecursionLimit)
3576 break;
3577
3579 SimplifyQuery ContextSQ = SQ.getWithoutCondContext();
3580
3581 bool First = true;
3582 bool Changed = false;
3583 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; ++I) {
3584 // TODO: Better support for self recursive phi
3585 BasicBlock *PredBB = P->getIncomingBlock(I);
3586 const Instruction *CtxI = PredBB->getTerminator();
3587
3588 // Attempt to simplify all incoming edges at a time. If we simplify one
3589 // incoming edge, the phi may fold away, losing information on a later
3590 // visit.
3591 KnownFPClass KnownSrc;
3593 P, P->getOperandNumForIncomingValue(I), DemandedMask, KnownSrc,
3594 ContextSQ.getWithInstruction(CtxI), Depth + 1)) {
3595 // Fixup the other block references to the simplified value.
3596 P->setIncomingValueForBlock(PredBB, P->getIncomingValue(I));
3597 Changed = true;
3598 }
3599
3600 if (First) {
3601 Known = KnownSrc;
3602 First = false;
3603 } else {
3604 Known |= KnownSrc;
3605 }
3606 }
3607
3608 if (Changed)
3609 return P;
3610
3611 Known.knownNot(~DemandedMask);
3612 break;
3613 }
3614 default:
3615 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3616 Known.knownNot(~DemandedMask);
3617 break;
3618 }
3619
3620 return getFPClassConstant(VTy, Known.getKnownFPClasses());
3621}
3622
3623/// Helper routine of SimplifyDemandedUseFPClass. It computes Known
3624/// floating-point classes. It also tries to handle simplifications that can be
3625/// done based on DemandedMask, but without modifying the Instruction.
3627 Instruction *I, FPClassTest DemandedMask, KnownFPClass &Known,
3628 const SimplifyQuery &SQ, unsigned Depth) {
3629 FastMathFlags FMF;
3630 if (auto *FPOp = dyn_cast<FPMathOperator>(I)) {
3631 FMF = FPOp->getFastMathFlags();
3632 DemandedMask = adjustDemandedMaskFromFlags(DemandedMask, FMF);
3633 }
3634
3635 switch (I->getOpcode()) {
3636 case Instruction::Select: {
3637 // TODO: Can we infer which side it came from based on adjusted result
3638 // class?
3639 KnownFPClass KnownRHS =
3640 computeKnownFPClass(I->getOperand(2), DemandedMask, SQ, Depth + 1);
3641 if (KnownRHS.isKnownNever(DemandedMask))
3642 return I->getOperand(1);
3643
3644 KnownFPClass KnownLHS =
3645 computeKnownFPClass(I->getOperand(1), DemandedMask, SQ, Depth + 1);
3646 if (KnownLHS.isKnownNever(DemandedMask))
3647 return I->getOperand(2);
3648
3649 adjustKnownFPClassForSelectArm(KnownLHS, I->getOperand(0), I->getOperand(1),
3650 /*Invert=*/false, SQ, Depth);
3651 adjustKnownFPClassForSelectArm(KnownRHS, I->getOperand(0), I->getOperand(2),
3652 /*Invert=*/true, SQ, Depth);
3653 Known = KnownLHS.intersectWith(KnownRHS);
3654 Known.knownNot(~DemandedMask);
3655 break;
3656 }
3657 case Instruction::FNeg: {
3658 // Special case fneg(fabs(x))
3659 Value *Src;
3660
3661 Value *FNegSrc = I->getOperand(0);
3662 if (!match(FNegSrc, m_FAbs(m_Value(Src)))) {
3663 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3664 break;
3665 }
3666
3667 KnownFPClass KnownSrc = computeKnownFPClass(Src, fcAllFlags, SQ, Depth + 1);
3668
3669 FastMathFlags FabsFMF = cast<FPMathOperator>(FNegSrc)->getFastMathFlags();
3670 FPClassTest ThisDemandedMask =
3671 adjustDemandedMaskFromFlags(DemandedMask, FabsFMF);
3672
3673 // We cannot apply the NSZ logic with multiple uses. We can apply it if the
3674 // inner fabs has it and this is the only use.
3675 if (Value *Simplified = simplifyDemandedFPClassFnegFabs(
3676 Known, Src, ThisDemandedMask, KnownSrc, /*NSZ=*/false))
3677 return Simplified;
3678 break;
3679 }
3680 case Instruction::Call: {
3681 const CallInst *CI = cast<CallInst>(I);
3682 const Intrinsic::ID IID = CI->getIntrinsicID();
3683 switch (IID) {
3684 case Intrinsic::fabs: {
3685 Value *Src = CI->getArgOperand(0);
3686 KnownFPClass KnownSrc =
3688
3689 // NSZ cannot be applied in multiple use case (maybe it could if all uses
3690 // were known nsz)
3691 if (Value *Simplified = simplifyDemandedFPClassFabs(
3692 Known, CI->getArgOperand(0), DemandedMask, KnownSrc,
3693 /*NSZ=*/false))
3694 return Simplified;
3695 break;
3696 }
3697 case Intrinsic::copysign: {
3698 Value *Mag = CI->getArgOperand(0);
3699 Value *Sign = CI->getArgOperand(1);
3700 KnownFPClass KnownMag =
3702
3703 // Rule out some cases by magnitude, which may help prove the sign bit is
3704 // one direction or the other.
3705 KnownMag.knownNot(~llvm::unknown_sign(DemandedMask));
3706
3707 // Cannot use nsz in the multiple use case.
3708 if (Value *Simplified = simplifyDemandedFPClassCopysignMag(
3709 Mag, DemandedMask, KnownMag, /*NSZ=*/false))
3710 return Simplified;
3711
3712 KnownFPClass KnownSign =
3714
3715 if (FMF.noInfs())
3716 KnownSign.knownNot(fcInf);
3717 if (FMF.noNaNs())
3718 KnownSign.knownNot(fcNan);
3719
3720 if (KnownSign.getSignBit() && KnownMag.getSignBit() &&
3721 *KnownSign.getSignBit() == *KnownMag.getSignBit())
3722 return Mag;
3723
3724 Known = KnownFPClass::copysign(KnownMag, KnownSign);
3725 break;
3726 }
3727 case Intrinsic::maxnum:
3728 case Intrinsic::minnum:
3729 case Intrinsic::maximum:
3730 case Intrinsic::minimum:
3731 case Intrinsic::maximumnum:
3732 case Intrinsic::minimumnum: {
3734 DemandedMask, SQ, Depth + 1);
3735 if (KnownRHS.isUnknown())
3736 return nullptr;
3737
3739 DemandedMask, SQ, Depth + 1);
3740
3741 // Cannot use NSZ in the multiple use case.
3742 return simplifyDemandedFPClassMinMax(Known, IID, CI, DemandedMask,
3743 KnownLHS, KnownRHS, F,
3744 /*NSZ=*/false);
3745 }
3746 default:
3747 break;
3748 }
3749
3750 [[fallthrough]];
3751 }
3752 default:
3753 Known = computeKnownFPClass(I, DemandedMask, SQ, Depth + 1);
3754 Known.knownNot(~DemandedMask);
3755 break;
3756 }
3757
3758 return getFPClassConstant(I->getType(), Known.getKnownFPClasses());
3759}
3760
3762 FPClassTest DemandedMask,
3764 const SimplifyQuery &SQ,
3765 unsigned Depth) {
3766 Use &U = I->getOperandUse(OpNo);
3767 Value *V = U.get();
3768 Type *VTy = V->getType();
3769
3770 if (DemandedMask == fcNone) {
3771 if (isa<PoisonValue>(V))
3772 return false;
3774 return true;
3775 }
3776
3777 // Handle constant
3779 if (!VInst) {
3780 // Handle constants and arguments
3782 Known.knownNot(~DemandedMask);
3783
3784 if (Known.getKnownFPClasses() == fcNone) {
3785 if (isa<PoisonValue>(V))
3786 return false;
3788 return true;
3789 }
3790
3791 // Do not try to replace values which are already constants (unless we are
3792 // folding to poison). Doing so could promote poison elements to non-poison
3793 // constants.
3794 if (isa<Constant>(V))
3795 return false;
3796
3797 Value *FoldedToConst = getFPClassConstant(VTy, Known.getKnownFPClasses());
3798 if (!FoldedToConst || FoldedToConst == V)
3799 return false;
3800
3801 replaceUse(U, FoldedToConst);
3802 return true;
3803 }
3804
3806 Known.knownNot(~DemandedMask);
3807 return false;
3808 }
3809
3810 Value *NewVal;
3811
3812 if (VInst->hasOneUse()) {
3813 // If the instruction has one use, we can directly simplify it.
3814 NewVal = SimplifyDemandedUseFPClass(VInst, DemandedMask, Known, SQ, Depth);
3815 } else {
3816 // If there are multiple uses of this instruction, then we can simplify
3817 // VInst to some other value, but not modify the instruction.
3818 NewVal = SimplifyMultipleUseDemandedFPClass(VInst, DemandedMask, Known, SQ,
3819 Depth);
3820 }
3821
3822 if (!NewVal)
3823 return false;
3824 if (Instruction *OpInst = dyn_cast<Instruction>(U))
3825 salvageDebugInfo(*OpInst);
3826
3827 replaceUse(U, NewVal);
3828 return true;
3829}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define DEBUG_TYPE
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static cl::opt< unsigned > SimplifyDemandedVectorEltsDepthLimit("instcombine-simplify-vector-elts-depth", cl::desc("Depth limit when simplifying vector instructions and their operands"), cl::Hidden, cl::init(10))
static Constant * getFPClassConstant(Type *Ty, FPClassTest Mask, bool IsCanonicalizing=false)
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 Value * simplifyDemandedFPClassFabs(KnownFPClass &Known, Value *Src, FPClassTest DemandedMask, KnownFPClass KnownSrc, bool NSZ)
Perform multiple-use aware simplfications for fabs(Src).
static Value * simplifyDemandedUseFPClassFPTrunc(InstCombinerImpl &IC, Instruction &I, FastMathFlags FMF, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &SQ, unsigned Depth)
static Value * simplifyDemandedFPClassFnegFabs(KnownFPClass &Known, Value *Src, FPClassTest DemandedMask, KnownFPClass KnownSrc, bool NSZ)
Perform multiple-use aware simplfications for fneg(fabs(Src)).
static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, const APInt &Demanded)
Check to see if the specified operand of the specified instruction is a constant integer.
static Value * simplifyShiftSelectingPackedElement(Instruction *I, const APInt &DemandedMask, InstCombinerImpl &IC, unsigned Depth)
Let N = 2 * M.
static Value * simplifyDemandedFPClassMinMax(KnownFPClass &Known, Intrinsic::ID IID, const CallInst *CI, FPClassTest DemandedMask, KnownFPClass KnownLHS, KnownFPClass KnownRHS, const Function &F, bool NSZ)
static bool canSkipDemandedEltsInInsertChain(InsertElementInst &IE, unsigned VWidth, unsigned DepthLimit)
Return true if the top-level all-lanes demanded-elements query can be skipped for an intermediate ins...
static Value * simplifyDemandedFPClassCopysignMag(Value *MagSrc, FPClassTest DemandedMask, KnownFPClass KnownSrc, bool NSZ)
static FPClassTest adjustDemandedMaskFromFlags(FPClassTest DemandedMask, FastMathFlags FMF)
static FastMathFlags inferFastMathValueFlags(FastMathFlags FMF, FPClassTest ValidResults, ArrayRef< KnownFPClass > Known)
Try to set an inferred no-nans or no-infs in FMF.
static Value * simplifyDemandedFPClassResult(Instruction *FPOp, FastMathFlags FMF, FPClassTest DemandedMask, KnownFPClass &Known, ArrayRef< KnownFPClass > KnownSrcs)
Apply epilog fixups to a floating-point intrinsic.
This file provides the interface for the instcombine pass implementation.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file implements the SmallBitVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1192
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:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:226
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1412
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1361
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1417
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1456
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:472
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
bool isIntN(unsigned N) const
Check if this APInt has an N-bits unsigned integer value.
Definition APInt.h:429
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:386
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Value * getArgOperand(unsigned i) const
LLVM_ABI 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:512
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:89
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
void setNoInfs(bool B=true)
Definition FMF.h:81
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2390
LLVM_ABI Value * CreateSelectWithUnknownProfile(Value *C, Value *True, Value *False, StringRef PassName, const Twine &Name="")
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
This instruction inserts a single (scalar) element into a VectorType value.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool SimplifyDemandedInstructionFPClass(Instruction &Inst)
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 * SimplifyDemandedUseFPClass(Instruction *I, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth=0)
Attempts to replace V with a simpler value based on the demanded floating-point classes.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
std::optional< std::pair< Intrinsic::ID, SmallVector< Value *, 3 > > > convertOrOfShiftsToFunnelShift(Instruction &Or)
Value * SimplifyMultipleUseDemandedFPClass(Instruction *I, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
Helper routine of SimplifyDemandedUseFPClass.
Value * simplifyShrShlDemandedBits(Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known)
Helper routine of SimplifyDemandedUseBits.
bool SimplifyDemandedFPClass(Instruction *I, unsigned Op, FPClassTest DemandedMask, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth=0)
Value * SimplifyDemandedUseBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Attempts to replace I with a simpler value based on the demanded bits.
bool SimplifyDemandedInstructionBits(Instruction &Inst)
Tries to simplify operands to an integer instruction based on its demanded bits.
Value * SimplifyMultipleUseDemandedBits(Instruction *I, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Helper routine of SimplifyDemandedUseBits.
SimplifyQuery SQ
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
void replaceUse(Use &U, Value *NewValue)
Replace use and add the previously used value to the worklist.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
LLVM_ABI std::optional< Value * > targetSimplifyDemandedVectorEltsIntrinsic(IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
LLVM_ABI std::optional< Value * > targetSimplifyDemandedUseBitsIntrinsic(IntrinsicInst &II, APInt DemandedMask, KnownBits &Known, bool &KnownBitsComputed)
LLVM_ABI void dropUBImplyingAttrsAndMetadata(ArrayRef< unsigned > Keep={})
Drop any attributes or metadata that can cause immediate undefined behavior.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
bool isShift() const
bool isIntDivRem() const
A wrapper class for inspecting calls to intrinsic functions.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool test(unsigned Idx) const
Returns true if bit Idx is set.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
bool isMultiUnitFPType() const
Returns true if this is a floating-point type that is an unevaluated sum of multiple floating-point u...
Definition Type.h:195
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isIEEELikeFPTy() const
Return true if this is a well-behaved IEEE-like type, which has a IEEE compatible layout,...
Definition Type.h:172
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
iterator_range< user_iterator > users()
Definition Value.h:428
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Base class of all SIMD vector types.
This class represents zero extension of integer types.
self_iterator getIterator()
Definition ilist_node.h:123
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
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)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
DisjointOr_match< LHS, RHS, true > m_c_DisjointOr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_FAbs(const Opnd0 &Op0)
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
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:1739
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1675
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:541
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI bool cannotOrderStrictlyLess(FPClassTest LHS, FPClassTest RHS, bool OrderedZeroSign=false)
Returns true if all values in LHS must be greater than or equal to those in RHS.
LLVM_ABI bool cannotOrderStrictlyGreater(FPClassTest LHS, FPClassTest RHS, bool OrderedZeroSign=false)
Returns true if all values in LHS must be less than or equal to those in RHS.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI FPClassTest inverse_fabs(FPClassTest Mask)
Return the test mask which returns true after fabs is applied to the value.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
LLVM_ABI FPClassTest unknown_sign(FPClassTest Mask)
Return the test mask which returns true if the value could have the same set of classes,...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getPreserveSign()
static constexpr DenormalMode getIEEE()
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
static constexpr FPClassTest OrderedGreaterThanZeroMask
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
void copysign(const KnownFPClass &Sign)
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
bool isKnownAlways(FPClassTest Mask) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
std::optional< bool > getSignBit() const
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool cannotBeOrderedGreaterEqZero(DenormalMode Mode) const
Return true if it's know this can never be a negative value or a logical 0.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
Matching combinators.
const Instruction * CxtI
SimplifyQuery getWithInstruction(const Instruction *I) const