LLVM 18.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
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 routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
21#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/StringRef.h"
31#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
40#include "llvm/IR/Constant.h"
42#include "llvm/IR/Constants.h"
45#include "llvm/IR/Dominators.h"
47#include "llvm/IR/Function.h"
49#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
56#include "llvm/IR/Intrinsics.h"
57#include "llvm/IR/IntrinsicsAArch64.h"
58#include "llvm/IR/IntrinsicsAMDGPU.h"
59#include "llvm/IR/IntrinsicsRISCV.h"
60#include "llvm/IR/IntrinsicsX86.h"
61#include "llvm/IR/LLVMContext.h"
62#include "llvm/IR/Metadata.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/Operator.h"
66#include "llvm/IR/Type.h"
67#include "llvm/IR/User.h"
68#include "llvm/IR/Value.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <optional>
79#include <utility>
80
81using namespace llvm;
82using namespace llvm::PatternMatch;
83
84// Controls the number of uses of the value searched for possible
85// dominating comparisons.
86static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
87 cl::Hidden, cl::init(20));
88
89
90/// Returns the bitwidth of the given scalar or pointer type. For vector types,
91/// returns the element type's bitwidth.
92static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
93 if (unsigned BitWidth = Ty->getScalarSizeInBits())
94 return BitWidth;
95
96 return DL.getPointerTypeSizeInBits(Ty);
97}
98
99// Given the provided Value and, potentially, a context instruction, return
100// the preferred context instruction (if any).
101static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
102 // If we've been provided with a context instruction, then use that (provided
103 // it has been inserted).
104 if (CxtI && CxtI->getParent())
105 return CxtI;
106
107 // If the value is really an already-inserted instruction, then use that.
108 CxtI = dyn_cast<Instruction>(V);
109 if (CxtI && CxtI->getParent())
110 return CxtI;
111
112 return nullptr;
113}
114
115static const Instruction *safeCxtI(const Value *V1, const Value *V2, const Instruction *CxtI) {
116 // If we've been provided with a context instruction, then use that (provided
117 // it has been inserted).
118 if (CxtI && CxtI->getParent())
119 return CxtI;
120
121 // If the value is really an already-inserted instruction, then use that.
122 CxtI = dyn_cast<Instruction>(V1);
123 if (CxtI && CxtI->getParent())
124 return CxtI;
125
126 CxtI = dyn_cast<Instruction>(V2);
127 if (CxtI && CxtI->getParent())
128 return CxtI;
129
130 return nullptr;
131}
132
134 const APInt &DemandedElts,
135 APInt &DemandedLHS, APInt &DemandedRHS) {
136 if (isa<ScalableVectorType>(Shuf->getType())) {
137 assert(DemandedElts == APInt(1,1));
138 DemandedLHS = DemandedRHS = DemandedElts;
139 return true;
140 }
141
142 int NumElts =
143 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
144 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
145 DemandedElts, DemandedLHS, DemandedRHS);
146}
147
148static void computeKnownBits(const Value *V, const APInt &DemandedElts,
149 KnownBits &Known, unsigned Depth,
150 const SimplifyQuery &Q);
151
152static void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
153 const SimplifyQuery &Q) {
154 // Since the number of lanes in a scalable vector is unknown at compile time,
155 // we track one bit which is implicitly broadcast to all lanes. This means
156 // that all lanes in a scalable vector are considered demanded.
157 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
158 APInt DemandedElts =
159 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
160 computeKnownBits(V, DemandedElts, Known, Depth, Q);
161}
162
164 const DataLayout &DL, unsigned Depth,
165 AssumptionCache *AC, const Instruction *CxtI,
166 const DominatorTree *DT, bool UseInstrInfo) {
168 V, Known, Depth,
169 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
170}
171
172void llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
173 KnownBits &Known, const DataLayout &DL,
174 unsigned Depth, AssumptionCache *AC,
175 const Instruction *CxtI, const DominatorTree *DT,
176 bool UseInstrInfo) {
178 V, DemandedElts, Known, Depth,
179 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
180}
181
183 unsigned Depth, AssumptionCache *AC,
184 const Instruction *CxtI,
185 const DominatorTree *DT, bool UseInstrInfo) {
186 return computeKnownBits(
187 V, Depth, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
188}
189
190KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
191 const DataLayout &DL, unsigned Depth,
192 AssumptionCache *AC, const Instruction *CxtI,
193 const DominatorTree *DT, bool UseInstrInfo) {
194 return computeKnownBits(
195 V, DemandedElts, Depth,
196 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
197}
198
200 const WithCache<const Value *> &RHSCache,
201 const SimplifyQuery &SQ) {
202 const Value *LHS = LHSCache.getValue();
203 const Value *RHS = RHSCache.getValue();
204
205 assert(LHS->getType() == RHS->getType() &&
206 "LHS and RHS should have the same type");
208 "LHS and RHS should be integers");
209 // Look for an inverted mask: (X & ~M) op (Y & M).
210 {
211 Value *M;
212 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
214 return true;
215 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
217 return true;
218 }
219
220 // X op (Y & ~X)
223 return true;
224
225 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
226 // for constant Y.
227 Value *Y;
228 if (match(RHS,
231 return true;
232
233 // Peek through extends to find a 'not' of the other side:
234 // (ext Y) op ext(~Y)
235 // (ext ~Y) op ext(Y)
236 if ((match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
240 return true;
241
242 // Look for: (A & B) op ~(A | B)
243 {
244 Value *A, *B;
245 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
247 return true;
248 if (match(RHS, m_And(m_Value(A), m_Value(B))) &&
250 return true;
251 }
252
254 RHSCache.getKnownBits(SQ));
255}
256
258 return !I->user_empty() && all_of(I->users(), [](const User *U) {
259 ICmpInst::Predicate P;
260 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
261 });
262}
263
264static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
265 const SimplifyQuery &Q);
266
268 bool OrZero, unsigned Depth,
269 AssumptionCache *AC, const Instruction *CxtI,
270 const DominatorTree *DT, bool UseInstrInfo) {
271 return ::isKnownToBeAPowerOfTwo(
272 V, OrZero, Depth,
273 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
274}
275
276static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
277 unsigned Depth, const SimplifyQuery &Q);
278
279static bool isKnownNonZero(const Value *V, unsigned Depth,
280 const SimplifyQuery &Q);
281
282bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
283 AssumptionCache *AC, const Instruction *CxtI,
284 const DominatorTree *DT, bool UseInstrInfo) {
285 return ::isKnownNonZero(
286 V, Depth, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
287}
288
290 unsigned Depth, AssumptionCache *AC,
291 const Instruction *CxtI, const DominatorTree *DT,
292 bool UseInstrInfo) {
293 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
294 return Known.isNonNegative();
295}
296
297bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
298 AssumptionCache *AC, const Instruction *CxtI,
299 const DominatorTree *DT, bool UseInstrInfo) {
300 if (auto *CI = dyn_cast<ConstantInt>(V))
301 return CI->getValue().isStrictlyPositive();
302
303 // TODO: We'd doing two recursive queries here. We should factor this such
304 // that only a single query is needed.
305 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
306 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
307}
308
309bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
310 AssumptionCache *AC, const Instruction *CxtI,
311 const DominatorTree *DT, bool UseInstrInfo) {
312 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
313 return Known.isNegative();
314}
315
316static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
317 const SimplifyQuery &Q);
318
319bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
320 const DataLayout &DL, AssumptionCache *AC,
321 const Instruction *CxtI, const DominatorTree *DT,
322 bool UseInstrInfo) {
323 return ::isKnownNonEqual(
324 V1, V2, 0,
325 SimplifyQuery(DL, DT, AC, safeCxtI(V2, V1, CxtI), UseInstrInfo));
326}
327
328static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
329 const SimplifyQuery &Q);
330
331bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
332 const DataLayout &DL, unsigned Depth,
333 AssumptionCache *AC, const Instruction *CxtI,
334 const DominatorTree *DT, bool UseInstrInfo) {
335 return ::MaskedValueIsZero(
336 V, Mask, Depth,
337 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
338}
339
340static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
341 unsigned Depth, const SimplifyQuery &Q);
342
343static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
344 const SimplifyQuery &Q) {
345 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ComputeNumSignBits(V, DemandedElts, Depth, Q);
349}
350
351unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
352 unsigned Depth, AssumptionCache *AC,
353 const Instruction *CxtI,
354 const DominatorTree *DT, bool UseInstrInfo) {
355 return ::ComputeNumSignBits(
356 V, Depth, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo));
357}
358
360 unsigned Depth, AssumptionCache *AC,
361 const Instruction *CxtI,
362 const DominatorTree *DT) {
363 unsigned SignBits = ComputeNumSignBits(V, DL, Depth, AC, CxtI, DT);
364 return V->getType()->getScalarSizeInBits() - SignBits + 1;
365}
366
367static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
368 bool NSW, const APInt &DemandedElts,
369 KnownBits &KnownOut, KnownBits &Known2,
370 unsigned Depth, const SimplifyQuery &Q) {
371 computeKnownBits(Op1, DemandedElts, KnownOut, Depth + 1, Q);
372
373 // If one operand is unknown and we have no nowrap information,
374 // the result will be unknown independently of the second operand.
375 if (KnownOut.isUnknown() && !NSW)
376 return;
377
378 computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
379 KnownOut = KnownBits::computeForAddSub(Add, NSW, Known2, KnownOut);
380}
381
382static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
383 const APInt &DemandedElts, KnownBits &Known,
384 KnownBits &Known2, unsigned Depth,
385 const SimplifyQuery &Q) {
386 computeKnownBits(Op1, DemandedElts, Known, Depth + 1, Q);
387 computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
388
389 bool isKnownNegative = false;
390 bool isKnownNonNegative = false;
391 // If the multiplication is known not to overflow, compute the sign bit.
392 if (NSW) {
393 if (Op0 == Op1) {
394 // The product of a number with itself is non-negative.
395 isKnownNonNegative = true;
396 } else {
397 bool isKnownNonNegativeOp1 = Known.isNonNegative();
398 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
399 bool isKnownNegativeOp1 = Known.isNegative();
400 bool isKnownNegativeOp0 = Known2.isNegative();
401 // The product of two numbers with the same sign is non-negative.
402 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
403 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
404 // The product of a negative number and a non-negative number is either
405 // negative or zero.
408 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
409 Known2.isNonZero()) ||
410 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
411 }
412 }
413
414 bool SelfMultiply = Op0 == Op1;
415 // TODO: SelfMultiply can be poison, but not undef.
416 if (SelfMultiply)
417 SelfMultiply &=
419 Known = KnownBits::mul(Known, Known2, SelfMultiply);
420
421 // Only make use of no-wrap flags if we failed to compute the sign bit
422 // directly. This matters if the multiplication always overflows, in
423 // which case we prefer to follow the result of the direct computation,
424 // though as the program is invoking undefined behaviour we can choose
425 // whatever we like here.
426 if (isKnownNonNegative && !Known.isNegative())
427 Known.makeNonNegative();
428 else if (isKnownNegative && !Known.isNonNegative())
429 Known.makeNegative();
430}
431
433 KnownBits &Known) {
434 unsigned BitWidth = Known.getBitWidth();
435 unsigned NumRanges = Ranges.getNumOperands() / 2;
436 assert(NumRanges >= 1);
437
438 Known.Zero.setAllBits();
439 Known.One.setAllBits();
440
441 for (unsigned i = 0; i < NumRanges; ++i) {
443 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
445 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
446 ConstantRange Range(Lower->getValue(), Upper->getValue());
447
448 // The first CommonPrefixBits of all values in Range are equal.
449 unsigned CommonPrefixBits =
450 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
451 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
452 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
453 Known.One &= UnsignedMax & Mask;
454 Known.Zero &= ~UnsignedMax & Mask;
455 }
456}
457
458static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
462
463 // The instruction defining an assumption's condition itself is always
464 // considered ephemeral to that assumption (even if it has other
465 // non-ephemeral users). See r246696's test case for an example.
466 if (is_contained(I->operands(), E))
467 return true;
468
469 while (!WorkSet.empty()) {
470 const Value *V = WorkSet.pop_back_val();
471 if (!Visited.insert(V).second)
472 continue;
473
474 // If all uses of this value are ephemeral, then so is this value.
475 if (llvm::all_of(V->users(), [&](const User *U) {
476 return EphValues.count(U);
477 })) {
478 if (V == E)
479 return true;
480
481 if (V == I || (isa<Instruction>(V) &&
482 !cast<Instruction>(V)->mayHaveSideEffects() &&
483 !cast<Instruction>(V)->isTerminator())) {
484 EphValues.insert(V);
485 if (const User *U = dyn_cast<User>(V))
486 append_range(WorkSet, U->operands());
487 }
488 }
489 }
490
491 return false;
492}
493
494// Is this an intrinsic that cannot be speculated but also cannot trap?
496 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
497 return CI->isAssumeLikeIntrinsic();
498
499 return false;
500}
501
503 const Instruction *CxtI,
504 const DominatorTree *DT) {
505 // There are two restrictions on the use of an assume:
506 // 1. The assume must dominate the context (or the control flow must
507 // reach the assume whenever it reaches the context).
508 // 2. The context must not be in the assume's set of ephemeral values
509 // (otherwise we will use the assume to prove that the condition
510 // feeding the assume is trivially true, thus causing the removal of
511 // the assume).
512
513 if (Inv->getParent() == CxtI->getParent()) {
514 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
515 // in the BB.
516 if (Inv->comesBefore(CxtI))
517 return true;
518
519 // Don't let an assume affect itself - this would cause the problems
520 // `isEphemeralValueOf` is trying to prevent, and it would also make
521 // the loop below go out of bounds.
522 if (Inv == CxtI)
523 return false;
524
525 // The context comes first, but they're both in the same block.
526 // Make sure there is nothing in between that might interrupt
527 // the control flow, not even CxtI itself.
528 // We limit the scan distance between the assume and its context instruction
529 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
530 // it can be adjusted if needed (could be turned into a cl::opt).
531 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
533 return false;
534
535 return !isEphemeralValueOf(Inv, CxtI);
536 }
537
538 // Inv and CxtI are in different blocks.
539 if (DT) {
540 if (DT->dominates(Inv, CxtI))
541 return true;
542 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
543 // We don't have a DT, but this trivially dominates.
544 return true;
545 }
546
547 return false;
548}
549
550// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
551// we still have enough information about `RHS` to conclude non-zero. For
552// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
553// so the extra compile time may not be worth it, but possibly a second API
554// should be created for use outside of loops.
555static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
556 // v u> y implies v != 0.
557 if (Pred == ICmpInst::ICMP_UGT)
558 return true;
559
560 // Special-case v != 0 to also handle v != null.
561 if (Pred == ICmpInst::ICMP_NE)
562 return match(RHS, m_Zero());
563
564 // All other predicates - rely on generic ConstantRange handling.
565 const APInt *C;
567 if (match(RHS, m_APInt(C))) {
569 return !TrueValues.contains(Zero);
570 }
571
572 auto *VC = dyn_cast<ConstantDataVector>(RHS);
573 if (VC == nullptr)
574 return false;
575
576 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
577 ++ElemIdx) {
579 Pred, VC->getElementAsAPInt(ElemIdx));
580 if (TrueValues.contains(Zero))
581 return false;
582 }
583 return true;
584}
585
586static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
587 // Use of assumptions is context-sensitive. If we don't have a context, we
588 // cannot use them!
589 if (!Q.AC || !Q.CxtI)
590 return false;
591
592 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
593 if (!Elem.Assume)
594 continue;
595
596 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
597 assert(I->getFunction() == Q.CxtI->getFunction() &&
598 "Got assumption for the wrong function!");
599
600 if (Elem.Index != AssumptionCache::ExprResultIdx) {
601 if (!V->getType()->isPointerTy())
602 continue;
604 *I, I->bundle_op_info_begin()[Elem.Index])) {
605 if (RK.WasOn == V &&
606 (RK.AttrKind == Attribute::NonNull ||
607 (RK.AttrKind == Attribute::Dereferenceable &&
609 V->getType()->getPointerAddressSpace()))) &&
611 return true;
612 }
613 continue;
614 }
615
616 // Warning: This loop can end up being somewhat performance sensitive.
617 // We're running this loop for once for each value queried resulting in a
618 // runtime of ~O(#assumes * #values).
619
620 Value *RHS;
622 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
623 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
624 return false;
625
626 if (cmpExcludesZero(Pred, RHS) && isValidAssumeForContext(I, Q.CxtI, Q.DT))
627 return true;
628 }
629
630 return false;
631}
632
633static void computeKnownBitsFromCmp(const Value *V, const ICmpInst *Cmp,
634 KnownBits &Known, unsigned Depth,
635 const SimplifyQuery &Q) {
636 unsigned BitWidth = Known.getBitWidth();
637 // We are attempting to compute known bits for the operands of an assume.
638 // Do not try to use other assumptions for those recursive calls because
639 // that can lead to mutual recursion and a compile-time explosion.
640 // An example of the mutual recursion: computeKnownBits can call
641 // isKnownNonZero which calls computeKnownBitsFromAssume (this function)
642 // and so on.
643 SimplifyQuery QueryNoAC = Q;
644 QueryNoAC.AC = nullptr;
645
646 // Note that ptrtoint may change the bitwidth.
647 Value *A, *B;
648 auto m_V =
650
652 uint64_t C;
653 switch (Cmp->getPredicate()) {
654 case ICmpInst::ICMP_EQ:
655 // assume(v = a)
656 if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A)))) {
657 KnownBits RHSKnown = computeKnownBits(A, Depth + 1, QueryNoAC);
658 Known = Known.unionWith(RHSKnown);
659 // assume(v & b = a)
660 } else if (match(Cmp,
661 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A)))) {
662 KnownBits RHSKnown = computeKnownBits(A, Depth + 1, QueryNoAC);
663 KnownBits MaskKnown = computeKnownBits(B, Depth + 1, QueryNoAC);
664
665 // For those bits in the mask that are known to be one, we can propagate
666 // known bits from the RHS to V.
667 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
668 Known.One |= RHSKnown.One & MaskKnown.One;
669 // assume(v | b = a)
670 } else if (match(Cmp,
671 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A)))) {
672 KnownBits RHSKnown = computeKnownBits(A, Depth + 1, QueryNoAC);
673 KnownBits BKnown = computeKnownBits(B, Depth + 1, QueryNoAC);
674
675 // For those bits in B that are known to be zero, we can propagate known
676 // bits from the RHS to V.
677 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
678 Known.One |= RHSKnown.One & BKnown.Zero;
679 // assume(v ^ b = a)
680 } else if (match(Cmp,
681 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A)))) {
682 KnownBits RHSKnown = computeKnownBits(A, Depth + 1, QueryNoAC);
683 KnownBits BKnown = computeKnownBits(B, Depth + 1, QueryNoAC);
684
685 // For those bits in B that are known to be zero, we can propagate known
686 // bits from the RHS to V. For those bits in B that are known to be one,
687 // we can propagate inverted known bits from the RHS to V.
688 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
689 Known.One |= RHSKnown.One & BKnown.Zero;
690 Known.Zero |= RHSKnown.One & BKnown.One;
691 Known.One |= RHSKnown.Zero & BKnown.One;
692 // assume(v << c = a)
693 } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
694 m_Value(A))) &&
695 C < BitWidth) {
696 KnownBits RHSKnown = computeKnownBits(A, Depth + 1, QueryNoAC);
697
698 // For those bits in RHS that are known, we can propagate them to known
699 // bits in V shifted to the right by C.
700 RHSKnown.Zero.lshrInPlace(C);
701 RHSKnown.One.lshrInPlace(C);
702 Known = Known.unionWith(RHSKnown);
703 // assume(v >> c = a)
704 } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
705 m_Value(A))) &&
706 C < BitWidth) {
707 KnownBits RHSKnown = computeKnownBits(A, Depth + 1, QueryNoAC);
708 // For those bits in RHS that are known, we can propagate them to known
709 // bits in V shifted to the right by C.
710 Known.Zero |= RHSKnown.Zero << C;
711 Known.One |= RHSKnown.One << C;
712 }
713 break;
714 case ICmpInst::ICMP_NE: {
715 // assume (v & b != 0) where b is a power of 2
716 const APInt *BPow2;
717 if (match(Cmp, m_ICmp(Pred, m_c_And(m_V, m_Power2(BPow2)), m_Zero()))) {
718 Known.One |= *BPow2;
719 }
720 break;
721 }
722 default:
723 const APInt *Offset = nullptr;
724 if (match(Cmp, m_ICmp(Pred, m_CombineOr(m_V, m_Add(m_V, m_APInt(Offset))),
725 m_Value(A)))) {
726 KnownBits RHSKnown = computeKnownBits(A, Depth + 1, QueryNoAC);
727 ConstantRange RHSRange =
728 ConstantRange::fromKnownBits(RHSKnown, Cmp->isSigned());
729 ConstantRange LHSRange =
731 if (Offset)
732 LHSRange = LHSRange.sub(*Offset);
733 Known = Known.unionWith(LHSRange.toKnownBits());
734 }
735 break;
736 }
737}
738
740 unsigned Depth, const SimplifyQuery &Q) {
741 // Use of assumptions is context-sensitive. If we don't have a context, we
742 // cannot use them!
743 if (!Q.AC || !Q.CxtI)
744 return;
745
746 unsigned BitWidth = Known.getBitWidth();
747
748 // Note that the patterns below need to be kept in sync with the code
749 // in AssumptionCache::updateAffectedValues.
750
751 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
752 if (!Elem.Assume)
753 continue;
754
755 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
756 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
757 "Got assumption for the wrong function!");
758
759 if (Elem.Index != AssumptionCache::ExprResultIdx) {
760 if (!V->getType()->isPointerTy())
761 continue;
763 *I, I->bundle_op_info_begin()[Elem.Index])) {
764 if (RK.WasOn == V && RK.AttrKind == Attribute::Alignment &&
765 isPowerOf2_64(RK.ArgValue) &&
767 Known.Zero.setLowBits(Log2_64(RK.ArgValue));
768 }
769 continue;
770 }
771
772 // Warning: This loop can end up being somewhat performance sensitive.
773 // We're running this loop for once for each value queried resulting in a
774 // runtime of ~O(#assumes * #values).
775
776 Value *Arg = I->getArgOperand(0);
777
778 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
779 assert(BitWidth == 1 && "assume operand is not i1?");
780 (void)BitWidth;
781 Known.setAllOnes();
782 return;
783 }
784 if (match(Arg, m_Not(m_Specific(V))) &&
786 assert(BitWidth == 1 && "assume operand is not i1?");
787 (void)BitWidth;
788 Known.setAllZero();
789 return;
790 }
791
792 // The remaining tests are all recursive, so bail out if we hit the limit.
794 continue;
795
796 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
797 if (!Cmp)
798 continue;
799
800 if (!isValidAssumeForContext(I, Q.CxtI, Q.DT))
801 continue;
802
803 computeKnownBitsFromCmp(V, Cmp, Known, Depth, Q);
804 }
805
806 // Conflicting assumption: Undefined behavior will occur on this execution
807 // path.
808 if (Known.hasConflict())
809 Known.resetAll();
810}
811
812/// Compute known bits from a shift operator, including those with a
813/// non-constant shift amount. Known is the output of this function. Known2 is a
814/// pre-allocated temporary with the same bit width as Known and on return
815/// contains the known bit of the shift value source. KF is an
816/// operator-specific function that, given the known-bits and a shift amount,
817/// compute the implied known-bits of the shift operator's result respectively
818/// for that shift amount. The results from calling KF are conservatively
819/// combined for all permitted shift amounts.
821 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
822 KnownBits &Known2, unsigned Depth, const SimplifyQuery &Q,
823 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
824 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
825 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
826 // To limit compile-time impact, only query isKnownNonZero() if we know at
827 // least something about the shift amount.
828 bool ShAmtNonZero =
829 Known.isNonZero() ||
830 (Known.getMaxValue().ult(Known.getBitWidth()) &&
831 isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q));
832 Known = KF(Known2, Known, ShAmtNonZero);
833}
834
835static KnownBits
836getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
837 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
838 unsigned Depth, const SimplifyQuery &Q) {
839 unsigned BitWidth = KnownLHS.getBitWidth();
840 KnownBits KnownOut(BitWidth);
841 bool IsAnd = false;
842 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
843 Value *X = nullptr, *Y = nullptr;
844
845 switch (I->getOpcode()) {
846 case Instruction::And:
847 KnownOut = KnownLHS & KnownRHS;
848 IsAnd = true;
849 // and(x, -x) is common idioms that will clear all but lowest set
850 // bit. If we have a single known bit in x, we can clear all bits
851 // above it.
852 // TODO: instcombine often reassociates independent `and` which can hide
853 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
854 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
855 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
856 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
857 KnownOut = KnownLHS.blsi();
858 else
859 KnownOut = KnownRHS.blsi();
860 }
861 break;
862 case Instruction::Or:
863 KnownOut = KnownLHS | KnownRHS;
864 break;
865 case Instruction::Xor:
866 KnownOut = KnownLHS ^ KnownRHS;
867 // xor(x, x-1) is common idioms that will clear all but lowest set
868 // bit. If we have a single known bit in x, we can clear all bits
869 // above it.
870 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
871 // -1 but for the purpose of demanded bits (xor(x, x-C) &
872 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
873 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
874 if (HasKnownOne &&
876 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
877 KnownOut = XBits.blsmsk();
878 }
879 break;
880 default:
881 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
882 }
883
884 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
885 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
886 // here we handle the more general case of adding any odd number by
887 // matching the form and/xor/or(x, add(x, y)) where y is odd.
888 // TODO: This could be generalized to clearing any bit set in y where the
889 // following bit is known to be unset in y.
890 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
894 KnownBits KnownY(BitWidth);
895 computeKnownBits(Y, DemandedElts, KnownY, Depth + 1, Q);
896 if (KnownY.countMinTrailingOnes() > 0) {
897 if (IsAnd)
898 KnownOut.Zero.setBit(0);
899 else
900 KnownOut.One.setBit(0);
901 }
902 }
903 return KnownOut;
904}
905
906// Public so this can be used in `SimplifyDemandedUseBits`.
908 const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS,
909 unsigned Depth, const DataLayout &DL, AssumptionCache *AC,
910 const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo) {
911 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
912 APInt DemandedElts =
913 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
914
916 I, DemandedElts, KnownLHS, KnownRHS, Depth,
917 SimplifyQuery(DL, DT, AC, safeCxtI(I, CxtI), UseInstrInfo));
918}
919
921 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
922 // Without vscale_range, we only know that vscale is non-zero.
923 if (!Attr.isValid())
925
926 unsigned AttrMin = Attr.getVScaleRangeMin();
927 // Minimum is larger than vscale width, result is always poison.
928 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
929 return ConstantRange::getEmpty(BitWidth);
930
931 APInt Min(BitWidth, AttrMin);
932 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
933 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
935
936 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
937}
938
940 const APInt &DemandedElts,
941 KnownBits &Known, unsigned Depth,
942 const SimplifyQuery &Q) {
943 unsigned BitWidth = Known.getBitWidth();
944
945 KnownBits Known2(BitWidth);
946 switch (I->getOpcode()) {
947 default: break;
948 case Instruction::Load:
949 if (MDNode *MD =
950 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
952 break;
953 case Instruction::And:
954 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
955 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
956
957 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Depth, Q);
958 break;
959 case Instruction::Or:
960 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
961 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
962
963 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Depth, Q);
964 break;
965 case Instruction::Xor:
966 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
967 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
968
969 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Depth, Q);
970 break;
971 case Instruction::Mul: {
972 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
973 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, DemandedElts,
974 Known, Known2, Depth, Q);
975 break;
976 }
977 case Instruction::UDiv: {
978 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
979 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
980 Known =
981 KnownBits::udiv(Known, Known2, Q.IIQ.isExact(cast<BinaryOperator>(I)));
982 break;
983 }
984 case Instruction::SDiv: {
985 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
986 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
987 Known =
988 KnownBits::sdiv(Known, Known2, Q.IIQ.isExact(cast<BinaryOperator>(I)));
989 break;
990 }
991 case Instruction::Select: {
992 const Value *LHS = nullptr, *RHS = nullptr;
995 computeKnownBits(RHS, Known, Depth + 1, Q);
996 computeKnownBits(LHS, Known2, Depth + 1, Q);
997 switch (SPF) {
998 default:
999 llvm_unreachable("Unhandled select pattern flavor!");
1000 case SPF_SMAX:
1001 Known = KnownBits::smax(Known, Known2);
1002 break;
1003 case SPF_SMIN:
1004 Known = KnownBits::smin(Known, Known2);
1005 break;
1006 case SPF_UMAX:
1007 Known = KnownBits::umax(Known, Known2);
1008 break;
1009 case SPF_UMIN:
1010 Known = KnownBits::umin(Known, Known2);
1011 break;
1012 }
1013 break;
1014 }
1015
1016 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1017 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1018
1019 // Only known if known in both the LHS and RHS.
1020 Known = Known.intersectWith(Known2);
1021
1022 if (SPF == SPF_ABS) {
1023 // RHS from matchSelectPattern returns the negation part of abs pattern.
1024 // If the negate has an NSW flag we can assume the sign bit of the result
1025 // will be 0 because that makes abs(INT_MIN) undefined.
1026 if (match(RHS, m_Neg(m_Specific(LHS))) &&
1027 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RHS)))
1028 Known.Zero.setSignBit();
1029 }
1030
1031 break;
1032 }
1033 case Instruction::FPTrunc:
1034 case Instruction::FPExt:
1035 case Instruction::FPToUI:
1036 case Instruction::FPToSI:
1037 case Instruction::SIToFP:
1038 case Instruction::UIToFP:
1039 break; // Can't work with floating point.
1040 case Instruction::PtrToInt:
1041 case Instruction::IntToPtr:
1042 // Fall through and handle them the same as zext/trunc.
1043 [[fallthrough]];
1044 case Instruction::ZExt:
1045 case Instruction::Trunc: {
1046 Type *SrcTy = I->getOperand(0)->getType();
1047
1048 unsigned SrcBitWidth;
1049 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1050 // which fall through here.
1051 Type *ScalarTy = SrcTy->getScalarType();
1052 SrcBitWidth = ScalarTy->isPointerTy() ?
1053 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1054 Q.DL.getTypeSizeInBits(ScalarTy);
1055
1056 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1057 Known = Known.anyextOrTrunc(SrcBitWidth);
1058 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1059 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1060 Inst && Inst->hasNonNeg() && !Known.isNegative())
1061 Known.makeNonNegative();
1062 Known = Known.zextOrTrunc(BitWidth);
1063 break;
1064 }
1065 case Instruction::BitCast: {
1066 Type *SrcTy = I->getOperand(0)->getType();
1067 if (SrcTy->isIntOrPtrTy() &&
1068 // TODO: For now, not handling conversions like:
1069 // (bitcast i64 %x to <2 x i32>)
1070 !I->getType()->isVectorTy()) {
1071 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1072 break;
1073 }
1074
1075 // Handle cast from vector integer type to scalar or vector integer.
1076 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1077 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1078 !I->getType()->isIntOrIntVectorTy() ||
1079 isa<ScalableVectorType>(I->getType()))
1080 break;
1081
1082 // Look through a cast from narrow vector elements to wider type.
1083 // Examples: v4i32 -> v2i64, v3i8 -> v24
1084 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1085 if (BitWidth % SubBitWidth == 0) {
1086 // Known bits are automatically intersected across demanded elements of a
1087 // vector. So for example, if a bit is computed as known zero, it must be
1088 // zero across all demanded elements of the vector.
1089 //
1090 // For this bitcast, each demanded element of the output is sub-divided
1091 // across a set of smaller vector elements in the source vector. To get
1092 // the known bits for an entire element of the output, compute the known
1093 // bits for each sub-element sequentially. This is done by shifting the
1094 // one-set-bit demanded elements parameter across the sub-elements for
1095 // consecutive calls to computeKnownBits. We are using the demanded
1096 // elements parameter as a mask operator.
1097 //
1098 // The known bits of each sub-element are then inserted into place
1099 // (dependent on endian) to form the full result of known bits.
1100 unsigned NumElts = DemandedElts.getBitWidth();
1101 unsigned SubScale = BitWidth / SubBitWidth;
1102 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1103 for (unsigned i = 0; i != NumElts; ++i) {
1104 if (DemandedElts[i])
1105 SubDemandedElts.setBit(i * SubScale);
1106 }
1107
1108 KnownBits KnownSrc(SubBitWidth);
1109 for (unsigned i = 0; i != SubScale; ++i) {
1110 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc,
1111 Depth + 1, Q);
1112 unsigned ShiftElt = Q.DL.isLittleEndian() ? i : SubScale - 1 - i;
1113 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1114 }
1115 }
1116 break;
1117 }
1118 case Instruction::SExt: {
1119 // Compute the bits in the result that are not present in the input.
1120 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1121
1122 Known = Known.trunc(SrcBitWidth);
1123 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1124 // If the sign bit of the input is known set or clear, then we know the
1125 // top bits of the result.
1126 Known = Known.sext(BitWidth);
1127 break;
1128 }
1129 case Instruction::Shl: {
1130 bool NUW = Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(I));
1131 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1132 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1133 bool ShAmtNonZero) {
1134 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1135 };
1136 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1137 KF);
1138 // Trailing zeros of a right-shifted constant never decrease.
1139 const APInt *C;
1140 if (match(I->getOperand(0), m_APInt(C)))
1141 Known.Zero.setLowBits(C->countr_zero());
1142 break;
1143 }
1144 case Instruction::LShr: {
1145 auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1146 bool ShAmtNonZero) {
1147 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero);
1148 };
1149 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1150 KF);
1151 // Leading zeros of a left-shifted constant never decrease.
1152 const APInt *C;
1153 if (match(I->getOperand(0), m_APInt(C)))
1154 Known.Zero.setHighBits(C->countl_zero());
1155 break;
1156 }
1157 case Instruction::AShr: {
1158 auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1159 bool ShAmtNonZero) {
1160 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero);
1161 };
1162 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1163 KF);
1164 break;
1165 }
1166 case Instruction::Sub: {
1167 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1168 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1169 DemandedElts, Known, Known2, Depth, Q);
1170 break;
1171 }
1172 case Instruction::Add: {
1173 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1174 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1175 DemandedElts, Known, Known2, Depth, Q);
1176 break;
1177 }
1178 case Instruction::SRem:
1179 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1180 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1181 Known = KnownBits::srem(Known, Known2);
1182 break;
1183
1184 case Instruction::URem:
1185 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1186 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1187 Known = KnownBits::urem(Known, Known2);
1188 break;
1189 case Instruction::Alloca:
1190 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1191 break;
1192 case Instruction::GetElementPtr: {
1193 // Analyze all of the subscripts of this getelementptr instruction
1194 // to determine if we can prove known low zero bits.
1195 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1196 // Accumulate the constant indices in a separate variable
1197 // to minimize the number of calls to computeForAddSub.
1198 APInt AccConstIndices(BitWidth, 0, /*IsSigned*/ true);
1199
1201 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1202 // TrailZ can only become smaller, short-circuit if we hit zero.
1203 if (Known.isUnknown())
1204 break;
1205
1206 Value *Index = I->getOperand(i);
1207
1208 // Handle case when index is zero.
1209 Constant *CIndex = dyn_cast<Constant>(Index);
1210 if (CIndex && CIndex->isZeroValue())
1211 continue;
1212
1213 if (StructType *STy = GTI.getStructTypeOrNull()) {
1214 // Handle struct member offset arithmetic.
1215
1216 assert(CIndex &&
1217 "Access to structure field must be known at compile time");
1218
1219 if (CIndex->getType()->isVectorTy())
1220 Index = CIndex->getSplatValue();
1221
1222 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1223 const StructLayout *SL = Q.DL.getStructLayout(STy);
1225 AccConstIndices += Offset;
1226 continue;
1227 }
1228
1229 // Handle array index arithmetic.
1230 Type *IndexedTy = GTI.getIndexedType();
1231 if (!IndexedTy->isSized()) {
1232 Known.resetAll();
1233 break;
1234 }
1235
1236 unsigned IndexBitWidth = Index->getType()->getScalarSizeInBits();
1237 KnownBits IndexBits(IndexBitWidth);
1238 computeKnownBits(Index, IndexBits, Depth + 1, Q);
1239 TypeSize IndexTypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1240 uint64_t TypeSizeInBytes = IndexTypeSize.getKnownMinValue();
1241 KnownBits ScalingFactor(IndexBitWidth);
1242 // Multiply by current sizeof type.
1243 // &A[i] == A + i * sizeof(*A[i]).
1244 if (IndexTypeSize.isScalable()) {
1245 // For scalable types the only thing we know about sizeof is
1246 // that this is a multiple of the minimum size.
1247 ScalingFactor.Zero.setLowBits(llvm::countr_zero(TypeSizeInBytes));
1248 } else if (IndexBits.isConstant()) {
1249 APInt IndexConst = IndexBits.getConstant();
1250 APInt ScalingFactor(IndexBitWidth, TypeSizeInBytes);
1251 IndexConst *= ScalingFactor;
1252 AccConstIndices += IndexConst.sextOrTrunc(BitWidth);
1253 continue;
1254 } else {
1255 ScalingFactor =
1256 KnownBits::makeConstant(APInt(IndexBitWidth, TypeSizeInBytes));
1257 }
1258 IndexBits = KnownBits::mul(IndexBits, ScalingFactor);
1259
1260 // If the offsets have a different width from the pointer, according
1261 // to the language reference we need to sign-extend or truncate them
1262 // to the width of the pointer.
1263 IndexBits = IndexBits.sextOrTrunc(BitWidth);
1264
1265 // Note that inbounds does *not* guarantee nsw for the addition, as only
1266 // the offset is signed, while the base address is unsigned.
1268 /*Add=*/true, /*NSW=*/false, Known, IndexBits);
1269 }
1270 if (!Known.isUnknown() && !AccConstIndices.isZero()) {
1271 KnownBits Index = KnownBits::makeConstant(AccConstIndices);
1273 /*Add=*/true, /*NSW=*/false, Known, Index);
1274 }
1275 break;
1276 }
1277 case Instruction::PHI: {
1278 const PHINode *P = cast<PHINode>(I);
1279 BinaryOperator *BO = nullptr;
1280 Value *R = nullptr, *L = nullptr;
1281 if (matchSimpleRecurrence(P, BO, R, L)) {
1282 // Handle the case of a simple two-predecessor recurrence PHI.
1283 // There's a lot more that could theoretically be done here, but
1284 // this is sufficient to catch some interesting cases.
1285 unsigned Opcode = BO->getOpcode();
1286
1287 // If this is a shift recurrence, we know the bits being shifted in.
1288 // We can combine that with information about the start value of the
1289 // recurrence to conclude facts about the result.
1290 if ((Opcode == Instruction::LShr || Opcode == Instruction::AShr ||
1291 Opcode == Instruction::Shl) &&
1292 BO->getOperand(0) == I) {
1293
1294 // We have matched a recurrence of the form:
1295 // %iv = [R, %entry], [%iv.next, %backedge]
1296 // %iv.next = shift_op %iv, L
1297
1298 // Recurse with the phi context to avoid concern about whether facts
1299 // inferred hold at original context instruction. TODO: It may be
1300 // correct to use the original context. IF warranted, explore and
1301 // add sufficient tests to cover.
1302 SimplifyQuery RecQ = Q;
1303 RecQ.CxtI = P;
1304 computeKnownBits(R, DemandedElts, Known2, Depth + 1, RecQ);
1305 switch (Opcode) {
1306 case Instruction::Shl:
1307 // A shl recurrence will only increase the tailing zeros
1308 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1309 break;
1310 case Instruction::LShr:
1311 // A lshr recurrence will preserve the leading zeros of the
1312 // start value
1313 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1314 break;
1315 case Instruction::AShr:
1316 // An ashr recurrence will extend the initial sign bit
1317 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1318 Known.One.setHighBits(Known2.countMinLeadingOnes());
1319 break;
1320 };
1321 }
1322
1323 // Check for operations that have the property that if
1324 // both their operands have low zero bits, the result
1325 // will have low zero bits.
1326 if (Opcode == Instruction::Add ||
1327 Opcode == Instruction::Sub ||
1328 Opcode == Instruction::And ||
1329 Opcode == Instruction::Or ||
1330 Opcode == Instruction::Mul) {
1331 // Change the context instruction to the "edge" that flows into the
1332 // phi. This is important because that is where the value is actually
1333 // "evaluated" even though it is used later somewhere else. (see also
1334 // D69571).
1335 SimplifyQuery RecQ = Q;
1336
1337 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1338 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1339 Instruction *LInst = P->getIncomingBlock(1-OpNum)->getTerminator();
1340
1341 // Ok, we have a PHI of the form L op= R. Check for low
1342 // zero bits.
1343 RecQ.CxtI = RInst;
1344 computeKnownBits(R, Known2, Depth + 1, RecQ);
1345
1346 // We need to take the minimum number of known bits
1347 KnownBits Known3(BitWidth);
1348 RecQ.CxtI = LInst;
1349 computeKnownBits(L, Known3, Depth + 1, RecQ);
1350
1351 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1352 Known3.countMinTrailingZeros()));
1353
1354 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1355 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
1356 // If initial value of recurrence is nonnegative, and we are adding
1357 // a nonnegative number with nsw, the result can only be nonnegative
1358 // or poison value regardless of the number of times we execute the
1359 // add in phi recurrence. If initial value is negative and we are
1360 // adding a negative number with nsw, the result can only be
1361 // negative or poison value. Similar arguments apply to sub and mul.
1362 //
1363 // (add non-negative, non-negative) --> non-negative
1364 // (add negative, negative) --> negative
1365 if (Opcode == Instruction::Add) {
1366 if (Known2.isNonNegative() && Known3.isNonNegative())
1367 Known.makeNonNegative();
1368 else if (Known2.isNegative() && Known3.isNegative())
1369 Known.makeNegative();
1370 }
1371
1372 // (sub nsw non-negative, negative) --> non-negative
1373 // (sub nsw negative, non-negative) --> negative
1374 else if (Opcode == Instruction::Sub && BO->getOperand(0) == I) {
1375 if (Known2.isNonNegative() && Known3.isNegative())
1376 Known.makeNonNegative();
1377 else if (Known2.isNegative() && Known3.isNonNegative())
1378 Known.makeNegative();
1379 }
1380
1381 // (mul nsw non-negative, non-negative) --> non-negative
1382 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1383 Known3.isNonNegative())
1384 Known.makeNonNegative();
1385 }
1386
1387 break;
1388 }
1389 }
1390
1391 // Unreachable blocks may have zero-operand PHI nodes.
1392 if (P->getNumIncomingValues() == 0)
1393 break;
1394
1395 // Otherwise take the unions of the known bit sets of the operands,
1396 // taking conservative care to avoid excessive recursion.
1397 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1398 // Skip if every incoming value references to ourself.
1399 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1400 break;
1401
1402 Known.Zero.setAllBits();
1403 Known.One.setAllBits();
1404 for (unsigned u = 0, e = P->getNumIncomingValues(); u < e; ++u) {
1405 Value *IncValue = P->getIncomingValue(u);
1406 // Skip direct self references.
1407 if (IncValue == P) continue;
1408
1409 // Change the context instruction to the "edge" that flows into the
1410 // phi. This is important because that is where the value is actually
1411 // "evaluated" even though it is used later somewhere else. (see also
1412 // D69571).
1413 SimplifyQuery RecQ = Q;
1414 RecQ.CxtI = P->getIncomingBlock(u)->getTerminator();
1415
1416 Known2 = KnownBits(BitWidth);
1417
1418 // Recurse, but cap the recursion to one level, because we don't
1419 // want to waste time spinning around in loops.
1420 // TODO: See if we can base recursion limiter on number of incoming phi
1421 // edges so we don't overly clamp analysis.
1422 computeKnownBits(IncValue, Known2, MaxAnalysisRecursionDepth - 1, RecQ);
1423
1424 // See if we can further use a conditional branch into the phi
1425 // to help us determine the range of the value.
1426 if (!Known2.isConstant()) {
1428 const APInt *RHSC;
1429 BasicBlock *TrueSucc, *FalseSucc;
1430 // TODO: Use RHS Value and compute range from its known bits.
1431 if (match(RecQ.CxtI,
1432 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1433 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1434 // Check for cases of duplicate successors.
1435 if ((TrueSucc == P->getParent()) != (FalseSucc == P->getParent())) {
1436 // If we're using the false successor, invert the predicate.
1437 if (FalseSucc == P->getParent())
1438 Pred = CmpInst::getInversePredicate(Pred);
1439 // Get the knownbits implied by the incoming phi condition.
1440 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
1441 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
1442 // We can have conflicts here if we are analyzing deadcode (its
1443 // impossible for us reach this BB based the icmp).
1444 if (KnownUnion.hasConflict()) {
1445 // No reason to continue analyzing in a known dead region, so
1446 // just resetAll and break. This will cause us to also exit the
1447 // outer loop.
1448 Known.resetAll();
1449 break;
1450 }
1451 Known2 = KnownUnion;
1452 }
1453 }
1454 }
1455
1456 Known = Known.intersectWith(Known2);
1457 // If all bits have been ruled out, there's no need to check
1458 // more operands.
1459 if (Known.isUnknown())
1460 break;
1461 }
1462 }
1463 break;
1464 }
1465 case Instruction::Call:
1466 case Instruction::Invoke:
1467 // If range metadata is attached to this call, set known bits from that,
1468 // and then intersect with known bits based on other properties of the
1469 // function.
1470 if (MDNode *MD =
1471 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
1473 if (const Value *RV = cast<CallBase>(I)->getReturnedArgOperand()) {
1474 computeKnownBits(RV, Known2, Depth + 1, Q);
1475 Known = Known.unionWith(Known2);
1476 }
1477 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1478 switch (II->getIntrinsicID()) {
1479 default: break;
1480 case Intrinsic::abs: {
1481 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1482 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
1483 Known = Known2.abs(IntMinIsPoison);
1484 break;
1485 }
1486 case Intrinsic::bitreverse:
1487 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1488 Known.Zero |= Known2.Zero.reverseBits();
1489 Known.One |= Known2.One.reverseBits();
1490 break;
1491 case Intrinsic::bswap:
1492 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1493 Known.Zero |= Known2.Zero.byteSwap();
1494 Known.One |= Known2.One.byteSwap();
1495 break;
1496 case Intrinsic::ctlz: {
1497 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1498 // If we have a known 1, its position is our upper bound.
1499 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
1500 // If this call is poison for 0 input, the result will be less than 2^n.
1501 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1502 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1503 unsigned LowBits = llvm::bit_width(PossibleLZ);
1504 Known.Zero.setBitsFrom(LowBits);
1505 break;
1506 }
1507 case Intrinsic::cttz: {
1508 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1509 // If we have a known 1, its position is our upper bound.
1510 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
1511 // If this call is poison for 0 input, the result will be less than 2^n.
1512 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1513 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1514 unsigned LowBits = llvm::bit_width(PossibleTZ);
1515 Known.Zero.setBitsFrom(LowBits);
1516 break;
1517 }
1518 case Intrinsic::ctpop: {
1519 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1520 // We can bound the space the count needs. Also, bits known to be zero
1521 // can't contribute to the population.
1522 unsigned BitsPossiblySet = Known2.countMaxPopulation();
1523 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
1524 Known.Zero.setBitsFrom(LowBits);
1525 // TODO: we could bound KnownOne using the lower bound on the number
1526 // of bits which might be set provided by popcnt KnownOne2.
1527 break;
1528 }
1529 case Intrinsic::fshr:
1530 case Intrinsic::fshl: {
1531 const APInt *SA;
1532 if (!match(I->getOperand(2), m_APInt(SA)))
1533 break;
1534
1535 // Normalize to funnel shift left.
1536 uint64_t ShiftAmt = SA->urem(BitWidth);
1537 if (II->getIntrinsicID() == Intrinsic::fshr)
1538 ShiftAmt = BitWidth - ShiftAmt;
1539
1540 KnownBits Known3(BitWidth);
1541 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1542 computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1543
1544 Known.Zero =
1545 Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1546 Known.One =
1547 Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1548 break;
1549 }
1550 case Intrinsic::uadd_sat:
1551 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1552 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1553 Known = KnownBits::uadd_sat(Known, Known2);
1554 break;
1555 case Intrinsic::usub_sat:
1556 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1557 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1558 Known = KnownBits::usub_sat(Known, Known2);
1559 break;
1560 case Intrinsic::sadd_sat:
1561 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1562 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1563 Known = KnownBits::sadd_sat(Known, Known2);
1564 break;
1565 case Intrinsic::ssub_sat:
1566 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1567 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1568 Known = KnownBits::ssub_sat(Known, Known2);
1569 break;
1570 case Intrinsic::umin:
1571 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1572 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1573 Known = KnownBits::umin(Known, Known2);
1574 break;
1575 case Intrinsic::umax:
1576 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1577 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1578 Known = KnownBits::umax(Known, Known2);
1579 break;
1580 case Intrinsic::smin:
1581 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1582 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1583 Known = KnownBits::smin(Known, Known2);
1584 break;
1585 case Intrinsic::smax:
1586 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1587 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1588 Known = KnownBits::smax(Known, Known2);
1589 break;
1590 case Intrinsic::ptrmask: {
1591 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1592
1593 const Value *Mask = I->getOperand(1);
1594 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
1595 computeKnownBits(Mask, Known2, Depth + 1, Q);
1596 // TODO: 1-extend would be more precise.
1597 Known &= Known2.anyextOrTrunc(BitWidth);
1598 break;
1599 }
1600 case Intrinsic::x86_sse42_crc32_64_64:
1601 Known.Zero.setBitsFrom(32);
1602 break;
1603 case Intrinsic::riscv_vsetvli:
1604 case Intrinsic::riscv_vsetvlimax:
1605 // Assume that VL output is >= 65536.
1606 // TODO: Take SEW and LMUL into account.
1607 if (BitWidth > 17)
1608 Known.Zero.setBitsFrom(17);
1609 break;
1610 case Intrinsic::vscale: {
1611 if (!II->getParent() || !II->getFunction())
1612 break;
1613
1614 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
1615 break;
1616 }
1617 }
1618 }
1619 break;
1620 case Instruction::ShuffleVector: {
1621 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
1622 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
1623 if (!Shuf) {
1624 Known.resetAll();
1625 return;
1626 }
1627 // For undef elements, we don't know anything about the common state of
1628 // the shuffle result.
1629 APInt DemandedLHS, DemandedRHS;
1630 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
1631 Known.resetAll();
1632 return;
1633 }
1634 Known.One.setAllBits();
1635 Known.Zero.setAllBits();
1636 if (!!DemandedLHS) {
1637 const Value *LHS = Shuf->getOperand(0);
1638 computeKnownBits(LHS, DemandedLHS, Known, Depth + 1, Q);
1639 // If we don't know any bits, early out.
1640 if (Known.isUnknown())
1641 break;
1642 }
1643 if (!!DemandedRHS) {
1644 const Value *RHS = Shuf->getOperand(1);
1645 computeKnownBits(RHS, DemandedRHS, Known2, Depth + 1, Q);
1646 Known = Known.intersectWith(Known2);
1647 }
1648 break;
1649 }
1650 case Instruction::InsertElement: {
1651 if (isa<ScalableVectorType>(I->getType())) {
1652 Known.resetAll();
1653 return;
1654 }
1655 const Value *Vec = I->getOperand(0);
1656 const Value *Elt = I->getOperand(1);
1657 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
1658 // Early out if the index is non-constant or out-of-range.
1659 unsigned NumElts = DemandedElts.getBitWidth();
1660 if (!CIdx || CIdx->getValue().uge(NumElts)) {
1661 Known.resetAll();
1662 return;
1663 }
1664 Known.One.setAllBits();
1665 Known.Zero.setAllBits();
1666 unsigned EltIdx = CIdx->getZExtValue();
1667 // Do we demand the inserted element?
1668 if (DemandedElts[EltIdx]) {
1669 computeKnownBits(Elt, Known, Depth + 1, Q);
1670 // If we don't know any bits, early out.
1671 if (Known.isUnknown())
1672 break;
1673 }
1674 // We don't need the base vector element that has been inserted.
1675 APInt DemandedVecElts = DemandedElts;
1676 DemandedVecElts.clearBit(EltIdx);
1677 if (!!DemandedVecElts) {
1678 computeKnownBits(Vec, DemandedVecElts, Known2, Depth + 1, Q);
1679 Known = Known.intersectWith(Known2);
1680 }
1681 break;
1682 }
1683 case Instruction::ExtractElement: {
1684 // Look through extract element. If the index is non-constant or
1685 // out-of-range demand all elements, otherwise just the extracted element.
1686 const Value *Vec = I->getOperand(0);
1687 const Value *Idx = I->getOperand(1);
1688 auto *CIdx = dyn_cast<ConstantInt>(Idx);
1689 if (isa<ScalableVectorType>(Vec->getType())) {
1690 // FIXME: there's probably *something* we can do with scalable vectors
1691 Known.resetAll();
1692 break;
1693 }
1694 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1695 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
1696 if (CIdx && CIdx->getValue().ult(NumElts))
1697 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
1698 computeKnownBits(Vec, DemandedVecElts, Known, Depth + 1, Q);
1699 break;
1700 }
1701 case Instruction::ExtractValue:
1702 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1703 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1704 if (EVI->getNumIndices() != 1) break;
1705 if (EVI->getIndices()[0] == 0) {
1706 switch (II->getIntrinsicID()) {
1707 default: break;
1708 case Intrinsic::uadd_with_overflow:
1709 case Intrinsic::sadd_with_overflow:
1710 computeKnownBitsAddSub(true, II->getArgOperand(0),
1711 II->getArgOperand(1), false, DemandedElts,
1712 Known, Known2, Depth, Q);
1713 break;
1714 case Intrinsic::usub_with_overflow:
1715 case Intrinsic::ssub_with_overflow:
1716 computeKnownBitsAddSub(false, II->getArgOperand(0),
1717 II->getArgOperand(1), false, DemandedElts,
1718 Known, Known2, Depth, Q);
1719 break;
1720 case Intrinsic::umul_with_overflow:
1721 case Intrinsic::smul_with_overflow:
1722 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1723 DemandedElts, Known, Known2, Depth, Q);
1724 break;
1725 }
1726 }
1727 }
1728 break;
1729 case Instruction::Freeze:
1730 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
1731 Depth + 1))
1732 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1733 break;
1734 }
1735}
1736
1737/// Determine which bits of V are known to be either zero or one and return
1738/// them.
1739KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
1740 unsigned Depth, const SimplifyQuery &Q) {
1741 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1742 ::computeKnownBits(V, DemandedElts, Known, Depth, Q);
1743 return Known;
1744}
1745
1746/// Determine which bits of V are known to be either zero or one and return
1747/// them.
1749 const SimplifyQuery &Q) {
1750 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1751 ::computeKnownBits(V, Known, Depth, Q);
1752 return Known;
1753}
1754
1755/// Determine which bits of V are known to be either zero or one and return
1756/// them in the Known bit set.
1757///
1758/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1759/// we cannot optimize based on the assumption that it is zero without changing
1760/// it to be an explicit zero. If we don't change it to zero, other code could
1761/// optimized based on the contradictory assumption that it is non-zero.
1762/// Because instcombine aggressively folds operations with undef args anyway,
1763/// this won't lose us code quality.
1764///
1765/// This function is defined on values with integer type, values with pointer
1766/// type, and vectors of integers. In the case
1767/// where V is a vector, known zero, and known one values are the
1768/// same width as the vector element, and the bit is set only if it is true
1769/// for all of the demanded elements in the vector specified by DemandedElts.
1770void computeKnownBits(const Value *V, const APInt &DemandedElts,
1771 KnownBits &Known, unsigned Depth,
1772 const SimplifyQuery &Q) {
1773 if (!DemandedElts) {
1774 // No demanded elts, better to assume we don't know anything.
1775 Known.resetAll();
1776 return;
1777 }
1778
1779 assert(V && "No Value?");
1780 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1781
1782#ifndef NDEBUG
1783 Type *Ty = V->getType();
1784 unsigned BitWidth = Known.getBitWidth();
1785
1787 "Not integer or pointer type!");
1788
1789 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
1790 assert(
1791 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
1792 "DemandedElt width should equal the fixed vector number of elements");
1793 } else {
1794 assert(DemandedElts == APInt(1, 1) &&
1795 "DemandedElt width should be 1 for scalars or scalable vectors");
1796 }
1797
1798 Type *ScalarTy = Ty->getScalarType();
1799 if (ScalarTy->isPointerTy()) {
1800 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
1801 "V and Known should have same BitWidth");
1802 } else {
1803 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
1804 "V and Known should have same BitWidth");
1805 }
1806#endif
1807
1808 const APInt *C;
1809 if (match(V, m_APInt(C))) {
1810 // We know all of the bits for a scalar constant or a splat vector constant!
1811 Known = KnownBits::makeConstant(*C);
1812 return;
1813 }
1814 // Null and aggregate-zero are all-zeros.
1815 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1816 Known.setAllZero();
1817 return;
1818 }
1819 // Handle a constant vector by taking the intersection of the known bits of
1820 // each element.
1821 if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
1822 assert(!isa<ScalableVectorType>(V->getType()));
1823 // We know that CDV must be a vector of integers. Take the intersection of
1824 // each element.
1825 Known.Zero.setAllBits(); Known.One.setAllBits();
1826 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
1827 if (!DemandedElts[i])
1828 continue;
1829 APInt Elt = CDV->getElementAsAPInt(i);
1830 Known.Zero &= ~Elt;
1831 Known.One &= Elt;
1832 }
1833 return;
1834 }
1835
1836 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1837 assert(!isa<ScalableVectorType>(V->getType()));
1838 // We know that CV must be a vector of integers. Take the intersection of
1839 // each element.
1840 Known.Zero.setAllBits(); Known.One.setAllBits();
1841 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1842 if (!DemandedElts[i])
1843 continue;
1844 Constant *Element = CV->getAggregateElement(i);
1845 if (isa<PoisonValue>(Element))
1846 continue;
1847 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1848 if (!ElementCI) {
1849 Known.resetAll();
1850 return;
1851 }
1852 const APInt &Elt = ElementCI->getValue();
1853 Known.Zero &= ~Elt;
1854 Known.One &= Elt;
1855 }
1856 return;
1857 }
1858
1859 // Start out not knowing anything.
1860 Known.resetAll();
1861
1862 // We can't imply anything about undefs.
1863 if (isa<UndefValue>(V))
1864 return;
1865
1866 // There's no point in looking through other users of ConstantData for
1867 // assumptions. Confirm that we've handled them all.
1868 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1869
1870 // All recursive calls that increase depth must come after this.
1872 return;
1873
1874 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1875 // the bits of its aliasee.
1876 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1877 if (!GA->isInterposable())
1878 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
1879 return;
1880 }
1881
1882 if (const Operator *I = dyn_cast<Operator>(V))
1883 computeKnownBitsFromOperator(I, DemandedElts, Known, Depth, Q);
1884 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1885 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
1886 Known = CR->toKnownBits();
1887 }
1888
1889 // Aligned pointers have trailing zeros - refine Known.Zero set
1890 if (isa<PointerType>(V->getType())) {
1891 Align Alignment = V->getPointerAlignment(Q.DL);
1892 Known.Zero.setLowBits(Log2(Alignment));
1893 }
1894
1895 // computeKnownBitsFromAssume strictly refines Known.
1896 // Therefore, we run them after computeKnownBitsFromOperator.
1897
1898 // Check whether a nearby assume intrinsic can determine some known bits.
1899 computeKnownBitsFromAssume(V, Known, Depth, Q);
1900
1901 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
1902}
1903
1904/// Try to detect a recurrence that the value of the induction variable is
1905/// always a power of two (or zero).
1906static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
1907 unsigned Depth, SimplifyQuery &Q) {
1908 BinaryOperator *BO = nullptr;
1909 Value *Start = nullptr, *Step = nullptr;
1910 if (!matchSimpleRecurrence(PN, BO, Start, Step))
1911 return false;
1912
1913 // Initial value must be a power of two.
1914 for (const Use &U : PN->operands()) {
1915 if (U.get() == Start) {
1916 // Initial value comes from a different BB, need to adjust context
1917 // instruction for analysis.
1918 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
1919 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Depth, Q))
1920 return false;
1921 }
1922 }
1923
1924 // Except for Mul, the induction variable must be on the left side of the
1925 // increment expression, otherwise its value can be arbitrary.
1926 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
1927 return false;
1928
1929 Q.CxtI = BO->getParent()->getTerminator();
1930 switch (BO->getOpcode()) {
1931 case Instruction::Mul:
1932 // Power of two is closed under multiplication.
1933 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
1934 Q.IIQ.hasNoSignedWrap(BO)) &&
1935 isKnownToBeAPowerOfTwo(Step, OrZero, Depth, Q);
1936 case Instruction::SDiv:
1937 // Start value must not be signmask for signed division, so simply being a
1938 // power of two is not sufficient, and it has to be a constant.
1939 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
1940 return false;
1941 [[fallthrough]];
1942 case Instruction::UDiv:
1943 // Divisor must be a power of two.
1944 // If OrZero is false, cannot guarantee induction variable is non-zero after
1945 // division, same for Shr, unless it is exact division.
1946 return (OrZero || Q.IIQ.isExact(BO)) &&
1947 isKnownToBeAPowerOfTwo(Step, false, Depth, Q);
1948 case Instruction::Shl:
1949 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
1950 case Instruction::AShr:
1951 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
1952 return false;
1953 [[fallthrough]];
1954 case Instruction::LShr:
1955 return OrZero || Q.IIQ.isExact(BO);
1956 default:
1957 return false;
1958 }
1959}
1960
1961/// Return true if the given value is known to have exactly one
1962/// bit set when defined. For vectors return true if every element is known to
1963/// be a power of two when defined. Supports values with integer or pointer
1964/// types and vectors of integers.
1965bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
1966 const SimplifyQuery &Q) {
1967 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
1968
1969 if (isa<Constant>(V))
1970 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
1971
1972 // i1 is by definition a power of 2 or zero.
1973 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
1974 return true;
1975
1976 auto *I = dyn_cast<Instruction>(V);
1977 if (!I)
1978 return false;
1979
1980 if (Q.CxtI && match(V, m_VScale())) {
1981 const Function *F = Q.CxtI->getFunction();
1982 // The vscale_range indicates vscale is a power-of-two.
1983 return F->hasFnAttribute(Attribute::VScaleRange);
1984 }
1985
1986 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1987 // it is shifted off the end then the result is undefined.
1988 if (match(I, m_Shl(m_One(), m_Value())))
1989 return true;
1990
1991 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1992 // the bottom. If it is shifted off the bottom then the result is undefined.
1993 if (match(I, m_LShr(m_SignMask(), m_Value())))
1994 return true;
1995
1996 // The remaining tests are all recursive, so bail out if we hit the limit.
1998 return false;
1999
2000 switch (I->getOpcode()) {
2001 case Instruction::ZExt:
2002 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Depth, Q);
2003 case Instruction::Trunc:
2004 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Depth, Q);
2005 case Instruction::Shl:
2006 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2007 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Depth, Q);
2008 return false;
2009 case Instruction::LShr:
2010 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2011 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Depth, Q);
2012 return false;
2013 case Instruction::UDiv:
2014 if (Q.IIQ.isExact(cast<BinaryOperator>(I)))
2015 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Depth, Q);
2016 return false;
2017 case Instruction::Mul:
2018 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Depth, Q) &&
2019 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Depth, Q) &&
2020 (OrZero || isKnownNonZero(I, Depth, Q));
2021 case Instruction::And:
2022 // A power of two and'd with anything is a power of two or zero.
2023 if (OrZero &&
2024 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Depth, Q) ||
2025 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Depth, Q)))
2026 return true;
2027 // X & (-X) is always a power of two or zero.
2028 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2029 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2030 return OrZero || isKnownNonZero(I->getOperand(0), Depth, Q);
2031 return false;
2032 case Instruction::Add: {
2033 // Adding a power-of-two or zero to the same power-of-two or zero yields
2034 // either the original power-of-two, a larger power-of-two or zero.
2035 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
2036 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2037 Q.IIQ.hasNoSignedWrap(VOBO)) {
2038 if (match(I->getOperand(0),
2039 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2040 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Depth, Q))
2041 return true;
2042 if (match(I->getOperand(1),
2043 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2044 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Depth, Q))
2045 return true;
2046
2047 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2048 KnownBits LHSBits(BitWidth);
2049 computeKnownBits(I->getOperand(0), LHSBits, Depth, Q);
2050
2051 KnownBits RHSBits(BitWidth);
2052 computeKnownBits(I->getOperand(1), RHSBits, Depth, Q);
2053 // If i8 V is a power of two or zero:
2054 // ZeroBits: 1 1 1 0 1 1 1 1
2055 // ~ZeroBits: 0 0 0 1 0 0 0 0
2056 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2057 // If OrZero isn't set, we cannot give back a zero result.
2058 // Make sure either the LHS or RHS has a bit set.
2059 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2060 return true;
2061 }
2062 return false;
2063 }
2064 case Instruction::Select:
2065 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Depth, Q) &&
2066 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Depth, Q);
2067 case Instruction::PHI: {
2068 // A PHI node is power of two if all incoming values are power of two, or if
2069 // it is an induction variable where in each step its value is a power of
2070 // two.
2071 auto *PN = cast<PHINode>(I);
2072 SimplifyQuery RecQ = Q;
2073
2074 // Check if it is an induction variable and always power of two.
2075 if (isPowerOfTwoRecurrence(PN, OrZero, Depth, RecQ))
2076 return true;
2077
2078 // Recursively check all incoming values. Limit recursion to 2 levels, so
2079 // that search complexity is limited to number of operands^2.
2080 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2081 return llvm::all_of(PN->operands(), [&](const Use &U) {
2082 // Value is power of 2 if it is coming from PHI node itself by induction.
2083 if (U.get() == PN)
2084 return true;
2085
2086 // Change the context instruction to the incoming block where it is
2087 // evaluated.
2088 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2089 return isKnownToBeAPowerOfTwo(U.get(), OrZero, NewDepth, RecQ);
2090 });
2091 }
2092 case Instruction::Invoke:
2093 case Instruction::Call: {
2094 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2095 switch (II->getIntrinsicID()) {
2096 case Intrinsic::umax:
2097 case Intrinsic::smax:
2098 case Intrinsic::umin:
2099 case Intrinsic::smin:
2100 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Depth, Q) &&
2101 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Depth, Q);
2102 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2103 // thus dont change pow2/non-pow2 status.
2104 case Intrinsic::bitreverse:
2105 case Intrinsic::bswap:
2106 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Depth, Q);
2107 case Intrinsic::fshr:
2108 case Intrinsic::fshl:
2109 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2110 if (II->getArgOperand(0) == II->getArgOperand(1))
2111 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Depth, Q);
2112 break;
2113 default:
2114 break;
2115 }
2116 }
2117 return false;
2118 }
2119 default:
2120 return false;
2121 }
2122}
2123
2124/// Test whether a GEP's result is known to be non-null.
2125///
2126/// Uses properties inherent in a GEP to try to determine whether it is known
2127/// to be non-null.
2128///
2129/// Currently this routine does not support vector GEPs.
2130static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
2131 const SimplifyQuery &Q) {
2132 const Function *F = nullptr;
2133 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2134 F = I->getFunction();
2135
2136 if (!GEP->isInBounds() ||
2137 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
2138 return false;
2139
2140 // FIXME: Support vector-GEPs.
2141 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2142
2143 // If the base pointer is non-null, we cannot walk to a null address with an
2144 // inbounds GEP in address space zero.
2145 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
2146 return true;
2147
2148 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2149 // If so, then the GEP cannot produce a null pointer, as doing so would
2150 // inherently violate the inbounds contract within address space zero.
2152 GTI != GTE; ++GTI) {
2153 // Struct types are easy -- they must always be indexed by a constant.
2154 if (StructType *STy = GTI.getStructTypeOrNull()) {
2155 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2156 unsigned ElementIdx = OpC->getZExtValue();
2157 const StructLayout *SL = Q.DL.getStructLayout(STy);
2158 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2159 if (ElementOffset > 0)
2160 return true;
2161 continue;
2162 }
2163
2164 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2165 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()).isZero())
2166 continue;
2167
2168 // Fast path the constant operand case both for efficiency and so we don't
2169 // increment Depth when just zipping down an all-constant GEP.
2170 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2171 if (!OpC->isZero())
2172 return true;
2173 continue;
2174 }
2175
2176 // We post-increment Depth here because while isKnownNonZero increments it
2177 // as well, when we pop back up that increment won't persist. We don't want
2178 // to recurse 10k times just because we have 10k GEP operands. We don't
2179 // bail completely out because we want to handle constant GEPs regardless
2180 // of depth.
2182 continue;
2183
2184 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
2185 return true;
2186 }
2187
2188 return false;
2189}
2190
2192 const Instruction *CtxI,
2193 const DominatorTree *DT) {
2194 assert(!isa<Constant>(V) && "Called for constant?");
2195
2196 if (!CtxI || !DT)
2197 return false;
2198
2199 unsigned NumUsesExplored = 0;
2200 for (const auto *U : V->users()) {
2201 // Avoid massive lists
2202 if (NumUsesExplored >= DomConditionsMaxUses)
2203 break;
2204 NumUsesExplored++;
2205
2206 // If the value is used as an argument to a call or invoke, then argument
2207 // attributes may provide an answer about null-ness.
2208 if (const auto *CB = dyn_cast<CallBase>(U))
2209 if (auto *CalledFunc = CB->getCalledFunction())
2210 for (const Argument &Arg : CalledFunc->args())
2211 if (CB->getArgOperand(Arg.getArgNo()) == V &&
2212 Arg.hasNonNullAttr(/* AllowUndefOrPoison */ false) &&
2213 DT->dominates(CB, CtxI))
2214 return true;
2215
2216 // If the value is used as a load/store, then the pointer must be non null.
2217 if (V == getLoadStorePointerOperand(U)) {
2218 const Instruction *I = cast<Instruction>(U);
2219 if (!NullPointerIsDefined(I->getFunction(),
2220 V->getType()->getPointerAddressSpace()) &&
2221 DT->dominates(I, CtxI))
2222 return true;
2223 }
2224
2225 if (match(U, m_IDiv(m_Value(), m_Specific(V))) &&
2226 isValidAssumeForContext(cast<Instruction>(U), CtxI, DT))
2227 return true;
2228
2229 // Consider only compare instructions uniquely controlling a branch
2230 Value *RHS;
2231 CmpInst::Predicate Pred;
2232 if (!match(U, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2233 continue;
2234
2235 bool NonNullIfTrue;
2236 if (cmpExcludesZero(Pred, RHS))
2237 NonNullIfTrue = true;
2239 NonNullIfTrue = false;
2240 else
2241 continue;
2242
2245 for (const auto *CmpU : U->users()) {
2246 assert(WorkList.empty() && "Should be!");
2247 if (Visited.insert(CmpU).second)
2248 WorkList.push_back(CmpU);
2249
2250 while (!WorkList.empty()) {
2251 auto *Curr = WorkList.pop_back_val();
2252
2253 // If a user is an AND, add all its users to the work list. We only
2254 // propagate "pred != null" condition through AND because it is only
2255 // correct to assume that all conditions of AND are met in true branch.
2256 // TODO: Support similar logic of OR and EQ predicate?
2257 if (NonNullIfTrue)
2258 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
2259 for (const auto *CurrU : Curr->users())
2260 if (Visited.insert(CurrU).second)
2261 WorkList.push_back(CurrU);
2262 continue;
2263 }
2264
2265 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
2266 assert(BI->isConditional() && "uses a comparison!");
2267
2268 BasicBlock *NonNullSuccessor =
2269 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
2270 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
2271 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
2272 return true;
2273 } else if (NonNullIfTrue && isGuard(Curr) &&
2274 DT->dominates(cast<Instruction>(Curr), CtxI)) {
2275 return true;
2276 }
2277 }
2278 }
2279 }
2280
2281 return false;
2282}
2283
2284/// Does the 'Range' metadata (which must be a valid MD_range operand list)
2285/// ensure that the value it's attached to is never Value? 'RangeType' is
2286/// is the type of the value described by the range.
2287static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
2288 const unsigned NumRanges = Ranges->getNumOperands() / 2;
2289 assert(NumRanges >= 1);
2290 for (unsigned i = 0; i < NumRanges; ++i) {
2292 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
2294 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
2295 ConstantRange Range(Lower->getValue(), Upper->getValue());
2296 if (Range.contains(Value))
2297 return false;
2298 }
2299 return true;
2300}
2301
2302/// Try to detect a recurrence that monotonically increases/decreases from a
2303/// non-zero starting value. These are common as induction variables.
2304static bool isNonZeroRecurrence(const PHINode *PN) {
2305 BinaryOperator *BO = nullptr;
2306 Value *Start = nullptr, *Step = nullptr;
2307 const APInt *StartC, *StepC;
2308 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
2309 !match(Start, m_APInt(StartC)) || StartC->isZero())
2310 return false;
2311
2312 switch (BO->getOpcode()) {
2313 case Instruction::Add:
2314 // Starting from non-zero and stepping away from zero can never wrap back
2315 // to zero.
2316 return BO->hasNoUnsignedWrap() ||
2317 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
2318 StartC->isNegative() == StepC->isNegative());
2319 case Instruction::Mul:
2320 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
2321 match(Step, m_APInt(StepC)) && !StepC->isZero();
2322 case Instruction::Shl:
2323 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
2324 case Instruction::AShr:
2325 case Instruction::LShr:
2326 return BO->isExact();
2327 default:
2328 return false;
2329 }
2330}
2331
2332static bool isNonZeroAdd(const APInt &DemandedElts, unsigned Depth,
2333 const SimplifyQuery &Q, unsigned BitWidth, Value *X,
2334 Value *Y, bool NSW) {
2335 KnownBits XKnown = computeKnownBits(X, DemandedElts, Depth, Q);
2336 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Depth, Q);
2337
2338 // If X and Y are both non-negative (as signed values) then their sum is not
2339 // zero unless both X and Y are zero.
2340 if (XKnown.isNonNegative() && YKnown.isNonNegative())
2341 if (isKnownNonZero(Y, DemandedElts, Depth, Q) ||
2342 isKnownNonZero(X, DemandedElts, Depth, Q))
2343 return true;
2344
2345 // If X and Y are both negative (as signed values) then their sum is not
2346 // zero unless both X and Y equal INT_MIN.
2347 if (XKnown.isNegative() && YKnown.isNegative()) {
2349 // The sign bit of X is set. If some other bit is set then X is not equal
2350 // to INT_MIN.
2351 if (XKnown.One.intersects(Mask))
2352 return true;
2353 // The sign bit of Y is set. If some other bit is set then Y is not equal
2354 // to INT_MIN.
2355 if (YKnown.One.intersects(Mask))
2356 return true;
2357 }
2358
2359 // The sum of a non-negative number and a power of two is not zero.
2360 if (XKnown.isNonNegative() &&
2361 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
2362 return true;
2363 if (YKnown.isNonNegative() &&
2364 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
2365 return true;
2366
2367 return KnownBits::computeForAddSub(/*Add*/ true, NSW, XKnown, YKnown)
2368 .isNonZero();
2369}
2370
2371static bool isNonZeroSub(const APInt &DemandedElts, unsigned Depth,
2372 const SimplifyQuery &Q, unsigned BitWidth, Value *X,
2373 Value *Y) {
2374 if (auto *C = dyn_cast<Constant>(X))
2375 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Depth, Q))
2376 return true;
2377
2378 KnownBits XKnown = computeKnownBits(X, DemandedElts, Depth, Q);
2379 if (XKnown.isUnknown())
2380 return false;
2381 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Depth, Q);
2382 // If X != Y then X - Y is non zero.
2383 std::optional<bool> ne = KnownBits::ne(XKnown, YKnown);
2384 // If we are unable to compute if X != Y, we won't be able to do anything
2385 // computing the knownbits of the sub expression so just return here.
2386 return ne && *ne;
2387}
2388
2389static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
2390 unsigned Depth, const SimplifyQuery &Q,
2391 const KnownBits &KnownVal) {
2392 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
2393 switch (I->getOpcode()) {
2394 case Instruction::Shl:
2395 return Lhs.shl(Rhs);
2396 case Instruction::LShr:
2397 return Lhs.lshr(Rhs);
2398 case Instruction::AShr:
2399 return Lhs.ashr(Rhs);
2400 default:
2401 llvm_unreachable("Unknown Shift Opcode");
2402 }
2403 };
2404
2405 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
2406 switch (I->getOpcode()) {
2407 case Instruction::Shl:
2408 return Lhs.lshr(Rhs);
2409 case Instruction::LShr:
2410 case Instruction::AShr:
2411 return Lhs.shl(Rhs);
2412 default:
2413 llvm_unreachable("Unknown Shift Opcode");
2414 }
2415 };
2416
2417 if (KnownVal.isUnknown())
2418 return false;
2419
2420 KnownBits KnownCnt =
2421 computeKnownBits(I->getOperand(1), DemandedElts, Depth, Q);
2422 APInt MaxShift = KnownCnt.getMaxValue();
2423 unsigned NumBits = KnownVal.getBitWidth();
2424 if (MaxShift.uge(NumBits))
2425 return false;
2426
2427 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
2428 return true;
2429
2430 // If all of the bits shifted out are known to be zero, and Val is known
2431 // non-zero then at least one non-zero bit must remain.
2432 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
2433 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
2434 isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q))
2435 return true;
2436
2437 return false;
2438}
2439
2441 const APInt &DemandedElts,
2442 unsigned Depth, const SimplifyQuery &Q) {
2443 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
2444 switch (I->getOpcode()) {
2445 case Instruction::Alloca:
2446 // Alloca never returns null, malloc might.
2447 return I->getType()->getPointerAddressSpace() == 0;
2448 case Instruction::GetElementPtr:
2449 if (I->getType()->isPointerTy())
2450 return isGEPKnownNonNull(cast<GEPOperator>(I), Depth, Q);
2451 break;
2452 case Instruction::BitCast: {
2453 // We need to be a bit careful here. We can only peek through the bitcast
2454 // if the scalar size of elements in the operand are smaller than and a
2455 // multiple of the size they are casting too. Take three cases:
2456 //
2457 // 1) Unsafe:
2458 // bitcast <2 x i16> %NonZero to <4 x i8>
2459 //
2460 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
2461 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
2462 // guranteed (imagine just sign bit set in the 2 i16 elements).
2463 //
2464 // 2) Unsafe:
2465 // bitcast <4 x i3> %NonZero to <3 x i4>
2466 //
2467 // Even though the scalar size of the src (`i3`) is smaller than the
2468 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
2469 // its possible for the `3 x i4` elements to be zero because there are
2470 // some elements in the destination that don't contain any full src
2471 // element.
2472 //
2473 // 3) Safe:
2474 // bitcast <4 x i8> %NonZero to <2 x i16>
2475 //
2476 // This is always safe as non-zero in the 4 i8 elements implies
2477 // non-zero in the combination of any two adjacent ones. Since i8 is a
2478 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
2479 // This all implies the 2 i16 elements are non-zero.
2480 Type *FromTy = I->getOperand(0)->getType();
2481 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
2482 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
2483 return isKnownNonZero(I->getOperand(0), Depth, Q);
2484 } break;
2485 case Instruction::IntToPtr:
2486 // Note that we have to take special care to avoid looking through
2487 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2488 // as casts that can alter the value, e.g., AddrSpaceCasts.
2489 if (!isa<ScalableVectorType>(I->getType()) &&
2490 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
2491 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
2492 return isKnownNonZero(I->getOperand(0), Depth, Q);
2493 break;
2494 case Instruction::PtrToInt:
2495 // Similar to int2ptr above, we can look through ptr2int here if the cast
2496 // is a no-op or an extend and not a truncate.
2497 if (!isa<ScalableVectorType>(I->getType()) &&
2498 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
2499 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
2500 return isKnownNonZero(I->getOperand(0), Depth, Q);
2501 break;
2502 case Instruction::Sub:
2503 return isNonZeroSub(DemandedElts, Depth, Q, BitWidth, I->getOperand(0),
2504 I->getOperand(1));
2505 case Instruction::Or:
2506 // X | Y != 0 if X != 0 or Y != 0.
2507 return isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q) ||
2508 isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q);
2509 case Instruction::SExt:
2510 case Instruction::ZExt:
2511 // ext X != 0 if X != 0.
2512 return isKnownNonZero(I->getOperand(0), Depth, Q);
2513
2514 case Instruction::Shl: {
2515 // shl nsw/nuw can't remove any non-zero bits.
2516 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(I);
2517 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
2518 return isKnownNonZero(I->getOperand(0), Depth, Q);
2519
2520 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
2521 // if the lowest bit is shifted off the end.
2522 KnownBits Known(BitWidth);
2523 computeKnownBits(I->getOperand(0), DemandedElts, Known, Depth, Q);
2524 if (Known.One[0])
2525 return true;
2526
2527 return isNonZeroShift(I, DemandedElts, Depth, Q, Known);
2528 }
2529 case Instruction::LShr:
2530 case Instruction::AShr: {
2531 // shr exact can only shift out zero bits.
2532 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(I);
2533 if (BO->isExact())
2534 return isKnownNonZero(I->getOperand(0), Depth, Q);
2535
2536 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
2537 // defined if the sign bit is shifted off the end.
2538 KnownBits Known =
2539 computeKnownBits(I->getOperand(0), DemandedElts, Depth, Q);
2540 if (Known.isNegative())
2541 return true;
2542
2543 return isNonZeroShift(I, DemandedElts, Depth, Q, Known);
2544 }
2545 case Instruction::UDiv:
2546 case Instruction::SDiv: {
2547 // X / Y
2548 // div exact can only produce a zero if the dividend is zero.
2549 if (cast<PossiblyExactOperator>(I)->isExact())
2550 return isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q);
2551
2552 std::optional<bool> XUgeY;
2553 KnownBits XKnown =
2554 computeKnownBits(I->getOperand(0), DemandedElts, Depth, Q);
2555 // If X is fully unknown we won't be able to figure anything out so don't
2556 // both computing knownbits for Y.
2557 if (XKnown.isUnknown())
2558 return false;
2559
2560 KnownBits YKnown =
2561 computeKnownBits(I->getOperand(1), DemandedElts, Depth, Q);
2562 if (I->getOpcode() == Instruction::SDiv) {
2563 // For signed division need to compare abs value of the operands.
2564 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
2565 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
2566 }
2567 // If X u>= Y then div is non zero (0/0 is UB).
2568 XUgeY = KnownBits::uge(XKnown, YKnown);
2569 // If X is total unknown or X u< Y we won't be able to prove non-zero
2570 // with compute known bits so just return early.
2571 return XUgeY && *XUgeY;
2572 }
2573 case Instruction::Add: {
2574 // X + Y.
2575
2576 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
2577 // non-zero.
2578 auto *BO = cast<OverflowingBinaryOperator>(I);
2579 if (Q.IIQ.hasNoUnsignedWrap(BO))
2580 return isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q) ||
2581 isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q);
2582
2583 return isNonZeroAdd(DemandedElts, Depth, Q, BitWidth, I->getOperand(0),
2584 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO));
2585 }
2586 case Instruction::Mul: {
2587 // If X and Y are non-zero then so is X * Y as long as the multiplication
2588 // does not overflow.
2589 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(I);
2590 if (Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO))
2591 return isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q) &&
2592 isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q);
2593
2594 // If either X or Y is odd, then if the other is non-zero the result can't
2595 // be zero.
2596 KnownBits XKnown =
2597 computeKnownBits(I->getOperand(0), DemandedElts, Depth, Q);
2598 if (XKnown.One[0])
2599 return isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q);
2600
2601 KnownBits YKnown =
2602 computeKnownBits(I->getOperand(1), DemandedElts, Depth, Q);
2603 if (YKnown.One[0])
2604 return XKnown.isNonZero() ||
2605 isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q);
2606
2607 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
2608 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
2609 // the lowest known One of X and Y. If they are non-zero, the result
2610 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
2611 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
2612 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
2613 BitWidth;
2614 }
2615 case Instruction::Select: {
2616 // (C ? X : Y) != 0 if X != 0 and Y != 0.
2617
2618 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
2619 // then see if the select condition implies the arm is non-zero. For example
2620 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
2621 // dominated by `X != 0`.
2622 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
2623 Value *Op;
2624 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
2625 // Op is trivially non-zero.
2626 if (isKnownNonZero(Op, DemandedElts, Depth, Q))
2627 return true;
2628
2629 // The condition of the select dominates the true/false arm. Check if the
2630 // condition implies that a given arm is non-zero.
2631 Value *X;
2632 CmpInst::Predicate Pred;
2633 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
2634 return false;
2635
2636 if (!IsTrueArm)
2637 Pred = ICmpInst::getInversePredicate(Pred);
2638
2639 return cmpExcludesZero(Pred, X);
2640 };
2641
2642 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
2643 SelectArmIsNonZero(/* IsTrueArm */ false))
2644 return true;
2645 break;
2646 }
2647 case Instruction::PHI: {
2648 auto *PN = cast<PHINode>(I);
2650 return true;
2651
2652 // Check if all incoming values are non-zero using recursion.
2653 SimplifyQuery RecQ = Q;
2654 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2655 return llvm::all_of(PN->operands(), [&](const Use &U) {
2656 if (U.get() == PN)
2657 return true;
2658 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2659 // Check if the branch on the phi excludes zero.
2660 ICmpInst::Predicate Pred;
2661 Value *X;
2662 BasicBlock *TrueSucc, *FalseSucc;
2663 if (match(RecQ.CxtI,
2664 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
2665 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2666 // Check for cases of duplicate successors.
2667 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
2668 // If we're using the false successor, invert the predicate.
2669 if (FalseSucc == PN->getParent())
2670 Pred = CmpInst::getInversePredicate(Pred);
2671 if (cmpExcludesZero(Pred, X))
2672 return true;
2673 }
2674 }
2675 // Finally recurse on the edge and check it directly.
2676 return isKnownNonZero(U.get(), DemandedElts, NewDepth, RecQ);
2677 });
2678 }
2679 case Instruction::ExtractElement:
2680 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
2681 const Value *Vec = EEI->getVectorOperand();
2682 const Value *Idx = EEI->getIndexOperand();
2683 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2684 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
2685 unsigned NumElts = VecTy->getNumElements();
2686 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2687 if (CIdx && CIdx->getValue().ult(NumElts))
2688 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2689 return isKnownNonZero(Vec, DemandedVecElts, Depth, Q);
2690 }
2691 }
2692 break;
2693 case Instruction::Freeze:
2694 return isKnownNonZero(I->getOperand(0), Depth, Q) &&
2695 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2696 Depth);
2697 case Instruction::Load: {
2698 auto *LI = cast<LoadInst>(I);
2699 // A Load tagged with nonnull or dereferenceable with null pointer undefined
2700 // is never null.
2701 if (auto *PtrT = dyn_cast<PointerType>(I->getType()))
2702 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
2703 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
2704 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
2705 return true;
2706
2707 // No need to fall through to computeKnownBits as range metadata is already
2708 // handled in isKnownNonZero.
2709 return false;
2710 }
2711 case Instruction::Call:
2712 case Instruction::Invoke:
2713 if (I->getType()->isPointerTy()) {
2714 const auto *Call = cast<CallBase>(I);
2715 if (Call->isReturnNonNull())
2716 return true;
2717 if (const auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
2718 return isKnownNonZero(RP, Depth, Q);
2719 } else if (const Value *RV = cast<CallBase>(I)->getReturnedArgOperand()) {
2720 if (isKnownNonZero(RV, Depth, Q))
2721 return true;
2722 }
2723
2724 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2725 switch (II->getIntrinsicID()) {
2726 case Intrinsic::sshl_sat:
2727 case Intrinsic::ushl_sat:
2728 case Intrinsic::abs:
2729 case Intrinsic::bitreverse:
2730 case Intrinsic::bswap:
2731 case Intrinsic::ctpop:
2732 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Depth, Q);
2733 case Intrinsic::ssub_sat:
2734 return isNonZeroSub(DemandedElts, Depth, Q, BitWidth,
2735 II->getArgOperand(0), II->getArgOperand(1));
2736 case Intrinsic::sadd_sat:
2737 return isNonZeroAdd(DemandedElts, Depth, Q, BitWidth,
2738 II->getArgOperand(0), II->getArgOperand(1),
2739 /*NSW*/ true);
2740 case Intrinsic::umax:
2741 case Intrinsic::uadd_sat:
2742 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Depth, Q) ||
2743 isKnownNonZero(II->getArgOperand(0), DemandedElts, Depth, Q);
2744 case Intrinsic::smin:
2745 case Intrinsic::smax: {
2746 auto KnownOpImpliesNonZero = [&](const KnownBits &K) {
2747 return II->getIntrinsicID() == Intrinsic::smin
2748 ? K.isNegative()
2749 : K.isStrictlyPositive();
2750 };
2751 KnownBits XKnown =
2752 computeKnownBits(II->getArgOperand(0), DemandedElts, Depth, Q);
2753 if (KnownOpImpliesNonZero(XKnown))
2754 return true;
2755 KnownBits YKnown =
2756 computeKnownBits(II->getArgOperand(1), DemandedElts, Depth, Q);
2757 if (KnownOpImpliesNonZero(YKnown))
2758 return true;
2759
2760 if (XKnown.isNonZero() && YKnown.isNonZero())
2761 return true;
2762 }
2763 [[fallthrough]];
2764 case Intrinsic::umin:
2765 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Depth, Q) &&
2766 isKnownNonZero(II->getArgOperand(1), DemandedElts, Depth, Q);
2767 case Intrinsic::cttz:
2768 return computeKnownBits(II->getArgOperand(0), DemandedElts, Depth, Q)
2769 .Zero[0];
2770 case Intrinsic::ctlz:
2771 return computeKnownBits(II->getArgOperand(0), DemandedElts, Depth, Q)
2772 .isNonNegative();
2773 case Intrinsic::fshr:
2774 case Intrinsic::fshl:
2775 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
2776 if (II->getArgOperand(0) == II->getArgOperand(1))
2777 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Depth, Q);
2778 break;
2779 case Intrinsic::vscale:
2780 return true;
2781 default:
2782 break;
2783 }
2784 break;
2785 }
2786
2787 return false;
2788 }
2789
2790 KnownBits Known(BitWidth);
2791 computeKnownBits(I, DemandedElts, Known, Depth, Q);
2792 return Known.One != 0;
2793}
2794
2795/// Return true if the given value is known to be non-zero when defined. For
2796/// vectors, return true if every demanded element is known to be non-zero when
2797/// defined. For pointers, if the context instruction and dominator tree are
2798/// specified, perform context-sensitive analysis and return true if the
2799/// pointer couldn't possibly be null at the specified instruction.
2800/// Supports values with integer or pointer type and vectors of integers.
2801bool isKnownNonZero(const Value *V, const APInt &DemandedElts, unsigned Depth,
2802 const SimplifyQuery &Q) {
2803
2804#ifndef NDEBUG
2805 Type *Ty = V->getType();
2806 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2807
2808 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2809 assert(
2810 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2811 "DemandedElt width should equal the fixed vector number of elements");
2812 } else {
2813 assert(DemandedElts == APInt(1, 1) &&
2814 "DemandedElt width should be 1 for scalars");
2815 }
2816#endif
2817
2818 if (auto *C = dyn_cast<Constant>(V)) {
2819 if (C->isNullValue())
2820 return false;
2821 if (isa<ConstantInt>(C))
2822 // Must be non-zero due to null test above.
2823 return true;
2824
2825 // For constant vectors, check that all elements are undefined or known
2826 // non-zero to determine that the whole vector is known non-zero.
2827 if (auto *VecTy = dyn_cast<FixedVectorType>(C->getType())) {
2828 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2829 if (!DemandedElts[i])
2830 continue;
2831 Constant *Elt = C->getAggregateElement(i);
2832 if (!Elt || Elt->isNullValue())
2833 return false;
2834 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2835 return false;
2836 }
2837 return true;
2838 }
2839
2840 // A global variable in address space 0 is non null unless extern weak
2841 // or an absolute symbol reference. Other address spaces may have null as a
2842 // valid address for a global, so we can't assume anything.
2843 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2844 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2845 GV->getType()->getAddressSpace() == 0)
2846 return true;
2847 }
2848
2849 // For constant expressions, fall through to the Operator code below.
2850 if (!isa<ConstantExpr>(V))
2851 return false;
2852 }
2853
2854 if (auto *I = dyn_cast<Instruction>(V)) {
2855 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
2856 // If the possible ranges don't contain zero, then the value is
2857 // definitely non-zero.
2858 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
2859 const APInt ZeroValue(Ty->getBitWidth(), 0);
2860 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2861 return true;
2862 }
2863 }
2864 }
2865
2866 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
2867 return true;
2868
2869 // Some of the tests below are recursive, so bail out if we hit the limit.
2871 return false;
2872
2873 // Check for pointer simplifications.
2874
2875 if (PointerType *PtrTy = dyn_cast<PointerType>(V->getType())) {
2876 // A byval, inalloca may not be null in a non-default addres space. A
2877 // nonnull argument is assumed never 0.
2878 if (const Argument *A = dyn_cast<Argument>(V)) {
2879 if (((A->hasPassPointeeByValueCopyAttr() &&
2880 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
2881 A->hasNonNullAttr()))
2882 return true;
2883 }
2884 }
2885
2886 if (const auto *I = dyn_cast<Operator>(V))
2887 if (isKnownNonZeroFromOperator(I, DemandedElts, Depth, Q))
2888 return true;
2889
2890 if (!isa<Constant>(V) &&
2892 return true;
2893
2894 return false;
2895}
2896
2897bool isKnownNonZero(const Value *V, unsigned Depth, const SimplifyQuery &Q) {
2898 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
2899 APInt DemandedElts =
2900 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
2901 return isKnownNonZero(V, DemandedElts, Depth, Q);
2902}
2903
2904/// If the pair of operators are the same invertible function, return the
2905/// the operands of the function corresponding to each input. Otherwise,
2906/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
2907/// every input value to exactly one output value. This is equivalent to
2908/// saying that Op1 and Op2 are equal exactly when the specified pair of
2909/// operands are equal, (except that Op1 and Op2 may be poison more often.)
2910static std::optional<std::pair<Value*, Value*>>
2912 const Operator *Op2) {
2913 if (Op1->getOpcode() != Op2->getOpcode())
2914 return std::nullopt;
2915
2916 auto getOperands = [&](unsigned OpNum) -> auto {
2917 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
2918 };
2919
2920 switch (Op1->getOpcode()) {
2921 default:
2922 break;
2923 case Instruction::Add:
2924 case Instruction::Sub:
2925 if (Op1->getOperand(0) == Op2->getOperand(0))
2926 return getOperands(1);
2927 if (Op1->getOperand(1) == Op2->getOperand(1))
2928 return getOperands(0);
2929 break;
2930 case Instruction::Mul: {
2931 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
2932 // and N is the bitwdith. The nsw case is non-obvious, but proven by
2933 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
2934 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2935 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2936 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2937 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2938 break;
2939
2940 // Assume operand order has been canonicalized
2941 if (Op1->getOperand(1) == Op2->getOperand(1) &&
2942 isa<ConstantInt>(Op1->getOperand(1)) &&
2943 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
2944 return getOperands(0);
2945 break;
2946 }
2947 case Instruction::Shl: {
2948 // Same as multiplies, with the difference that we don't need to check
2949 // for a non-zero multiply. Shifts always multiply by non-zero.
2950 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2951 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2952 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2953 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2954 break;
2955
2956 if (Op1->getOperand(1) == Op2->getOperand(1))
2957 return getOperands(0);
2958 break;
2959 }
2960 case Instruction::AShr:
2961 case Instruction::LShr: {
2962 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
2963 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
2964 if (!PEO1->isExact() || !PEO2->isExact())
2965 break;
2966
2967 if (Op1->getOperand(1) == Op2->getOperand(1))
2968 return getOperands(0);
2969 break;
2970 }
2971 case Instruction::SExt:
2972 case Instruction::ZExt:
2973 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
2974 return getOperands(0);
2975 break;
2976 case Instruction::PHI: {
2977 const PHINode *PN1 = cast<PHINode>(Op1);
2978 const PHINode *PN2 = cast<PHINode>(Op2);
2979
2980 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
2981 // are a single invertible function of the start values? Note that repeated
2982 // application of an invertible function is also invertible
2983 BinaryOperator *BO1 = nullptr;
2984 Value *Start1 = nullptr, *Step1 = nullptr;
2985 BinaryOperator *BO2 = nullptr;
2986 Value *Start2 = nullptr, *Step2 = nullptr;
2987 if (PN1->getParent() != PN2->getParent() ||
2988 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
2989 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
2990 break;
2991
2992 auto Values = getInvertibleOperands(cast<Operator>(BO1),
2993 cast<Operator>(BO2));
2994 if (!Values)
2995 break;
2996
2997 // We have to be careful of mutually defined recurrences here. Ex:
2998 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
2999 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3000 // The invertibility of these is complicated, and not worth reasoning
3001 // about (yet?).
3002 if (Values->first != PN1 || Values->second != PN2)
3003 break;
3004
3005 return std::make_pair(Start1, Start2);
3006 }
3007 }
3008 return std::nullopt;
3009}
3010
3011/// Return true if V2 == V1 + X, where X is known non-zero.
3012static bool isAddOfNonZero(const Value *V1, const Value *V2, unsigned Depth,
3013 const SimplifyQuery &Q) {
3014 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
3015 if (!BO || BO->getOpcode() != Instruction::Add)
3016 return false;
3017 Value *Op = nullptr;
3018 if (V2 == BO->getOperand(0))
3019 Op = BO->getOperand(1);
3020 else if (V2 == BO->getOperand(1))
3021 Op = BO->getOperand(0);
3022 else
3023 return false;
3024 return isKnownNonZero(Op, Depth + 1, Q);
3025}
3026
3027/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
3028/// the multiplication is nuw or nsw.
3029static bool isNonEqualMul(const Value *V1, const Value *V2, unsigned Depth,
3030 const SimplifyQuery &Q) {
3031 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3032 const APInt *C;
3033 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
3034 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3035 !C->isZero() && !C->isOne() && isKnownNonZero(V1, Depth + 1, Q);
3036 }
3037 return false;
3038}
3039
3040/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
3041/// the shift is nuw or nsw.
3042static bool isNonEqualShl(const Value *V1, const Value *V2, unsigned Depth,
3043 const SimplifyQuery &Q) {
3044 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3045 const APInt *C;
3046 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
3047 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3048 !C->isZero() && isKnownNonZero(V1, Depth + 1, Q);
3049 }
3050 return false;
3051}
3052
3053static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
3054 unsigned Depth, const SimplifyQuery &Q) {
3055 // Check two PHIs are in same block.
3056 if (PN1->getParent() != PN2->getParent())
3057 return false;
3058
3060 bool UsedFullRecursion = false;
3061 for (const BasicBlock *IncomBB : PN1->blocks()) {
3062 if (!VisitedBBs.insert(IncomBB).second)
3063 continue; // Don't reprocess blocks that we have dealt with already.
3064 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
3065 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
3066 const APInt *C1, *C2;
3067 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
3068 continue;
3069
3070 // Only one pair of phi operands is allowed for full recursion.
3071 if (UsedFullRecursion)
3072 return false;
3073
3074 SimplifyQuery RecQ = Q;
3075 RecQ.CxtI = IncomBB->getTerminator();
3076 if (!isKnownNonEqual(IV1, IV2, Depth + 1, RecQ))
3077 return false;
3078 UsedFullRecursion = true;
3079 }
3080 return true;
3081}
3082
3083static bool isNonEqualSelect(const Value *V1, const Value *V2, unsigned Depth,
3084 const SimplifyQuery &Q) {
3085 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
3086 if (!SI1)
3087 return false;
3088
3089 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
3090 const Value *Cond1 = SI1->getCondition();
3091 const Value *Cond2 = SI2->getCondition();
3092 if (Cond1 == Cond2)
3093 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
3094 Depth + 1, Q) &&
3095 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
3096 Depth + 1, Q);
3097 }
3098 return isKnownNonEqual(SI1->getTrueValue(), V2, Depth + 1, Q) &&
3099 isKnownNonEqual(SI1->getFalseValue(), V2, Depth + 1, Q);
3100}
3101
3102/// Return true if it is known that V1 != V2.
3103static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
3104 const SimplifyQuery &Q) {
3105 if (V1 == V2)
3106 return false;
3107 if (V1->getType() != V2->getType())
3108 // We can't look through casts yet.
3109 return false;
3110
3112 return false;
3113
3114 // See if we can recurse through (exactly one of) our operands. This
3115 // requires our operation be 1-to-1 and map every input value to exactly
3116 // one output value. Such an operation is invertible.
3117 auto *O1 = dyn_cast<Operator>(V1);
3118 auto *O2 = dyn_cast<Operator>(V2);
3119 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
3120 if (auto Values = getInvertibleOperands(O1, O2))
3121 return isKnownNonEqual(Values->first, Values->second, Depth + 1, Q);
3122
3123 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
3124 const PHINode *PN2 = cast<PHINode>(V2);
3125 // FIXME: This is missing a generalization to handle the case where one is
3126 // a PHI and another one isn't.
3127 if (isNonEqualPHIs(PN1, PN2, Depth, Q))
3128 return true;
3129 };
3130 }
3131
3132 if (isAddOfNonZero(V1, V2, Depth, Q) || isAddOfNonZero(V2, V1, Depth, Q))
3133 return true;
3134
3135 if (isNonEqualMul(V1, V2, Depth, Q) || isNonEqualMul(V2, V1, Depth, Q))
3136 return true;
3137
3138 if (isNonEqualShl(V1, V2, Depth, Q) || isNonEqualShl(V2, V1, Depth, Q))
3139 return true;
3140
3141 if (V1->getType()->isIntOrIntVectorTy()) {
3142 // Are any known bits in V1 contradictory to known bits in V2? If V1
3143 // has a known zero where V2 has a known one, they must not be equal.
3144 KnownBits Known1 = computeKnownBits(V1, Depth, Q);
3145 KnownBits Known2 = computeKnownBits(V2, Depth, Q);
3146
3147 if (Known1.Zero.intersects(Known2.One) ||
3148 Known2.Zero.intersects(Known1.One))
3149 return true;
3150 }
3151
3152 if (isNonEqualSelect(V1, V2, Depth, Q) || isNonEqualSelect(V2, V1, Depth, Q))
3153 return true;
3154
3155 return false;
3156}
3157
3158/// Return true if 'V & Mask' is known to be zero. We use this predicate to
3159/// simplify operations downstream. Mask is known to be zero for bits that V
3160/// cannot have.
3161///
3162/// This function is defined on values with integer type, values with pointer
3163/// type, and vectors of integers. In the case
3164/// where V is a vector, the mask, known zero, and known one values are the
3165/// same width as the vector element, and the bit is set only if it is true
3166/// for all of the elements in the vector.
3167bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
3168 const SimplifyQuery &Q) {
3169 KnownBits Known(Mask.getBitWidth());
3170 computeKnownBits(V, Known, Depth, Q);
3171 return Mask.isSubsetOf(Known.Zero);
3172}
3173
3174// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
3175// Returns the input and lower/upper bounds.
3176static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
3177 const APInt *&CLow, const APInt *&CHigh) {
3178 assert(isa<Operator>(Select) &&
3179 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
3180 "Input should be a Select!");
3181
3182 const Value *LHS = nullptr, *RHS = nullptr;
3184 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
3185 return false;
3186
3187 if (!match(RHS, m_APInt(CLow)))
3188 return false;
3189
3190 const Value *LHS2 = nullptr, *RHS2 = nullptr;
3192 if (getInverseMinMaxFlavor(SPF) != SPF2)
3193 return false;
3194
3195 if (!match(RHS2, m_APInt(CHigh)))
3196 return false;
3197
3198 if (SPF == SPF_SMIN)
3199 std::swap(CLow, CHigh);
3200
3201 In = LHS2;
3202 return CLow->sle(*CHigh);
3203}
3204
3206 const APInt *&CLow,
3207 const APInt *&CHigh) {
3208 assert((II->getIntrinsicID() == Intrinsic::smin ||
3209 II->getIntrinsicID() == Intrinsic::smax) && "Must be smin/smax");
3210
3212 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
3213 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
3214 !match(II->getArgOperand(1), m_APInt(CLow)) ||
3215 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
3216 return false;
3217
3218 if (II->getIntrinsicID() == Intrinsic::smin)
3219 std::swap(CLow, CHigh);
3220 return CLow->sle(*CHigh);
3221}
3222
3223/// For vector constants, loop over the elements and find the constant with the
3224/// minimum number of sign bits. Return 0 if the value is not a vector constant
3225/// or if any element was not analyzed; otherwise, return the count for the
3226/// element with the minimum number of sign bits.
3228 const APInt &DemandedElts,
3229 unsigned TyBits) {
3230 const auto *CV = dyn_cast<Constant>(V);
3231 if (!CV || !isa<FixedVectorType>(CV->getType()))
3232 return 0;
3233
3234 unsigned MinSignBits = TyBits;
3235 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
3236 for (unsigned i = 0; i != NumElts; ++i) {
3237 if (!DemandedElts[i])
3238 continue;
3239 // If we find a non-ConstantInt, bail out.
3240 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
3241 if (!Elt)
3242 return 0;
3243
3244 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
3245 }
3246
3247 return MinSignBits;
3248}
3249
3250static unsigned ComputeNumSignBitsImpl(const Value *V,
3251 const APInt &DemandedElts,
3252 unsigned Depth, const SimplifyQuery &Q);
3253
3254static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
3255 unsigned Depth, const SimplifyQuery &Q) {
3256 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Depth, Q);
3257 assert(Result > 0 && "At least one sign bit needs to be present!");
3258 return Result;
3259}
3260
3261/// Return the number of times the sign bit of the register is replicated into
3262/// the other bits. We know that at least 1 bit is always equal to the sign bit
3263/// (itself), but other cases can give us information. For example, immediately
3264/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
3265/// other, so we return 3. For vectors, return the number of sign bits for the
3266/// vector element with the minimum number of known sign bits of the demanded
3267/// elements in the vector specified by DemandedElts.
3268static unsigned ComputeNumSignBitsImpl(const Value *V,
3269 const APInt &DemandedElts,
3270 unsigned Depth, const SimplifyQuery &Q) {
3271 Type *Ty = V->getType();
3272#ifndef NDEBUG
3273 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3274
3275 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3276 assert(
3277 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3278 "DemandedElt width should equal the fixed vector number of elements");
3279 } else {
3280 assert(DemandedElts == APInt(1, 1) &&
3281 "DemandedElt width should be 1 for scalars");
3282 }
3283#endif
3284
3285 // We return the minimum number of sign bits that are guaranteed to be present
3286 // in V, so for undef we have to conservatively return 1. We don't have the
3287 // same behavior for poison though -- that's a FIXME today.
3288
3289 Type *ScalarTy = Ty->getScalarType();
3290 unsigned TyBits = ScalarTy->isPointerTy() ?
3291 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
3292 Q.DL.getTypeSizeInBits(ScalarTy);
3293
3294 unsigned Tmp, Tmp2;
3295 unsigned FirstAnswer = 1;
3296
3297 // Note that ConstantInt is handled by the general computeKnownBits case
3298 // below.
3299
3301 return 1;
3302
3303 if (auto *U = dyn_cast<Operator>(V)) {
3304 switch (Operator::getOpcode(V)) {
3305 default: break;
3306 case Instruction::SExt:
3307 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
3308 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
3309
3310 case Instruction::SDiv: {
3311 const APInt *Denominator;
3312 // sdiv X, C -> adds log(C) sign bits.
3313 if (match(U->getOperand(1), m_APInt(Denominator))) {
3314
3315 // Ignore non-positive denominator.
3316 if (!Denominator->isStrictlyPositive())
3317 break;
3318
3319 // Calculate the incoming numerator bits.
3320 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3321
3322 // Add floor(log(C)) bits to the numerator bits.
3323 return std::min(TyBits, NumBits + Denominator->logBase2());
3324 }
3325 break;
3326 }
3327
3328 case Instruction::SRem: {
3329 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3330
3331 const APInt *Denominator;
3332 // srem X, C -> we know that the result is within [-C+1,C) when C is a
3333 // positive constant. This let us put a lower bound on the number of sign
3334 // bits.
3335 if (match(U->getOperand(1), m_APInt(Denominator))) {
3336
3337 // Ignore non-positive denominator.
3338 if (Denominator->isStrictlyPositive()) {
3339 // Calculate the leading sign bit constraints by examining the
3340 // denominator. Given that the denominator is positive, there are two
3341 // cases:
3342 //
3343 // 1. The numerator is positive. The result range is [0,C) and
3344 // [0,C) u< (1 << ceilLogBase2(C)).
3345 //
3346 // 2. The numerator is negative. Then the result range is (-C,0] and
3347 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
3348 //
3349 // Thus a lower bound on the number of sign bits is `TyBits -
3350 // ceilLogBase2(C)`.
3351
3352 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
3353 Tmp = std::max(Tmp, ResBits);
3354 }
3355 }
3356 return Tmp;
3357 }
3358
3359 case Instruction::AShr: {
3360 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3361 // ashr X, C -> adds C sign bits. Vectors too.
3362 const APInt *ShAmt;
3363 if (match(U->getOperand(1), m_APInt(ShAmt))) {
3364 if (ShAmt->uge(TyBits))
3365 break; // Bad shift.
3366 unsigned ShAmtLimited = ShAmt->getZExtValue();
3367 Tmp += ShAmtLimited;
3368 if (Tmp > TyBits) Tmp = TyBits;
3369 }
3370 return Tmp;
3371 }
3372 case Instruction::Shl: {
3373 const APInt *ShAmt;
3374 if (match(U->getOperand(1), m_APInt(ShAmt))) {
3375 // shl destroys sign bits.
3376 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3377 if (ShAmt->uge(TyBits) || // Bad shift.
3378 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
3379 Tmp2 = ShAmt->getZExtValue();
3380 return Tmp - Tmp2;
3381 }
3382 break;
3383 }
3384 case Instruction::And:
3385 case Instruction::Or:
3386 case Instruction::Xor: // NOT is handled here.
3387 // Logical binary ops preserve the number of sign bits at the worst.
3388 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3389 if (Tmp != 1) {
3390 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3391 FirstAnswer = std::min(Tmp, Tmp2);
3392 // We computed what we know about the sign bits as our first
3393 // answer. Now proceed to the generic code that uses
3394 // computeKnownBits, and pick whichever answer is better.
3395 }
3396 break;
3397
3398 case Instruction::Select: {
3399 // If we have a clamp pattern, we know that the number of sign bits will
3400 // be the minimum of the clamp min/max range.
3401 const Value *X;
3402 const APInt *CLow, *CHigh;
3403 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
3404 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
3405
3406 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3407 if (Tmp == 1) break;
3408 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
3409 return std::min(Tmp, Tmp2);
3410 }
3411
3412 case Instruction::Add:
3413 // Add can have at most one carry bit. Thus we know that the output
3414 // is, at worst, one more bit than the inputs.
3415 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3416 if (Tmp == 1) break;
3417
3418 // Special case decrementing a value (ADD X, -1):
3419 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
3420 if (CRHS->isAllOnesValue()) {
3421 KnownBits Known(TyBits);
3422 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
3423
3424 // If the input is known to be 0 or 1, the output is 0/-1, which is
3425 // all sign bits set.
3426 if ((Known.Zero | 1).isAllOnes())
3427 return TyBits;
3428
3429 // If we are subtracting one from a positive number, there is no carry
3430 // out of the result.
3431 if (Known.isNonNegative())
3432 return Tmp;
3433 }
3434
3435 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3436 if (Tmp2 == 1) break;
3437 return std::min(Tmp, Tmp2) - 1;
3438
3439 case Instruction::Sub:
3440 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3441 if (Tmp2 == 1) break;
3442
3443 // Handle NEG.
3444 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
3445 if (CLHS->isNullValue()) {
3446 KnownBits Known(TyBits);
3447 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
3448 // If the input is known to be 0 or 1, the output is 0/-1, which is
3449 // all sign bits set.
3450 if ((Known.Zero | 1).isAllOnes())
3451 return TyBits;
3452
3453 // If the input is known to be positive (the sign bit is known clear),
3454 // the output of the NEG has the same number of sign bits as the
3455 // input.
3456 if (Known.isNonNegative())
3457 return Tmp2;
3458
3459 // Otherwise, we treat this like a SUB.
3460 }
3461
3462 // Sub can have at most one carry bit. Thus we know that the output
3463 // is, at worst, one more bit than the inputs.
3464 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3465 if (Tmp == 1) break;
3466 return std::min(Tmp, Tmp2) - 1;
3467
3468 case Instruction::Mul: {
3469 // The output of the Mul can be at most twice the valid bits in the
3470 // inputs.
3471 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3472 if (SignBitsOp0 == 1) break;
3473 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3474 if (SignBitsOp1 == 1) break;
3475 unsigned OutValidBits =
3476 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
3477 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
3478 }
3479
3480 case Instruction::PHI: {
3481 const PHINode *PN = cast<PHINode>(U);
3482 unsigned NumIncomingValues = PN->getNumIncomingValues();
3483 // Don't analyze large in-degree PHIs.
3484 if (NumIncomingValues > 4) break;
3485 // Unreachable blocks may have zero-operand PHI nodes.
3486 if (NumIncomingValues == 0) break;
3487
3488 // Take the minimum of all incoming values. This can't infinitely loop
3489 // because of our depth threshold.
3490 SimplifyQuery RecQ = Q;
3491 Tmp = TyBits;
3492 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
3493 if (Tmp == 1) return Tmp;
3494 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
3495 Tmp = std::min(
3496 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, RecQ));
3497 }
3498 return Tmp;
3499 }
3500
3501 case Instruction::Trunc: {
3502 // If the input contained enough sign bits that some remain after the
3503 // truncation, then we can make use of that. Otherwise we don't know
3504 // anything.
3505 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3506 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
3507 if (Tmp > (OperandTyBits - TyBits))
3508 return Tmp - (OperandTyBits - TyBits);
3509
3510 return 1;
3511 }
3512
3513 case Instruction::ExtractElement:
3514 // Look through extract element. At the moment we keep this simple and
3515 // skip tracking the specific element. But at least we might find
3516 // information valid for all elements of the vector (for example if vector
3517 // is sign extended, shifted, etc).
3518 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3519
3520 case Instruction::ShuffleVector: {
3521 // Collect the minimum number of sign bits that are shared by every vector
3522 // element referenced by the shuffle.
3523 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
3524 if (!Shuf) {
3525 // FIXME: Add support for shufflevector constant expressions.
3526 return 1;
3527 }
3528 APInt DemandedLHS, DemandedRHS;
3529 // For undef elements, we don't know anything about the common state of
3530 // the shuffle result.
3531 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3532 return 1;
3533 Tmp = std::numeric_limits<unsigned>::max();
3534 if (!!DemandedLHS) {
3535 const Value *LHS = Shuf->getOperand(0);
3536 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Depth + 1, Q);
3537 }
3538 // If we don't know anything, early out and try computeKnownBits
3539 // fall-back.
3540 if (Tmp == 1)
3541 break;
3542 if (!!DemandedRHS) {
3543 const Value *RHS = Shuf->getOperand(1);
3544 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Depth + 1, Q);
3545 Tmp = std::min(Tmp, Tmp2);
3546 }
3547 // If we don't know anything, early out and try computeKnownBits
3548 // fall-back.
3549 if (Tmp == 1)
3550 break;
3551 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
3552 return Tmp;
3553 }
3554 case Instruction::Call: {
3555 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
3556 switch (II->getIntrinsicID()) {
3557 default: break;
3558 case Intrinsic::abs:
3559 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3560 if (Tmp == 1) break;
3561
3562 // Absolute value reduces number of sign bits by at most 1.
3563 return Tmp - 1;
3564 case Intrinsic::smin:
3565 case Intrinsic::smax: {
3566 const APInt *CLow, *CHigh;
3567 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
3568 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
3569 }
3570 }
3571 }
3572 }
3573 }
3574 }
3575
3576 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3577 // use this information.
3578
3579 // If we can examine all elements of a vector constant successfully, we're
3580 // done (we can't do any better than that). If not, keep trying.
3581 if (unsigned VecSignBits =
3582 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
3583 return VecSignBits;
3584
3585 KnownBits Known(TyBits);
3586 computeKnownBits(V, DemandedElts, Known, Depth, Q);
3587
3588 // If we know that the sign bit is either zero or one, determine the number of
3589 // identical bits in the top of the input value.
3590 return std::max(FirstAnswer, Known.countMinSignBits());
3591}
3592
3594 const TargetLibraryInfo *TLI) {
3595 const Function *F = CB.getCalledFunction();
3596 if (!F)
3598
3599 if (F->isIntrinsic())
3600 return F->getIntrinsicID();
3601
3602 // We are going to infer semantics of a library function based on mapping it
3603 // to an LLVM intrinsic. Check that the library function is available from
3604 // this callbase and in this environment.
3605 LibFunc Func;
3606 if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) ||
3607 !CB.onlyReadsMemory())
3609
3610 switch (Func) {
3611 default:
3612 break;
3613 case LibFunc_sin:
3614 case LibFunc_sinf:
3615 case LibFunc_sinl:
3616 return Intrinsic::sin;
3617 case LibFunc_cos:
3618 case LibFunc_cosf:
3619 case LibFunc_cosl:
3620 return Intrinsic::cos;
3621 case LibFunc_exp:
3622 case LibFunc_expf:
3623 case LibFunc_expl:
3624 return Intrinsic::exp;
3625 case LibFunc_exp2:
3626 case LibFunc_exp2f:
3627 case LibFunc_exp2l:
3628 return Intrinsic::exp2;
3629 case LibFunc_log:
3630 case LibFunc_logf:
3631 case LibFunc_logl:
3632 return Intrinsic::log;
3633 case LibFunc_log10:
3634 case LibFunc_log10f:
3635 case LibFunc_log10l:
3636 return Intrinsic::log10;
3637 case LibFunc_log2:
3638 case LibFunc_log2f:
3639 case LibFunc_log2l:
3640 return Intrinsic::log2;
3641 case LibFunc_fabs:
3642 case LibFunc_fabsf:
3643 case LibFunc_fabsl:
3644 return Intrinsic::fabs;
3645 case LibFunc_fmin:
3646 case LibFunc_fminf:
3647 case LibFunc_fminl:
3648 return Intrinsic::minnum;
3649 case LibFunc_fmax:
3650 case LibFunc_fmaxf:
3651 case LibFunc_fmaxl:
3652 return Intrinsic::maxnum;
3653 case LibFunc_copysign:
3654 case LibFunc_copysignf:
3655 case LibFunc_copysignl:
3656 return Intrinsic::copysign;
3657 case LibFunc_floor:
3658 case LibFunc_floorf:
3659 case LibFunc_floorl:
3660 return Intrinsic::floor;
3661 case LibFunc_ceil:
3662 case LibFunc_ceilf:
3663 case LibFunc_ceill:
3664 return Intrinsic::ceil;
3665 case LibFunc_trunc:
3666 case LibFunc_truncf:
3667 case LibFunc_truncl:
3668 return Intrinsic::trunc;
3669 case LibFunc_rint:
3670 case LibFunc_rintf:
3671 case LibFunc_rintl:
3672 return Intrinsic::rint;
3673 case LibFunc_nearbyint:
3674 case LibFunc_nearbyintf:
3675 case LibFunc_nearbyintl:
3676 return Intrinsic::nearbyint;
3677 case LibFunc_round:
3678 case LibFunc_roundf:
3679 case LibFunc_roundl:
3680 return Intrinsic::round;
3681 case LibFunc_roundeven:
3682 case LibFunc_roundevenf:
3683 case LibFunc_roundevenl:
3684 return Intrinsic::roundeven;
3685 case LibFunc_pow:
3686 case LibFunc_powf:
3687 case LibFunc_powl:
3688 return Intrinsic::pow;
3689 case LibFunc_sqrt:
3690 case LibFunc_sqrtf:
3691 case LibFunc_sqrtl:
3692 return Intrinsic::sqrt;
3693 }
3694
3696}
3697
3698/// Deprecated, use computeKnownFPClass instead.
3699///
3700/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
3701/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
3702/// bit despite comparing equal.
3704 const DataLayout &DL,
3705 const TargetLibraryInfo *TLI,
3706 bool SignBitOnly, unsigned Depth) {
3707 // TODO: This function does not do the right thing when SignBitOnly is true
3708 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
3709 // which flips the sign bits of NaNs. See
3710 // https://llvm.org/bugs/show_bug.cgi?id=31702.
3711
3712 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3713 return !CFP->getValueAPF().isNegative() ||
3714 (!SignBitOnly && CFP->getValueAPF().isZero());
3715 }
3716
3717 // Handle vector of constants.
3718 if (auto *CV = dyn_cast<Constant>(V)) {
3719 if (auto *CVFVTy = dyn_cast<FixedVectorType>(CV->getType())) {
3720 unsigned NumElts = CVFVTy->getNumElements();
3721 for (unsigned i = 0; i != NumElts; ++i) {
3722 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
3723 if (!CFP)
3724 return false;
3725 if (CFP->getValueAPF().isNegative() &&
3726 (SignBitOnly || !CFP->getValueAPF().isZero()))
3727 return false;
3728 }
3729
3730 // All non-negative ConstantFPs.
3731 return true;
3732 }
3733 }
3734
3736 return false;
3737
3738 const Operator *I = dyn_cast<Operator>(V);
3739 if (!I)
3740 return false;
3741
3742 switch (I->getOpcode()) {
3743 default:
3744 break;
3745 // Unsigned integers are always nonnegative.
3746 case Instruction::UIToFP:
3747 return true;
3748 case Instruction::FDiv:
3749 // X / X is always exactly 1.0 or a NaN.
3750 if (I->getOperand(0) == I->getOperand(1) &&
3751 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
3752 return true;
3753
3754 // Set SignBitOnly for RHS, because X / -0.0 is -Inf (or NaN).
3755 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3756 SignBitOnly, Depth + 1) &&
3757 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), DL, TLI,
3758 /*SignBitOnly*/ true, Depth + 1);
3759 case Instruction::FMul:
3760 // X * X is always non-negative or a NaN.
3761 if (I->getOperand(0) == I->getOperand(1) &&
3762 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
3763 return true;
3764
3765 [[fallthrough]];
3766 case Instruction::FAdd:
3767 case Instruction::FRem:
3768 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3769 SignBitOnly, Depth + 1) &&
3770 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), DL, TLI,
3771 SignBitOnly, Depth + 1);
3772 case Instruction::Select:
3773 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), DL, TLI,
3774 SignBitOnly, Depth + 1) &&
3775 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), DL, TLI,
3776 SignBitOnly, Depth + 1);
3777 case Instruction::FPExt:
3778 case Instruction::FPTrunc:
3779 // Widening/narrowing never change sign.
3780 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3781 SignBitOnly, Depth + 1);
3782 case Instruction::ExtractElement:
3783 // Look through extract element. At the moment we keep this simple and skip
3784 // tracking the specific element. But at least we might find information
3785 // valid for all elements of the vector.
3786 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3787 SignBitOnly, Depth + 1);
3788 case Instruction::Call:
3789 const auto *CI = cast<CallInst>(I);
3790 Intrinsic::ID IID = getIntrinsicForCallSite(*CI, TLI);
3791 switch (IID) {
3792 default:
3793 break;
3794 case Intrinsic::canonicalize:
3795 case Intrinsic::arithmetic_fence:
3796 case Intrinsic::floor:
3797 case Intrinsic::ceil:
3798 case Intrinsic::trunc:
3799 case Intrinsic::rint:
3800 case Intrinsic::nearbyint:
3801 case Intrinsic::round:
3802 case Intrinsic::roundeven:
3803 case Intrinsic::fptrunc_round:
3804 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3805 SignBitOnly, Depth + 1);
3806 case Intrinsic::maxnum: {
3807 Value *V0 = I->getOperand(0), *V1 = I->getOperand(1);
3808 auto isPositiveNum = [&](Value *V) {
3809 if (SignBitOnly) {
3810 // With SignBitOnly, this is tricky because the result of
3811 // maxnum(+0.0, -0.0) is unspecified. Just check if the operand is
3812 // a constant strictly greater than 0.0.
3813 const APFloat *C;
3814 return match(V, m_APFloat(C)) &&
3815 *C > APFloat::getZero(C->getSemantics());
3816 }
3817
3818 // -0.0 compares equal to 0.0, so if this operand is at least -0.0,
3819 // maxnum can't be ordered-less-than-zero.
3820 return isKnownNeverNaN(V, DL, TLI) &&
3821 cannotBeOrderedLessThanZeroImpl(V, DL, TLI, false, Depth + 1);
3822 };
3823
3824 // TODO: This could be improved. We could also check that neither operand
3825 // has its sign bit set (and at least 1 is not-NAN?).
3826 return isPositiveNum(V0) || isPositiveNum(V1);
3827 }
3828
3829 case Intrinsic::maximum:
3830 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3831 SignBitOnly, Depth + 1) ||
3832 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), DL, TLI,
3833 SignBitOnly, Depth + 1);
3834 case Intrinsic::minnum:
3835 case Intrinsic::minimum:
3836 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3837 SignBitOnly, Depth + 1) &&
3838 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), DL, TLI,
3839 SignBitOnly, Depth + 1);
3840 case Intrinsic::exp:
3841 case Intrinsic::exp2:
3842 case Intrinsic::fabs:
3843 return true;
3844 case Intrinsic::copysign:
3845 // Only the sign operand matters.
3846 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), DL, TLI, true,
3847 Depth + 1);
3848 case Intrinsic::sqrt:
3849 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
3850 if (!SignBitOnly)
3851 return true;
3852 return CI->hasNoNaNs() &&
3853 (CI->hasNoSignedZeros() ||
3854 cannotBeNegativeZero(CI->getOperand(0), DL, TLI));
3855
3856 case Intrinsic::powi:
3857 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
3858 // powi(x,n) is non-negative if n is even.
3859 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
3860 return true;
3861 }
3862 // TODO: This is not correct. Given that exp is an integer, here are the
3863 // ways that pow can return a negative value:
3864 //
3865 // pow(x, exp) --> negative if exp is odd and x is negative.
3866 // pow(-0, exp) --> -inf if exp is negative odd.
3867 // pow(-0, exp) --> -0 if exp is positive odd.
3868 // pow(-inf, exp) --> -0 if exp is negative odd.
3869 // pow(-inf, exp) --> -inf if exp is positive odd.
3870 //
3871 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3872 // but we must return false if x == -0. Unfortunately we do not currently
3873 // have a way of expressing this constraint. See details in
3874 // https://llvm.org/bugs/show_bug.cgi?id=31702.
3875 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), DL, TLI,
3876 SignBitOnly, Depth + 1);
3877
3878 case Intrinsic::fma:
3879 case Intrinsic::fmuladd:
3880 // x*x+y is non-negative if y is non-negative.
3881 return I->getOperand(0) == I->getOperand(1) &&
3882 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3883 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), DL, TLI,
3884 SignBitOnly, Depth + 1);
3885 }
3886 break;
3887 }
3888 return false;
3889}
3890
3892 const TargetLibraryInfo *TLI) {
3893 // FIXME: Use computeKnownFPClass and pass all arguments
3894 return cannotBeOrderedLessThanZeroImpl(V, DL, TLI, true, 0);
3895}
3896
3897/// Return true if it's possible to assume IEEE treatment of input denormals in
3898/// \p F for \p Val.
3899static bool inputDenormalIsIEEE(const Function &F, const Type *Ty) {
3900 Ty = Ty->getScalarType();
3901 return F.getDenormalMode(Ty->getFltSemantics()).Input == DenormalMode::IEEE;
3902}
3903
3904static bool inputDenormalIsIEEEOrPosZero(const Function &F, const Type *Ty) {
3905 Ty = Ty->getScalarType();
3906 DenormalMode Mode = F.getDenormalMode(Ty->getFltSemantics());
3907 return Mode.Input == DenormalMode::IEEE ||
3908 Mode.Input == DenormalMode::PositiveZero;
3909}
3910
3911static bool outputDenormalIsIEEEOrPosZero(const Function &F, const Type *Ty) {
3912 Ty = Ty->getScalarType();
3913 DenormalMode Mode = F.getDenormalMode(Ty->getFltSemantics());
3914 return Mode.Output == DenormalMode::IEEE ||
3915 Mode.Output == DenormalMode::PositiveZero;
3916}
3917
3919 return isKnownNeverZero() &&
3921}
3922
3924 Type *Ty) const {
3925 return isKnownNeverNegZero() &&
3927}
3928
3930 Type *Ty) const {
3931 if (!isKnownNeverPosZero())
3932 return false;
3933
3934 // If we know there are no denormals, nothing can be flushed to zero.
3936 return true;
3937
3938 DenormalMode Mode = F.getDenormalMode(Ty->getScalarType()->getFltSemantics());
3939 switch (Mode.Input) {
3940 case DenormalMode::IEEE:
3941 return true;
3943 // Negative subnormal won't flush to +0
3944 return isKnownNeverPosSubnormal();
3946 default:
3947 // Both positive and negative subnormal could flush to +0
3948 return false;
3949 }
3950
3951 llvm_unreachable("covered switch over denormal mode");
3952}
3953
3955 Type *Ty) {
3956 KnownFPClasses = Src.KnownFPClasses;
3957 // If we aren't assuming the source can't be a zero, we don't have to check if
3958 // a denormal input could be flushed.
3959 if (!Src.isKnownNeverPosZero() && !Src.isKnownNeverNegZero())
3960 return;
3961
3962 // If we know the input can't be a denormal, it can't be flushed to 0.
3963 if (Src.isKnownNeverSubnormal())
3964 return;
3965
3966 DenormalMode Mode = F.getDenormalMode(Ty->getScalarType()->getFltSemantics());
3967
3968 if (!Src.isKnownNeverPosSubnormal() && Mode != DenormalMode::getIEEE())
3970
3971 if (!Src.isKnownNeverNegSubnormal() && Mode != DenormalMode::getIEEE()) {
3972 if (Mode != DenormalMode::getPositiveZero())
3974
3975 if (Mode.Input == DenormalMode::PositiveZero ||
3976 Mode.Output == DenormalMode::PositiveZero ||
3977 Mode.Input == DenormalMode::Dynamic ||
3978 Mode.Output == DenormalMode::Dynamic)
3980 }
3981}
3982
3984 const Function &F, Type *Ty) {
3985 propagateDenormal(Src, F, Ty);
3986 propagateNaN(Src, /*PreserveSign=*/true);
3987}
3988
3989/// Returns a pair of values, which if passed to llvm.is.fpclass, returns the
3990/// same result as an fcmp with the given operands.
3991std::pair<Value *, FPClassTest> llvm::fcmpToClassTest(FCmpInst::Predicate Pred,
3992 const Function &F,
3993 Value *LHS, Value *RHS,
3994 bool LookThroughSrc) {
3995 const APFloat *ConstRHS;
3996 if (!match(RHS, m_APFloatAllowUndef(ConstRHS)))
3997 return {nullptr, fcAllFlags};
3998
3999 return fcmpToClassTest(Pred, F, LHS, ConstRHS, LookThroughSrc);
4000}
4001
4002std::pair<Value *, FPClassTest>
4004 const APFloat *ConstRHS, bool LookThroughSrc) {
4005 // fcmp ord x, zero|normal|subnormal|inf -> ~fcNan
4006 if (Pred == FCmpInst::FCMP_ORD && !ConstRHS->isNaN())
4007 return {LHS, ~fcNan};
4008
4009 // fcmp uno x, zero|normal|subnormal|inf -> fcNan
4010 if (Pred == FCmpInst::FCMP_UNO && !ConstRHS->isNaN())
4011 return {LHS, fcNan};
4012
4013 if (ConstRHS->isZero()) {
4014 // Compares with fcNone are only exactly equal to fcZero if input denormals
4015 // are not flushed.
4016 // TODO: Handle DAZ by expanding masks to cover subnormal cases.
4017 if (Pred != FCmpInst::FCMP_ORD && Pred != FCmpInst::FCMP_UNO &&
4019 return {nullptr, fcAllFlags};
4020
4021 switch (Pred) {
4022 case FCmpInst::FCMP_OEQ: // Match x == 0.0
4023 return {LHS, fcZero};
4024 case FCmpInst::FCMP_UEQ: // Match isnan(x) || (x == 0.0)
4025 return {LHS, fcZero | fcNan};
4026 case FCmpInst::FCMP_UNE: // Match (x != 0.0)
4027 return {LHS, ~fcZero};
4028 case FCmpInst::FCMP_ONE: // Match !isnan(x) && x != 0.0
4029 return {LHS, ~fcNan & ~fcZero};
4030 case FCmpInst::FCMP_ORD:
4031 // Canonical form of ord/uno is with a zero. We could also handle
4032 // non-canonical other non-NaN constants or LHS == RHS.
4033 return {LHS, ~fcNan};
4034 case FCmpInst::FCMP_UNO:
4035 return {LHS, fcNan};
4036 case FCmpInst::FCMP_OGT: // x > 0
4037 return {LHS, fcPosSubnormal | fcPosNormal | fcPosInf};
4038 case FCmpInst::FCMP_UGT: // isnan(x) || x > 0
4040 case FCmpInst::FCMP_OGE: // x >= 0
4041 return {LHS, fcPositive | fcNegZero};
4042 case FCmpInst::FCMP_UGE: // isnan(x) || x >= 0
4043 return {LHS, fcPositive | fcNegZero | fcNan};
4044 case FCmpInst::FCMP_OLT: // x < 0
4045 return {LHS, fcNegSubnormal | fcNegNormal | fcNegInf};
4046 case FCmpInst::FCMP_ULT: // isnan(x) || x < 0
4048 case FCmpInst::FCMP_OLE: // x <= 0
4049 return {LHS, fcNegative | fcPosZero};
4050 case FCmpInst::FCMP_ULE: // isnan(x) || x <= 0
4051 return {LHS, fcNegative | fcPosZero | fcNan};
4052 default:
4053 break;
4054 }
4055
4056 return {nullptr, fcAllFlags};
4057 }
4058
4059 Value *Src = LHS;
4060 const bool IsFabs = LookThroughSrc && match(LHS, m_FAbs(m_Value(Src)));
4061
4062 // Compute the test mask that would return true for the ordered comparisons.
4063 FPClassTest Mask;
4064
4065 if (ConstRHS->isInfinity()) {
4066 switch (Pred) {
4067 case FCmpInst::FCMP_OEQ:
4068 case FCmpInst::FCMP_UNE: {
4069 // Match __builtin_isinf patterns
4070 //
4071 // fcmp oeq x, +inf -> is_fpclass x, fcPosInf
4072 // fcmp oeq fabs(x), +inf -> is_fpclass x, fcInf
4073 // fcmp oeq x, -inf -> is_fpclass x, fcNegInf
4074 // fcmp oeq fabs(x), -inf -> is_fpclass x, 0 -> false
4075 //
4076 // fcmp une x, +inf -> is_fpclass x, ~fcPosInf
4077 // fcmp une fabs(x), +inf -> is_fpclass x, ~fcInf
4078 // fcmp une x, -inf -> is_fpclass x, ~fcNegInf
4079 // fcmp une fabs(x), -inf -> is_fpclass x, fcAllFlags -> true
4080
4081 if (ConstRHS->isNegative()) {
4082 Mask = fcNegInf;
4083 if (IsFabs)
4084 Mask = fcNone;
4085 } else {
4086 Mask = fcPosInf;
4087 if (IsFabs)
4088 Mask |= fcNegInf;
4089 }
4090
4091 break;
4092 }
4093 case FCmpInst::FCMP_ONE:
4094 case FCmpInst::FCMP_UEQ: {
4095 // Match __builtin_isinf patterns
4096 // fcmp one x, -inf -> is_fpclass x, fcNegInf
4097 // fcmp one fabs(x), -inf -> is_fpclass x, ~fcNegInf & ~fcNan
4098 // fcmp one x, +inf -> is_fpclass x, ~fcNegInf & ~fcNan
4099 // fcmp one fabs(x), +inf -> is_fpclass x, ~fcInf & fcNan
4100 //
4101 // fcmp ueq x, +inf -> is_fpclass x, fcPosInf|fcNan
4102 // fcmp ueq (fabs x), +inf -> is_fpclass x, fcInf|fcNan
4103 // fcmp ueq x, -inf -> is_fpclass x, fcNegInf|fcNan
4104 // fcmp ueq fabs(x), -inf -> is_fpclass x, fcNan
4105 if (ConstRHS->isNegative()) {
4106 Mask = ~fcNegInf & ~fcNan;
4107 if (IsFabs)
4108 Mask = ~fcNan;
4109 } else {
4110 Mask = ~fcPosInf & ~fcNan;
4111 if (IsFabs)
4112 Mask &= ~fcNegInf;
4113 }
4114
4115 break;
4116 }
4117 case FCmpInst::FCMP_OLT:
4118 case FCmpInst::FCMP_UGE: {
4119 if (ConstRHS->isNegative()) {
4120 // No value is ordered and less than negative infinity.
4121 // All values are unordered with or at least negative infinity.
4122 // fcmp olt x, -inf -> false
4123 // fcmp uge x, -inf -> true
4124 Mask = fcNone;
4125 break;
4126 }
4127
4128 // fcmp olt fabs(x), +inf -> fcFinite
4129 // fcmp uge fabs(x), +inf -> ~fcFinite
4130 // fcmp olt x, +inf -> fcFinite|fcNegInf
4131 // fcmp uge x, +inf -> ~(fcFinite|fcNegInf)
4132 Mask = fcFinite;
4133 if (!IsFabs)
4134 Mask |= fcNegInf;
4135 break;
4136 }
4137 case FCmpInst::FCMP_OGE:
4138 case FCmpInst::FCMP_ULT: {
4139 if (ConstRHS->isNegative()) {
4140 // fcmp oge x, -inf -> ~fcNan
4141 // fcmp oge fabs(x), -inf -> ~fcNan
4142 // fcmp ult x, -inf -> fcNan
4143 // fcmp ult fabs(x), -inf -> fcNan
4144 Mask = ~fcNan;
4145 break;
4146 }
4147
4148 // fcmp oge fabs(x), +inf -> fcInf
4149 // fcmp oge x, +inf -> fcPosInf
4150 // fcmp ult fabs(x), +inf -> ~fcInf
4151 // fcmp ult x, +inf -> ~fcPosInf
4152 Mask = fcPosInf;
4153 if (IsFabs)
4154 Mask |= fcNegInf;
4155 break;
4156 }
4157 case FCmpInst::FCMP_OGT:
4158 case FCmpInst::FCMP_ULE: {
4159 if (ConstRHS->isNegative()) {
4160 // fcmp ogt x, -inf -> fcmp one x, -inf
4161 // fcmp ogt fabs(x), -inf -> fcmp ord x, x
4162 // fcmp ule x, -inf -> fcmp ueq x, -inf
4163 // fcmp ule fabs(x), -inf -> fcmp uno x, x
4164 Mask = IsFabs ? ~fcNan : ~(fcNegInf | fcNan);
4165 break;
4166 }
4167
4168 // No value is ordered and greater than infinity.
4169 Mask = fcNone;
4170 break;
4171 }
4172 default:
4173 return {nullptr, fcAllFlags};
4174 }
4175 } else if (ConstRHS->isSmallestNormalized() && !ConstRHS->isNegative()) {
4176 // Match pattern that's used in __builtin_isnormal.
4177 switch (Pred) {
4178 case FCmpInst::FCMP_OLT:
4179 case FCmpInst::FCMP_UGE: {
4180 // fcmp olt x, smallest_normal -> fcNegInf|fcNegNormal|fcSubnormal|fcZero
4181 // fcmp olt fabs(x), smallest_normal -> fcSubnormal|fcZero
4182 // fcmp uge x, smallest_normal -> fcNan|fcPosNormal|fcPosInf
4183 // fcmp uge fabs(x), smallest_normal -> ~(fcSubnormal|fcZero)
4184 Mask = fcZero | fcSubnormal;
4185 if (!IsFabs)
4186 Mask |= fcNegNormal | fcNegInf;
4187
4188 break;
4189 }
4190 case FCmpInst::FCMP_OGE:
4191 case FCmpInst::FCMP_ULT: {
4192 // fcmp oge x, smallest_normal -> fcPosNormal | fcPosInf
4193 // fcmp oge fabs(x), smallest_normal -> fcInf | fcNormal
4194 // fcmp ult x, smallest_normal -> ~(fcPosNormal | fcPosInf)
4195 // fcmp ult fabs(x), smallest_normal -> ~(fcInf | fcNormal)
4196 Mask = fcPosInf | fcPosNormal;
4197 if (IsFabs)
4198 Mask |= fcNegInf | fcNegNormal;
4199 break;
4200 }
4201 default:
4202 return {nullptr, fcAllFlags};
4203 }
4204 } else if (ConstRHS->isNaN()) {
4205 // fcmp o__ x, nan -> false
4206 // fcmp u__ x, nan -> true
4207 Mask = fcNone;
4208 } else
4209 return {nullptr, fcAllFlags};
4210
4211 // Invert the comparison for the unordered cases.
4212 if (FCmpInst::isUnordered(Pred))
4213 Mask = ~Mask;
4214
4215 return {Src, Mask};
4216}
4217
4219 const SimplifyQuery &Q) {
4220 FPClassTest KnownFromAssume = fcAllFlags;
4221
4222 // Try to restrict the floating-point classes based on information from
4223 // assumptions.
4224 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
4225 if (!AssumeVH)
4226 continue;
4227 CallInst *I = cast<CallInst>(AssumeVH);
4228 const Function *F = I->getFunction();
4229
4230 assert(F == Q.CxtI->getParent()->getParent() &&
4231 "Got assumption for the wrong function!");
4232 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
4233 "must be an assume intrinsic");
4234
4235 if (!isValidAssumeForContext(I, Q.CxtI, Q.DT))
4236 continue;
4237
4238 CmpInst::Predicate Pred;
4239 Value *LHS, *RHS;
4240 uint64_t ClassVal = 0;
4241 if (match(I->getArgOperand(0), m_FCmp(Pred, m_Value(LHS), m_Value(RHS)))) {
4242 auto [TestedValue, TestedMask] =
4243 fcmpToClassTest(Pred, *F, LHS, RHS, true);
4244 // First see if we can fold in fabs/fneg into the test.
4245 if (TestedValue == V)
4246 KnownFromAssume &= TestedMask;
4247 else {
4248 // Try again without the lookthrough if we found a different source
4249 // value.
4250 auto [TestedValue, TestedMask] =
4251 fcmpToClassTest(Pred, *F, LHS, RHS, false);
4252 if (TestedValue == V)
4253 KnownFromAssume &= TestedMask;
4254 }
4255 } else if (match(I->getArgOperand(0),
4256 m_Intrinsic<Intrinsic::is_fpclass>(
4257 m_Value(LHS), m_ConstantInt(ClassVal)))) {
4258 KnownFromAssume &= static_cast<FPClassTest>(ClassVal);
4259 }
4260 }
4261
4262 return KnownFromAssume;
4263}
4264
4265void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
4266 FPClassTest InterestedClasses, KnownFPClass &Known,
4267 unsigned Depth, const SimplifyQuery &Q);
4268
4269static void computeKnownFPClass(const Value *V, KnownFPClass &Known,
4270 FPClassTest InterestedClasses, unsigned Depth,
4271 const SimplifyQuery &Q) {
4272 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
4273 APInt DemandedElts =
4274 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
4275 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Depth, Q);
4276}
4277
4279 const APInt &DemandedElts,
4280 FPClassTest InterestedClasses,
4281 KnownFPClass &Known, unsigned Depth,
4282 const SimplifyQuery &Q) {
4283 if ((InterestedClasses &
4285 return;
4286
4287 KnownFPClass KnownSrc;
4288 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
4289 KnownSrc, Depth + 1, Q);
4290
4291 // Sign should be preserved
4292 // TODO: Handle cannot be ordered greater than zero
4293 if (KnownSrc.cannotBeOrderedLessThanZero())
4295
4296 Known.propagateNaN(KnownSrc, true);
4297
4298 // Infinity needs a range check.
4299}
4300
4301// TODO: Merge implementation of cannotBeOrderedLessThanZero into here.
4302void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
4303 FPClassTest InterestedClasses, KnownFPClass &Known,
4304 unsigned Depth, const SimplifyQuery &Q) {
4305 assert(Known.isUnknown() && "should not be called with known information");
4306
4307 if (!DemandedElts) {
4308 // No demanded elts, better to assume we don't know anything.
4309 Known.resetAll();
4310 return;
4311 }
4312
4313 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4314
4315 if (auto *CFP = dyn_cast_or_null<ConstantFP>(V)) {
4316 Known.KnownFPClasses = CFP->getValueAPF().classify();
4317 Known.SignBit = CFP->isNegative();
4318 return;
4319 }
4320
4321 // Try to handle fixed width vector constants
4322 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
4323 const Constant *CV = dyn_cast<Constant>(V);
4324 if (VFVTy && CV) {
4325 Known.KnownFPClasses = fcNone;
4326
4327 // For vectors, verify that each element is not NaN.
4328 unsigned NumElts = VFVTy->getNumElements();
4329 for (unsigned i = 0; i != NumElts; ++i) {
4330 Constant *Elt = CV->getAggregateElement(i);
4331 if (!Elt) {
4332 Known = KnownFPClass();
4333 return;
4334 }
4335 if (isa<UndefValue>(Elt))
4336 continue;
4337 auto *CElt = dyn_cast<ConstantFP>(Elt);
4338 if (!CElt) {
4339 Known = KnownFPClass();
4340 return;
4341 }
4342
4343 KnownFPClass KnownElt{CElt->getValueAPF().classify(), CElt->isNegative()};
4344 Known |= KnownElt;
4345 }
4346
4347 return;
4348 }
4349
4350 FPClassTest KnownNotFromFlags = fcNone;
4351 if (const auto *CB = dyn_cast<CallBase>(V))
4352 KnownNotFromFlags |= CB->getRetNoFPClass();
4353 else if (const auto *Arg = dyn_cast<Argument>(V))
4354 KnownNotFromFlags |= Arg->getNoFPClass();
4355
4356 const Operator *Op = dyn_cast<Operator>(V);
4357 if (const FPMathOperator *FPOp = dyn_cast_or_null<FPMathOperator>(Op)) {
4358 if (FPOp->hasNoNaNs())
4359 KnownNotFromFlags |= fcNan;
4360 if (FPOp->hasNoInfs())
4361 KnownNotFromFlags |= fcInf;
4362 }
4363
4364 if (Q.AC) {
4365 FPClassTest AssumedClasses = computeKnownFPClassFromAssumes(V, Q);
4366 KnownNotFromFlags |= ~AssumedClasses;
4367 }
4368
4369 // We no longer need to find out about these bits from inputs if we can
4370 // assume this from flags/attributes.
4371 InterestedClasses &= ~KnownNotFromFlags;
4372
4373 auto ClearClassesFromFlags = make_scope_exit([=, &Known] {
4374 Known.knownNot(KnownNotFromFlags);
4375 });
4376
4377 if (!Op)
4378 return;
4379
4380 // All recursive calls that increase depth must come after this.
4382 return;
4383
4384 const unsigned Opc = Op->getOpcode();
4385 switch (Opc) {
4386 case Instruction::FNeg: {
4387 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
4388 Known, Depth + 1, Q);
4389 Known.fneg();
4390 break;
4391 }
4392 case Instruction::Select: {
4393 Value *Cond = Op->getOperand(0);
4394 Value *LHS = Op->getOperand(1);
4395 Value *RHS = Op->getOperand(2);
4396
4397 FPClassTest FilterLHS = fcAllFlags;
4398 FPClassTest FilterRHS = fcAllFlags;
4399
4400 Value *TestedValue = nullptr;
4401 FPClassTest TestedMask = fcNone;
4402 uint64_t ClassVal = 0;
4403 const Function *F = cast<Instruction>(Op)->getFunction();
4404 CmpInst::Predicate Pred;
4405 Value *CmpLHS, *CmpRHS;
4406 if (F && match(Cond, m_FCmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)))) {
4407 // If the select filters out a value based on the class, it no longer
4408 // participates in the class of the result
4409
4410 // TODO: In some degenerate cases we can infer something if we try again
4411 // without looking through sign operations.
4412 bool LookThroughFAbsFNeg = CmpLHS != LHS && CmpLHS != RHS;
4413 std::tie(TestedValue, TestedMask) =
4414 fcmpToClassTest(Pred, *F, CmpLHS, CmpRHS, LookThroughFAbsFNeg);
4415 } else if (match(Cond,
4416 m_Intrinsic<Intrinsic::is_fpclass>(
4417 m_Value(TestedValue), m_ConstantInt(ClassVal)))) {
4418 TestedMask = static_cast<FPClassTest>(ClassVal);
4419 }
4420
4421 if (TestedValue == LHS) {
4422 // match !isnan(x) ? x : y
4423 FilterLHS = TestedMask;
4424 } else if (TestedValue == RHS) {
4425 // match !isnan(x) ? y : x
4426 FilterRHS = ~TestedMask;
4427 }
4428
4429 KnownFPClass Known2;
4430 computeKnownFPClass(LHS, DemandedElts, InterestedClasses & FilterLHS, Known,
4431 Depth + 1, Q);
4432 Known.KnownFPClasses &= FilterLHS;
4433
4434 computeKnownFPClass(RHS, DemandedElts, InterestedClasses & FilterRHS,
4435 Known2, Depth + 1, Q);
4436 Known2.KnownFPClasses &= FilterRHS;
4437
4438 Known |= Known2;
4439 break;
4440 }
4441 case Instruction::Call: {
4442 const CallInst *II = cast<CallInst>(Op);
4443 const Intrinsic::ID IID = II->getIntrinsicID();
4444 switch (IID) {
4445 case Intrinsic::fabs: {
4446 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
4447 // If we only care about the sign bit we don't need to inspect the
4448 // operand.
4449 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
4450 InterestedClasses, Known, Depth + 1, Q);
4451 }
4452
4453 Known.fabs();
4454 break;
4455 }
4456 case Intrinsic::copysign: {
4457 KnownFPClass KnownSign;
4458
4459 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
4460 Known, Depth + 1, Q);
4461 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
4462 KnownSign, Depth + 1, Q);
4463 Known.copysign(KnownSign);
4464 break;
4465 }
4466 case Intrinsic::fma:
4467 case Intrinsic::fmuladd: {
4468 if ((InterestedClasses & fcNegative) == fcNone)
4469 break;
4470
4471 if (II->getArgOperand(0) != II->getArgOperand(1))
4472 break;
4473
4474 // The multiply cannot be -0 and therefore the add can't be -0
4475 Known.knownNot(fcNegZero);
4476
4477 // x * x + y is non-negative if y is non-negative.
4478 KnownFPClass KnownAddend;
4479 computeKnownFPClass(II->getArgOperand(2), DemandedElts, InterestedClasses,
4480 KnownAddend, Depth + 1, Q);
4481
4482 // TODO: Known sign bit with no nans
4483 if (KnownAddend.cannotBeOrderedLessThanZero())
4484 Known.knownNot(fcNegative);
4485 break;
4486 }
4487 case Intrinsic::sqrt:
4488 case Intrinsic::experimental_constrained_sqrt: {
4489 KnownFPClass KnownSrc;
4490 FPClassTest InterestedSrcs = InterestedClasses;
4491 if (InterestedClasses & fcNan)
4492 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
4493
4494 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
4495 KnownSrc, Depth + 1, Q);
4496
4497 if (KnownSrc.isKnownNeverPosInfinity())
4498 Known.knownNot(fcPosInf);
4499 if (KnownSrc.isKnownNever(fcSNan))
4500 Known.knownNot(fcSNan);
4501
4502 // Any negative value besides -0 returns a nan.
4503 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
4504 Known.knownNot(fcNan);
4505
4506 // The only negative value that can be returned is -0 for -0 inputs.
4507 Known.knownNot(