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