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