LLVM 24.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/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98/// Returns the bitwidth of the given scalar or pointer type. For vector types,
99/// returns the element type's bitwidth.
100static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
101 if (unsigned BitWidth = Ty->getScalarSizeInBits())
102 return BitWidth;
103
104 return DL.getPointerTypeSizeInBits(Ty);
105}
106
107// Given the provided Value and, potentially, a context instruction, return
108// the preferred context instruction (if any).
109static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
110 // If we've been provided with a context instruction, then use that (provided
111 // it has been inserted).
112 if (CxtI && CxtI->getParent())
113 return CxtI;
114
115 // If the value is really an already-inserted instruction, then use that.
116 CxtI = dyn_cast<Instruction>(V);
117 if (CxtI && CxtI->getParent())
118 return CxtI;
119
120 return nullptr;
121}
122
124 const APInt &DemandedElts,
125 APInt &DemandedLHS, APInt &DemandedRHS) {
126 if (isa<ScalableVectorType>(Shuf->getType())) {
127 assert(DemandedElts == APInt(1,1));
128 DemandedLHS = DemandedRHS = DemandedElts;
129 return true;
130 }
131
132 int NumElts =
133 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
134 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
135 DemandedElts, DemandedLHS, DemandedRHS);
136}
137
138static void computeKnownBits(const Value *V, const APInt &DemandedElts,
139 KnownBits &Known, const SimplifyQuery &Q,
140 unsigned Depth);
141
143 const SimplifyQuery &Q, unsigned Depth) {
144 // Since the number of lanes in a scalable vector is unknown at compile time,
145 // we track one bit which is implicitly broadcast to all lanes. This means
146 // that all lanes in a scalable vector are considered demanded.
147 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
148 APInt DemandedElts =
149 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
150 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
151}
152
154 const DataLayout &DL, AssumptionCache *AC,
155 const Instruction *CxtI, const DominatorTree *DT,
156 bool UseInstrInfo, unsigned Depth) {
158 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
159 Depth);
160}
161
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT, bool UseInstrInfo,
165 unsigned Depth) {
166 return computeKnownBits(
167 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
168}
169
170KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
171 const DataLayout &DL, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT, bool UseInstrInfo,
174 unsigned Depth) {
175 return computeKnownBits(
176 V, DemandedElts,
177 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
178}
179
182 const SimplifyQuery &SQ) {
183 // Look for an inverted mask: (X & ~M) op (Y & M).
184 {
185 Value *M;
186 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
188 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
191 }
192
193 // X op (Y & ~X)
195 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
198
199 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
200 // for constant Y.
201 Value *Y;
202 if (match(RHS,
204 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
205 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
206 return IsNoUndef ? NoCommonBitsSetResult::Known
208 }
209
210 // Peek through extends to find a 'not' of the other side:
211 // (ext Y) op ext(~Y)
212 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
214 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
217
218 // Look for: (A & B) op ~(A | B)
219 {
220 Value *A, *B;
221 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
223 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
224 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
225 return IsNoUndef ? NoCommonBitsSetResult::Known
227 }
228 }
229
230 // Look for: (X << V) op (Y >> (BitWidth - V))
231 // or (X >> V) op (Y << (BitWidth - V))
232 {
233 const Value *V;
234 const APInt *R;
235 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
236 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
237 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
238 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
239 R->uge(LHS->getType()->getScalarSizeInBits()))
241 }
242
244}
245
248 const WithCache<const Value *> &RHSCache,
249 const SimplifyQuery &SQ) {
250 const Value *LHS = LHSCache.getValue();
251 const Value *RHS = RHSCache.getValue();
252
253 assert(LHS->getType() == RHS->getType() &&
254 "LHS and RHS should have the same type");
255 assert(LHS->getType()->isIntOrIntVectorTy() &&
256 "LHS and RHS should be integers");
257
259 if (Result == NoCommonBitsSetResult::Known)
261
262 NoCommonBitsSetResult CommuteResult =
264 if (CommuteResult == NoCommonBitsSetResult::Known)
266
268 RHSCache.getKnownBits(SQ)))
270
274
276}
277
279 const WithCache<const Value *> &RHSCache,
280 const SimplifyQuery &SQ) {
281 NoCommonBitsSetResult Result =
282 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
283 return Result == NoCommonBitsSetResult::Known;
284}
285
287 return !I->user_empty() &&
288 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
289}
290
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 CmpPredicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
299 bool OrZero, AssumptionCache *AC,
300 const Instruction *CxtI,
301 const DominatorTree *DT, bool UseInstrInfo,
302 unsigned Depth) {
303 return ::isKnownToBeAPowerOfTwo(
304 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
305 Depth);
306}
307
308static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
309 const SimplifyQuery &Q, unsigned Depth);
310
312 unsigned Depth) {
313 return computeKnownBits(V, SQ, Depth).isNonNegative();
314}
315
317 unsigned Depth) {
318 if (auto *CI = dyn_cast<ConstantInt>(V))
319 return CI->getValue().isStrictlyPositive();
320
321 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
322 // this updated.
324 return Known.isNonNegative() &&
325 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
326}
327
329 unsigned Depth) {
330 return computeKnownBits(V, SQ, Depth).isNegative();
331}
332
333static bool isKnownNonEqual(const Value *V1, const Value *V2,
334 const APInt &DemandedElts, const SimplifyQuery &Q,
335 unsigned Depth);
336
337static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
338 const Value *RHS);
339
340bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
341 const SimplifyQuery &Q, unsigned Depth) {
342 // We don't support looking through casts.
343 if (V1 == V2 || V1->getType() != V2->getType())
344 return false;
345 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
349}
350
351bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
352 const SimplifyQuery &SQ, unsigned Depth) {
353 KnownBits Known(Mask.getBitWidth());
355 return Mask.isSubsetOf(Known.Zero);
356}
357
358static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
359 const SimplifyQuery &Q, unsigned Depth);
360
361static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
362 unsigned Depth = 0) {
363 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
364 APInt DemandedElts =
365 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
366 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
367}
368
369unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
370 AssumptionCache *AC, const Instruction *CxtI,
371 const DominatorTree *DT, bool UseInstrInfo,
372 unsigned Depth) {
373 return ::ComputeNumSignBits(
374 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
375}
376
378 AssumptionCache *AC,
379 const Instruction *CxtI,
380 const DominatorTree *DT,
381 unsigned Depth) {
382 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
383 return V->getType()->getScalarSizeInBits() - SignBits + 1;
384}
385
386/// Try to detect the lerp pattern: a * (b - c) + c * d
387/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
388///
389/// In that particular case, we can use the following chain of reasoning:
390///
391/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
392///
393/// Since that is true for arbitrary a, b, c and d within our constraints, we
394/// can conclude that:
395///
396/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
397///
398/// Considering that any result of the lerp would be less or equal to U, it
399/// would have at least the number of leading 0s as in U.
400///
401/// While being quite a specific situation, it is fairly common in computer
402/// graphics in the shape of alpha blending.
403///
404/// Modifies given KnownOut in-place with the inferred information.
405static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
406 const APInt &DemandedElts,
407 KnownBits &KnownOut,
408 const SimplifyQuery &Q,
409 unsigned Depth) {
410
411 Type *Ty = Op0->getType();
412 const unsigned BitWidth = Ty->getScalarSizeInBits();
413
414 // Only handle scalar types for now
415 if (Ty->isVectorTy())
416 return;
417
418 // Try to match: a * (b - c) + c * d.
419 // When a == 1 => A == nullptr, the same applies to d/D as well.
420 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
421 const Instruction *SubBC = nullptr;
422
423 const auto MatchSubBC = [&]() {
424 // (b - c) can have two forms that interest us:
425 //
426 // 1. sub nuw %b, %c
427 // 2. xor %c, %b
428 //
429 // For the first case, nuw flag guarantees our requirement b >= c.
430 //
431 // The second case might happen when the analysis can infer that b is a mask
432 // for c and we can transform sub operation into xor (that is usually true
433 // for constant b's). Even though xor is symmetrical, canonicalization
434 // ensures that the constant will be the RHS. We have additional checks
435 // later on to ensure that this xor operation is equivalent to subtraction.
437 m_Xor(m_Value(C), m_Value(B))));
438 };
439
440 const auto MatchASubBC = [&]() {
441 // Cases:
442 // - a * (b - c)
443 // - (b - c) * a
444 // - (b - c) <- a implicitly equals 1
445 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
446 };
447
448 const auto MatchCD = [&]() {
449 // Cases:
450 // - d * c
451 // - c * d
452 // - c <- d implicitly equals 1
454 };
455
456 const auto Match = [&](const Value *LHS, const Value *RHS) {
457 // We do use m_Specific(C) in MatchCD, so we have to make sure that
458 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
459 // has to evaluate first and return true.
460 //
461 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
462 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
463 };
464
465 if (!Match(Op0, Op1) && !Match(Op1, Op0))
466 return;
467
468 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
469 // For some of the values we use the convention of leaving
470 // it nullptr to signify an implicit constant 1.
471 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
473 };
474
475 // Check that all operands are non-negative
476 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
477 if (!KnownA.isNonNegative())
478 return;
479
480 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
481 if (!KnownD.isNonNegative())
482 return;
483
484 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
485 if (!KnownB.isNonNegative())
486 return;
487
488 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
489 if (!KnownC.isNonNegative())
490 return;
491
492 // If we matched subtraction as xor, we need to actually check that xor
493 // is semantically equivalent to subtraction.
494 //
495 // For that to be true, b has to be a mask for c or that b's known
496 // ones cover all known and possible ones of c.
497 if (SubBC->getOpcode() == Instruction::Xor &&
498 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
499 return;
500
501 const APInt MaxA = KnownA.getMaxValue();
502 const APInt MaxD = KnownD.getMaxValue();
503 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
504 const APInt MaxB = KnownB.getMaxValue();
505
506 // We can't infer leading zeros info if the upper-bound estimate wraps.
507 bool Overflow;
508 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
509
510 if (Overflow)
511 return;
512
513 // If we know that x <= y and both are positive than x has at least the same
514 // number of leading zeros as y.
515 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
516 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
517}
518
519static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
520 bool NSW, bool NUW,
521 const APInt &DemandedElts,
522 KnownBits &KnownOut, KnownBits &Known2,
523 const SimplifyQuery &Q, unsigned Depth) {
524 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
525
526 // If one operand is unknown and we have no nowrap information,
527 // the result will be unknown independently of the second operand.
528 if (KnownOut.isUnknown() && !NSW && !NUW)
529 return;
530
531 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
532 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
533
534 if (!Add && NSW && !KnownOut.isNonNegative() &&
536 .value_or(false) ||
537 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
538 KnownOut.makeNonNegative();
539
540 if (Add)
541 // Try to match lerp pattern and combine results
542 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
543}
544
545static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
546 bool NUW, const APInt &DemandedElts,
547 KnownBits &Known, KnownBits &Known2,
548 const SimplifyQuery &Q, unsigned Depth) {
549 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
550 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
551
552 bool isKnownNegative = false;
553 bool isKnownNonNegative = false;
554 // If the multiplication is known not to overflow, compute the sign bit.
555 if (NSW) {
556 if (Op0 == Op1) {
557 // The product of a number with itself is non-negative.
558 isKnownNonNegative = true;
559 } else {
560 bool isKnownNonNegativeOp1 = Known.isNonNegative();
561 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
562 bool isKnownNegativeOp1 = Known.isNegative();
563 bool isKnownNegativeOp0 = Known2.isNegative();
564 // The product of two numbers with the same sign is non-negative.
565 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
566 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
567 if (!isKnownNonNegative && NUW) {
568 // mul nuw nsw with a factor > 1 is non-negative.
569 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
570 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
571 KnownBits::sgt(Known2, One).value_or(false);
572 }
573
574 // The product of a negative number and a non-negative number is either
575 // negative or zero.
578 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
579 Known2.isNonZero()) ||
580 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
581 }
582 }
583
584 bool SelfMultiply = Op0 == Op1;
585 if (SelfMultiply)
586 SelfMultiply &=
587 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
588 Known = KnownBits::mul(Known, Known2, SelfMultiply);
589
590 if (SelfMultiply) {
591 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
592 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
593 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
594
595 if (OutValidBits < TyBits) {
596 APInt KnownZeroMask =
597 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
598 Known.Zero |= KnownZeroMask;
599 }
600 }
601
602 // Only make use of no-wrap flags if we failed to compute the sign bit
603 // directly. This matters if the multiplication always overflows, in
604 // which case we prefer to follow the result of the direct computation,
605 // though as the program is invoking undefined behaviour we can choose
606 // whatever we like here.
607 if (isKnownNonNegative && !Known.isNegative())
608 Known.makeNonNegative();
609 else if (isKnownNegative && !Known.isNonNegative())
610 Known.makeNegative();
611}
612
614 KnownBits &Known) {
615 unsigned BitWidth = Known.getBitWidth();
616 unsigned NumRanges = Ranges.getNumOperands() / 2;
617 assert(NumRanges >= 1);
618
619 Known.setAllConflict();
620
621 for (unsigned i = 0; i < NumRanges; ++i) {
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
625 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
626 ConstantRange Range(Lower->getValue(), Upper->getValue());
627 // BitWidth must equal the Ranges BitWidth for the correct number of high
628 // bits to be set.
629 assert(BitWidth == Range.getBitWidth() &&
630 "Known bit width must match range bit width!");
631
632 // The first CommonPrefixBits of all values in Range are equal.
633 unsigned CommonPrefixBits =
634 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
635 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
636 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
637 Known.One &= UnsignedMax & Mask;
638 Known.Zero &= ~UnsignedMax & Mask;
639 }
640}
641
642static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
643 // The instruction defining an assumption's condition itself is always
644 // considered ephemeral to that assumption (even if it has other
645 // non-ephemeral users). See r246696's test case for an example.
646 if (is_contained(I->operands(), E))
647 return true;
648
649 const auto *EI = dyn_cast<Instruction>(E);
650 if (!EI)
651 return false;
652
653 if (EI == I)
654 return true;
655
658 Visited.insert(EI);
659 WorkList.push_back(EI);
660 bool ReachesI = false;
661 while (!WorkList.empty()) {
662 const Instruction *V = WorkList.pop_back_val();
663 for (const User *U : V->users()) {
664 const auto *UI = cast<Instruction>(U);
665 if (UI == I) {
666 ReachesI = true;
667 continue;
668 }
669 if (UI->mayHaveSideEffects() || UI->isTerminator())
670 return false;
671 if (Visited.insert(UI).second)
672 WorkList.push_back(UI);
673 }
674 }
675 return ReachesI;
676}
677
678// Is this an intrinsic that cannot be speculated but also cannot trap?
680 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
681 return CI->isAssumeLikeIntrinsic();
682
683 return false;
684}
685
687 const Instruction *CxtI,
688 const DominatorTree *DT,
689 bool AllowEphemerals) {
690 // There are two restrictions on the use of an assume:
691 // 1. The assume must dominate the context (or the control flow must
692 // reach the assume whenever it reaches the context).
693 // 2. The context must not be in the assume's set of ephemeral values
694 // (otherwise we will use the assume to prove that the condition
695 // feeding the assume is trivially true, thus causing the removal of
696 // the assume).
697
698 if (Inv->getParent() == CxtI->getParent()) {
699 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
700 // in the BB.
701 if (Inv->comesBefore(CxtI))
702 return true;
703
704 // Don't let an assume affect itself - this would cause the problems
705 // `isEphemeralValueOf` is trying to prevent, and it would also make
706 // the loop below go out of bounds.
707 if (!AllowEphemerals && Inv == CxtI)
708 return false;
709
710 // The context comes first, but they're both in the same block.
711 // Make sure there is nothing in between that might interrupt
712 // the control flow, not even CxtI itself.
713 // We limit the scan distance between the assume and its context instruction
714 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
715 // it can be adjusted if needed (could be turned into a cl::opt).
716 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
718 return false;
719
720 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
721 }
722
723 // Inv and CxtI are in different blocks.
724 if (DT) {
725 if (DT->dominates(Inv, CxtI))
726 return true;
727 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
728 Inv->getParent()->isEntryBlock()) {
729 // We don't have a DT, but this trivially dominates.
730 return true;
731 }
732
733 return false;
734}
735
737 const Instruction *CtxI) {
738 // Helper to check if there are any calls in the range that may free memory.
739 unsigned NumChecked = 0;
740 auto hasNoFreeInRange = [&NumChecked](auto Range) {
741 for (const Instruction &I : Range) {
742 if (NumChecked++ > MaxInstrsToCheckForFree)
743 return false;
744
745 if (auto *CB = dyn_cast<CallBase>(&I)) {
746 if (!CB->hasFnAttr(Attribute::NoFree))
747 return false;
748 } else if (I.maySynchronize())
749 return false;
750 }
751 return true;
752 };
753
754 const BasicBlock *CtxBB = CtxI->getParent();
755 const BasicBlock *AssumeBB = Assume->getParent();
756 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
757 if (CtxBB == AssumeBB) {
758 // Same block case: check that Assume comes before CtxI.
759 if (Assume != CtxI && !Assume->comesBefore(CtxI))
760 return false;
761 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
762 }
763
764 // Handle chain of single-predecessor blocks.
765 const BasicBlock *CurBB = CtxBB;
766 while (true) {
767 if (CurBB == AssumeBB)
768 return hasNoFreeInRange(
769 make_range(Assume->getIterator(), AssumeBB->end()));
770
771 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
772 if (!PredBB)
773 return false;
774
775 if (!hasNoFreeInRange(make_range(CurBB->begin(),
776 CurBB == CtxBB ? CtxIter : CurBB->end())))
777 return false;
778 CurBB = PredBB;
779 }
780}
781
782// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
783// we still have enough information about `RHS` to conclude non-zero. For
784// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
785// so the extra compile time may not be worth it, but possibly a second API
786// should be created for use outside of loops.
787static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
788 // v u> y implies v != 0.
789 if (Pred == ICmpInst::ICMP_UGT)
790 return true;
791
792 // Special-case v != 0 to also handle v != null.
793 if (Pred == ICmpInst::ICMP_NE)
794 return match(RHS, m_Zero());
795
796 // All other predicates - rely on generic ConstantRange handling.
797 const APInt *C;
798 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
799 if (match(RHS, m_APInt(C))) {
801 return !TrueValues.contains(Zero);
802 }
803
805 if (VC == nullptr)
806 return false;
807
808 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
809 ++ElemIdx) {
811 Pred, VC->getElementAsAPInt(ElemIdx));
812 if (TrueValues.contains(Zero))
813 return false;
814 }
815 return true;
816}
817
818static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
819 Value *&ValOut, Instruction *&CtxIOut,
820 const PHINode **PhiOut = nullptr) {
821 ValOut = U->get();
822 if (ValOut == PHI)
823 return;
824 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
825 if (PhiOut)
826 *PhiOut = PHI;
827 Value *V;
828 // If the Use is a select of this phi, compute analysis on other arm to break
829 // recursion.
830 // TODO: Min/Max
831 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
832 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
833 ValOut = V;
834
835 // Same for select, if this phi is 2-operand phi, compute analysis on other
836 // incoming value to break recursion.
837 // TODO: We could handle any number of incoming edges as long as we only have
838 // two unique values.
839 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
840 IncPhi && IncPhi->getNumIncomingValues() == 2) {
841 for (int Idx = 0; Idx < 2; ++Idx) {
842 if (IncPhi->getIncomingValue(Idx) == PHI) {
843 ValOut = IncPhi->getIncomingValue(1 - Idx);
844 if (PhiOut)
845 *PhiOut = IncPhi;
846 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
847 break;
848 }
849 }
850 }
851}
852
853static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
854 // Use of assumptions is context-sensitive. If we don't have a context, we
855 // cannot use them!
856 if (!Q.AC || !Q.CxtI)
857 return false;
858
859 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
860 if (!Elem.Assume)
861 continue;
862
863 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
864 assert(I->getFunction() == Q.CxtI->getFunction() &&
865 "Got assumption for the wrong function!");
866
867 if (Elem.Index != AssumptionCache::ExprResultIdx) {
869 I->getOperandBundleAt(Elem.Index)) &&
871 return true;
872 continue;
873 }
874
875 // Warning: This loop can end up being somewhat performance sensitive.
876 // We're running this loop for once for each value queried resulting in a
877 // runtime of ~O(#assumes * #values).
878
879 Value *RHS;
880 CmpPredicate Pred;
881 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
882 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
883 continue;
884
886 return true;
887 }
888
889 return false;
890}
891
894 const SimplifyQuery &Q) {
895 if (RHS->getType()->isPointerTy()) {
896 // Handle comparison of pointer to null explicitly, as it will not be
897 // covered by the m_APInt() logic below.
898 if (LHS == V && match(RHS, m_Zero())) {
899 switch (Pred) {
901 Known.setAllZero();
902 break;
905 Known.makeNonNegative();
906 break;
908 Known.makeNegative();
909 break;
910 default:
911 break;
912 }
913 }
914 return;
915 }
916
917 unsigned BitWidth = Known.getBitWidth();
918 auto m_V =
920
921 Value *Y;
922 const APInt *Mask, *C;
923 if (!match(RHS, m_APInt(C)))
924 return;
925
926 uint64_t ShAmt;
927 switch (Pred) {
929 // assume(V = C)
930 if (match(LHS, m_V)) {
931 Known = Known.unionWith(KnownBits::makeConstant(*C));
932 // assume(V & Mask = C)
933 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
934 // For one bits in Mask, we can propagate bits from C to V.
935 Known.One |= *C;
936 if (match(Y, m_APInt(Mask)))
937 Known.Zero |= ~*C & *Mask;
938 // assume(V | Mask = C)
939 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
940 // For zero bits in Mask, we can propagate bits from C to V.
941 Known.Zero |= ~*C;
942 if (match(Y, m_APInt(Mask)))
943 Known.One |= *C & ~*Mask;
944 // assume(V << ShAmt = C)
945 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
946 ShAmt < BitWidth) {
947 // For those bits in C that are known, we can propagate them to known
948 // bits in V shifted to the right by ShAmt.
950 RHSKnown >>= ShAmt;
951 Known = Known.unionWith(RHSKnown);
952 // assume(V >> ShAmt = C)
953 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
954 ShAmt < BitWidth) {
955 // For those bits in RHS that are known, we can propagate them to known
956 // bits in V shifted to the right by C.
958 RHSKnown <<= ShAmt;
959 Known = Known.unionWith(RHSKnown);
960 }
961 break;
962 case ICmpInst::ICMP_NE: {
963 // assume (V & B != 0) where B is a power of 2
964 const APInt *BPow2;
965 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
966 Known.One |= *BPow2;
967 break;
968 }
969 default: {
970 const APInt *Offset = nullptr;
971 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
973 if (Offset)
974 LHSRange = LHSRange.sub(*Offset);
975 Known = Known.unionWith(LHSRange.toKnownBits());
976 }
977 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
978 // X & Y u> C -> X u> C && Y u> C
979 // X nuw- Y u> C -> X u> C
980 if (match(LHS, m_c_And(m_V, m_Value())) ||
981 match(LHS, m_NUWSub(m_V, m_Value())))
982 Known.One.setHighBits(
983 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
984 }
985 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
986 // X | Y u< C -> X u< C && Y u< C
987 // X nuw+ Y u< C -> X u< C && Y u< C
988 if (match(LHS, m_c_Or(m_V, m_Value())) ||
989 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
990 Known.Zero.setHighBits(
991 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
992 }
993 }
994 } break;
995 }
996}
997
998static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
1000 const SimplifyQuery &SQ, bool Invert) {
1001 ICmpInst::Predicate Pred =
1002 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1003 Value *LHS = Cmp->getOperand(0);
1004 Value *RHS = Cmp->getOperand(1);
1005
1006 // Handle icmp pred (trunc V), C
1007 if (match(LHS, m_Trunc(m_Specific(V)))) {
1008 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1009 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1011 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1012 else
1013 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1014 return;
1015 }
1016
1017 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1018}
1019
1021 KnownBits &Known, const SimplifyQuery &SQ,
1022 bool Invert, unsigned Depth) {
1023 Value *A, *B;
1026 KnownBits Known2(Known.getBitWidth());
1027 KnownBits Known3(Known.getBitWidth());
1028 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1029 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1030 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1032 Known2 = Known2.unionWith(Known3);
1033 else
1034 Known2 = Known2.intersectWith(Known3);
1035 Known = Known.unionWith(Known2);
1036 return;
1037 }
1038
1039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1040 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1041 return;
1042 }
1043
1044 if (match(Cond, m_Trunc(m_Specific(V)))) {
1045 KnownBits DstKnown(1);
1046 if (Invert) {
1047 DstKnown.setAllZero();
1048 } else {
1049 DstKnown.setAllOnes();
1050 }
1052 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1053 return;
1054 }
1055 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1056 return;
1057 }
1058
1060 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1061}
1062
1064 const SimplifyQuery &Q, unsigned Depth) {
1065 // Handle injected condition.
1066 if (Q.CC && Q.CC->AffectedValues.contains(V))
1068
1069 if (!Q.CxtI)
1070 return;
1071
1072 if (Q.DC && Q.DT) {
1073 // Handle dominating conditions.
1074 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1075 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1076 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1077 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1078 /*Invert*/ false, Depth);
1079
1080 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1081 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1082 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1083 /*Invert*/ true, Depth);
1084 }
1085
1086 if (Known.hasConflict())
1087 Known.resetAll();
1088 }
1089
1090 if (!Q.AC)
1091 return;
1092
1093 unsigned BitWidth = Known.getBitWidth();
1094
1095 // Note that the patterns below need to be kept in sync with the code
1096 // in AssumptionCache::updateAffectedValues.
1097
1098 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1099 if (!Elem.Assume)
1100 continue;
1101
1102 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1103 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1104 "Got assumption for the wrong function!");
1105
1106 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1107 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1108 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1109 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1110 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1112 Known.Zero |= (*Alignment - 1) & ~*Offset;
1113 Known.One |= (*Alignment - 1) & *Offset;
1114 }
1115 }
1116 continue;
1117 }
1118
1119 // Warning: This loop can end up being somewhat performance sensitive.
1120 // We're running this loop for once for each value queried resulting in a
1121 // runtime of ~O(#assumes * #values).
1122
1123 Value *Arg = I->getArgOperand(0);
1124
1125 if (Arg == V && isValidAssumeForContext(I, Q)) {
1126 assert(BitWidth == 1 && "assume operand is not i1?");
1127 (void)BitWidth;
1128 Known.setAllOnes();
1129 return;
1130 }
1131 if (match(Arg, m_Not(m_Specific(V))) &&
1133 assert(BitWidth == 1 && "assume operand is not i1?");
1134 (void)BitWidth;
1135 Known.setAllZero();
1136 return;
1137 }
1138 auto *Trunc = dyn_cast<TruncInst>(Arg);
1139 if (Trunc && Trunc->getOperand(0) == V &&
1141 if (Trunc->hasNoUnsignedWrap()) {
1143 return;
1144 }
1145 Known.One.setBit(0);
1146 return;
1147 }
1148
1149 // The remaining tests are all recursive, so bail out if we hit the limit.
1151 continue;
1152
1153 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1154 if (!Cmp)
1155 continue;
1156
1157 if (!isValidAssumeForContext(I, Q))
1158 continue;
1159
1160 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1161 }
1162
1163 // Conflicting assumption: Undefined behavior will occur on this execution
1164 // path.
1165 if (Known.hasConflict())
1166 Known.resetAll();
1167}
1168
1169/// Compute known bits from a shift operator, including those with a
1170/// non-constant shift amount. Known is the output of this function. Known2 is a
1171/// pre-allocated temporary with the same bit width as Known and on return
1172/// contains the known bit of the shift value source. KF is an
1173/// operator-specific function that, given the known-bits and a shift amount,
1174/// compute the implied known-bits of the shift operator's result respectively
1175/// for that shift amount. The results from calling KF are conservatively
1176/// combined for all permitted shift amounts.
1178 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1179 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1180 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1181 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1182 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1183 // To limit compile-time impact, only query isKnownNonZero() if we know at
1184 // least something about the shift amount.
1185 bool ShAmtNonZero =
1186 Known.isNonZero() ||
1187 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1188 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1189 Known = KF(Known2, Known, ShAmtNonZero);
1190}
1191
1192static KnownBits
1193getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1194 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1195 const SimplifyQuery &Q, unsigned Depth) {
1196 unsigned BitWidth = KnownLHS.getBitWidth();
1197 KnownBits KnownOut(BitWidth);
1198 bool IsAnd = false;
1199 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1200 Value *X = nullptr, *Y = nullptr;
1201
1202 switch (I->getOpcode()) {
1203 case Instruction::And:
1204 KnownOut = KnownLHS & KnownRHS;
1205 IsAnd = true;
1206 // and(x, -x) is common idioms that will clear all but lowest set
1207 // bit. If we have a single known bit in x, we can clear all bits
1208 // above it.
1209 // TODO: instcombine often reassociates independent `and` which can hide
1210 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1211 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1212 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1213 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1214 KnownOut = KnownLHS.blsi();
1215 else
1216 KnownOut = KnownRHS.blsi();
1217 }
1218 break;
1219 case Instruction::Or:
1220 KnownOut = KnownLHS | KnownRHS;
1221 break;
1222 case Instruction::Xor:
1223 KnownOut = KnownLHS ^ KnownRHS;
1224 // xor(x, x-1) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1228 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1229 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1230 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1231 if (HasKnownOne &&
1233 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1234 KnownOut = XBits.blsmsk();
1235 }
1236 break;
1237 default:
1238 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1239 }
1240
1241 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1242 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1243 // here we handle the more general case of adding any odd number by
1244 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1245 // TODO: This could be generalized to clearing any bit set in y where the
1246 // following bit is known to be unset in y.
1247 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1251 KnownBits KnownY(BitWidth);
1252 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1253 if (KnownY.countMinTrailingOnes() > 0) {
1254 if (IsAnd)
1255 KnownOut.Zero.setBit(0);
1256 else
1257 KnownOut.One.setBit(0);
1258 }
1259 }
1260 return KnownOut;
1261}
1262
1264 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1265 unsigned Depth,
1266 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1267 KnownBitsFunc) {
1268 APInt DemandedEltsLHS, DemandedEltsRHS;
1270 DemandedElts, DemandedEltsLHS,
1271 DemandedEltsRHS);
1272
1273 const auto ComputeForSingleOpFunc =
1274 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1275 return KnownBitsFunc(
1276 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1277 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1278 };
1279
1280 if (DemandedEltsRHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1282 if (DemandedEltsLHS.isZero())
1283 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1284
1285 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1286 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1287}
1288
1289// Public so this can be used in `SimplifyDemandedUseBits`.
1291 const KnownBits &KnownLHS,
1292 const KnownBits &KnownRHS,
1293 const SimplifyQuery &SQ,
1294 unsigned Depth) {
1295 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1296 APInt DemandedElts =
1297 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1298
1299 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1300 Depth);
1301}
1302
1304 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1305 // Without vscale_range, we only know that vscale is non-zero.
1306 if (!Attr.isValid())
1308
1309 unsigned AttrMin = Attr.getVScaleRangeMin();
1310 // Minimum is larger than vscale width, result is always poison.
1311 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1312 return ConstantRange::getEmpty(BitWidth);
1313
1314 APInt Min(BitWidth, AttrMin);
1315 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1316 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1318
1319 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1320}
1321
1323 Value *Arm, bool Invert,
1324 const SimplifyQuery &Q, unsigned Depth) {
1325 // If we have a constant arm, we are done.
1326 if (Known.isConstant())
1327 return;
1328
1329 // See what condition implies about the bits of the select arm.
1330 KnownBits CondRes(Known.getBitWidth());
1331 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1332 // If we don't get any information from the condition, no reason to
1333 // proceed.
1334 if (CondRes.isUnknown())
1335 return;
1336
1337 // We can have conflict if the condition is dead. I.e if we have
1338 // (x | 64) < 32 ? (x | 64) : y
1339 // we will have conflict at bit 6 from the condition/the `or`.
1340 // In that case just return. Its not particularly important
1341 // what we do, as this select is going to be simplified soon.
1342 CondRes = CondRes.unionWith(Known);
1343 if (CondRes.hasConflict())
1344 return;
1345
1346 // Finally make sure the information we found is valid. This is relatively
1347 // expensive so it's left for the very end.
1348 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1349 return;
1350
1351 // Finally, we know we get information from the condition and its valid,
1352 // so return it.
1353 Known = std::move(CondRes);
1354}
1355
1356// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1357// Returns the input and lower/upper bounds.
1358static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1359 const APInt *&CLow, const APInt *&CHigh) {
1361 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1362 "Input should be a Select!");
1363
1364 const Value *LHS = nullptr, *RHS = nullptr;
1366 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1367 return false;
1368
1369 if (!match(RHS, m_APInt(CLow)))
1370 return false;
1371
1372 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1374 if (getInverseMinMaxFlavor(SPF) != SPF2)
1375 return false;
1376
1377 if (!match(RHS2, m_APInt(CHigh)))
1378 return false;
1379
1380 if (SPF == SPF_SMIN)
1381 std::swap(CLow, CHigh);
1382
1383 In = LHS2;
1384 return CLow->sle(*CHigh);
1385}
1386
1388 const APInt *&CLow,
1389 const APInt *&CHigh) {
1390 assert((II->getIntrinsicID() == Intrinsic::smin ||
1391 II->getIntrinsicID() == Intrinsic::smax) &&
1392 "Must be smin/smax");
1393
1394 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1395 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1396 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1397 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1398 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1399 return false;
1400
1401 if (II->getIntrinsicID() == Intrinsic::smin)
1402 std::swap(CLow, CHigh);
1403 return CLow->sle(*CHigh);
1404}
1405
1407 KnownBits &Known) {
1408 const APInt *CLow, *CHigh;
1409 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1410 Known = Known.unionWith(
1411 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1412}
1413
1415 const APInt &DemandedElts,
1417 const SimplifyQuery &Q,
1418 unsigned Depth) {
1419 unsigned BitWidth = Known.getBitWidth();
1420
1421 KnownBits Known2(BitWidth);
1422 switch (I->getOpcode()) {
1423 default: break;
1424 case Instruction::Load:
1425 if (MDNode *MD =
1426 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1428 break;
1429 case Instruction::And:
1430 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1431 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1432
1433 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1434 break;
1435 case Instruction::Or:
1436 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1437 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1438
1439 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1440 break;
1441 case Instruction::Xor:
1442 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1443 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1444
1445 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1446 break;
1447 case Instruction::Mul: {
1450 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1451 DemandedElts, Known, Known2, Q, Depth);
1452 break;
1453 }
1454 case Instruction::UDiv: {
1455 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1456 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1457 Known =
1459 break;
1460 }
1461 case Instruction::SDiv: {
1462 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1463 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1464 Known =
1466 break;
1467 }
1468 case Instruction::Select: {
1469 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1470 KnownBits Res(Known.getBitWidth());
1471 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1472 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1473 return Res;
1474 };
1475 // Only known if known in both the LHS and RHS.
1476 Known =
1477 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1478 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1479 break;
1480 }
1481 case Instruction::FPTrunc:
1482 case Instruction::FPExt:
1483 case Instruction::FPToUI:
1484 case Instruction::FPToSI:
1485 case Instruction::SIToFP:
1486 case Instruction::UIToFP:
1487 break; // Can't work with floating point.
1488 case Instruction::PtrToInt:
1489 case Instruction::PtrToAddr:
1490 case Instruction::IntToPtr:
1491 // Fall through and handle them the same as zext/trunc.
1492 [[fallthrough]];
1493 case Instruction::ZExt:
1494 case Instruction::Trunc: {
1495 Type *SrcTy = I->getOperand(0)->getType();
1496
1497 unsigned SrcBitWidth;
1498 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1499 // which fall through here.
1500 Type *ScalarTy = SrcTy->getScalarType();
1501 SrcBitWidth = ScalarTy->isPointerTy() ?
1502 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1503 Q.DL.getTypeSizeInBits(ScalarTy);
1504
1505 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1506 Known = Known.anyextOrTrunc(SrcBitWidth);
1507 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1508 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1509 Inst && Inst->hasNonNeg() && !Known.isNegative())
1510 Known.makeNonNegative();
1511 Known = Known.zextOrTrunc(BitWidth);
1512 break;
1513 }
1514 case Instruction::BitCast: {
1515 Type *SrcTy = I->getOperand(0)->getType();
1516 if (SrcTy->isIntOrPtrTy() &&
1517 // TODO: For now, not handling conversions like:
1518 // (bitcast i64 %x to <2 x i32>)
1519 !I->getType()->isVectorTy()) {
1520 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1521 break;
1522 }
1523
1524 const Value *V;
1525 // Handle bitcast from floating point to integer.
1526 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1527 V->getType()->isFPOrFPVectorTy()) {
1528 Type *FPType = V->getType()->getScalarType();
1529 KnownFPClass Result =
1530 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1531
1532 Known = Result.toKnownBits(FPType->getFltSemantics());
1533
1534 break;
1535 }
1536
1537 // Handle cast from vector integer type to scalar or vector integer.
1538 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1539 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1540 !I->getType()->isIntOrIntVectorTy() ||
1541 isa<ScalableVectorType>(I->getType()))
1542 break;
1543
1544 unsigned NumElts = DemandedElts.getBitWidth();
1545 bool IsLE = Q.DL.isLittleEndian();
1546 // Look through a cast from narrow vector elements to wider type.
1547 // Examples: v4i32 -> v2i64, v3i8 -> v24
1548 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1549 if (BitWidth % SubBitWidth == 0) {
1550 // Known bits are automatically intersected across demanded elements of a
1551 // vector. So for example, if a bit is computed as known zero, it must be
1552 // zero across all demanded elements of the vector.
1553 //
1554 // For this bitcast, each demanded element of the output is sub-divided
1555 // across a set of smaller vector elements in the source vector. To get
1556 // the known bits for an entire element of the output, compute the known
1557 // bits for each sub-element sequentially. This is done by shifting the
1558 // one-set-bit demanded elements parameter across the sub-elements for
1559 // consecutive calls to computeKnownBits. We are using the demanded
1560 // elements parameter as a mask operator.
1561 //
1562 // The known bits of each sub-element are then inserted into place
1563 // (dependent on endian) to form the full result of known bits.
1564 unsigned SubScale = BitWidth / SubBitWidth;
1565 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1566 for (unsigned i = 0; i != NumElts; ++i) {
1567 if (DemandedElts[i])
1568 SubDemandedElts.setBit(i * SubScale);
1569 }
1570
1571 KnownBits KnownSrc(SubBitWidth);
1572 for (unsigned i = 0; i != SubScale; ++i) {
1573 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1574 Depth + 1);
1575 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1576 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1577 }
1578 }
1579 // Look through a cast from wider vector elements to narrow type.
1580 // Examples: v2i64 -> v4i32
1581 if (SubBitWidth % BitWidth == 0) {
1582 unsigned SubScale = SubBitWidth / BitWidth;
1583 KnownBits KnownSrc(SubBitWidth);
1584 APInt SubDemandedElts =
1585 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1586 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1587 Depth + 1);
1588
1589 Known.setAllConflict();
1590 for (unsigned i = 0; i != NumElts; ++i) {
1591 if (DemandedElts[i]) {
1592 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1593 unsigned Offset = (Shifts % SubScale) * BitWidth;
1594 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1595 if (Known.isUnknown())
1596 break;
1597 }
1598 }
1599 }
1600 break;
1601 }
1602 case Instruction::SExt: {
1603 // Compute the bits in the result that are not present in the input.
1604 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1605
1606 Known = Known.trunc(SrcBitWidth);
1607 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1608 // If the sign bit of the input is known set or clear, then we know the
1609 // top bits of the result.
1610 Known = Known.sext(BitWidth);
1611 break;
1612 }
1613 case Instruction::Shl: {
1616 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1617 bool ShAmtNonZero) {
1618 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1619 };
1620 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1621 KF);
1622 // Trailing zeros of a right-shifted constant never decrease.
1623 const APInt *C;
1624 if (match(I->getOperand(0), m_APInt(C)))
1625 Known.Zero.setLowBits(C->countr_zero());
1626
1627 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1628 // lands at bit Y, when BitWidth is a power of 2.
1629 const APInt *YC;
1630 Value *X = I->getOperand(0);
1631 if (isPowerOf2_32(BitWidth) &&
1632 match(I->getOperand(1),
1634 m_SpecificInt(BitWidth - 1)))) &&
1635 YC->ult(BitWidth - 1)) {
1636 unsigned Y = YC->getZExtValue();
1637 Known.One.setBit(Y);
1638 Known.Zero.setBitsFrom(Y + 1);
1639 }
1640 break;
1641 }
1642 case Instruction::LShr: {
1643 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1644 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1645 bool ShAmtNonZero) {
1646 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1647 };
1648 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1649 KF);
1650 // Leading zeros of a left-shifted constant never decrease.
1651 const APInt *C;
1652 if (match(I->getOperand(0), m_APInt(C)))
1653 Known.Zero.setHighBits(C->countl_zero());
1654 break;
1655 }
1656 case Instruction::AShr: {
1657 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1658 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1659 bool ShAmtNonZero) {
1660 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1661 };
1662 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1663 KF);
1664 break;
1665 }
1666 case Instruction::Sub: {
1669 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1670 DemandedElts, Known, Known2, Q, Depth);
1671 break;
1672 }
1673 case Instruction::Add: {
1676 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1677 DemandedElts, Known, Known2, Q, Depth);
1678 break;
1679 }
1680 case Instruction::SRem:
1681 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1682 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1683 Known = KnownBits::srem(Known, Known2);
1684 break;
1685
1686 case Instruction::URem:
1687 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1688 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1689 Known = KnownBits::urem(Known, Known2);
1690 break;
1691 case Instruction::Alloca:
1692 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1693 break;
1694 case Instruction::GetElementPtr: {
1695 // Analyze all of the subscripts of this getelementptr instruction
1696 // to determine if we can prove known low zero bits.
1697 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1698 // Accumulate the constant indices in a separate variable
1699 // to minimize the number of calls to computeForAddSub.
1700 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1701 APInt AccConstIndices(IndexWidth, 0);
1702
1703 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1704 if (IndexWidth == BitWidth) {
1705 // Note that inbounds does *not* guarantee nsw for the addition, as only
1706 // the offset is signed, while the base address is unsigned.
1707 Known = KnownBits::add(Known, IndexBits);
1708 } else {
1709 // If the index width is smaller than the pointer width, only add the
1710 // value to the low bits.
1711 assert(IndexWidth < BitWidth &&
1712 "Index width can't be larger than pointer width");
1713 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1714 }
1715 };
1716
1718 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1719 // TrailZ can only become smaller, short-circuit if we hit zero.
1720 if (Known.isUnknown())
1721 break;
1722
1723 Value *Index = I->getOperand(i);
1724
1725 // Handle case when index is zero.
1726 Constant *CIndex = dyn_cast<Constant>(Index);
1727 if (CIndex && CIndex->isNullValue())
1728 continue;
1729
1730 if (StructType *STy = GTI.getStructTypeOrNull()) {
1731 // Handle struct member offset arithmetic.
1732
1733 assert(CIndex &&
1734 "Access to structure field must be known at compile time");
1735
1736 if (CIndex->getType()->isVectorTy())
1737 Index = CIndex->getSplatValue();
1738
1739 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1740 const StructLayout *SL = Q.DL.getStructLayout(STy);
1741 uint64_t Offset = SL->getElementOffset(Idx);
1742 AccConstIndices += Offset;
1743 continue;
1744 }
1745
1746 // Handle array index arithmetic.
1747 Type *IndexedTy = GTI.getIndexedType();
1748 if (!IndexedTy->isSized()) {
1749 Known.resetAll();
1750 break;
1751 }
1752
1753 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1754 uint64_t StrideInBytes = Stride.getKnownMinValue();
1755 if (!Stride.isScalable()) {
1756 // Fast path for constant offset.
1757 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1758 AccConstIndices +=
1759 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1760 continue;
1761 }
1762 }
1763
1764 KnownBits IndexBits =
1765 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1766 KnownBits ScalingFactor(IndexWidth);
1767 // Multiply by current sizeof type.
1768 // &A[i] == A + i * sizeof(*A[i]).
1769 if (Stride.isScalable()) {
1770 // For scalable types the only thing we know about sizeof is
1771 // that this is a multiple of the minimum size.
1772 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1773 } else {
1774 ScalingFactor =
1775 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1776 }
1777 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1778 }
1779 if (!Known.isUnknown() && !AccConstIndices.isZero())
1780 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1781 break;
1782 }
1783 case Instruction::PHI: {
1784 const PHINode *P = cast<PHINode>(I);
1785 BinaryOperator *BO = nullptr;
1786 Value *R = nullptr, *L = nullptr;
1787 if (matchSimpleRecurrence(P, BO, R, L)) {
1788 // Handle the case of a simple two-predecessor recurrence PHI.
1789 // There's a lot more that could theoretically be done here, but
1790 // this is sufficient to catch some interesting cases.
1791 unsigned Opcode = BO->getOpcode();
1792
1793 switch (Opcode) {
1794 // If this is a shift recurrence, we know the bits being shifted in. We
1795 // can combine that with information about the start value of the
1796 // recurrence to conclude facts about the result. If this is a udiv
1797 // recurrence, we know that the result can never exceed either the
1798 // numerator or the start value, whichever is greater.
1799 case Instruction::LShr:
1800 case Instruction::AShr:
1801 case Instruction::Shl:
1802 case Instruction::UDiv:
1803 if (BO->getOperand(0) != I)
1804 break;
1805 [[fallthrough]];
1806
1807 // For a urem recurrence, the result can never exceed the start value. The
1808 // phi could either be the numerator or the denominator.
1809 case Instruction::URem: {
1810 // We have matched a recurrence of the form:
1811 // %iv = [R, %entry], [%iv.next, %backedge]
1812 // %iv.next = shift_op %iv, L
1813
1814 // Recurse with the phi context to avoid concern about whether facts
1815 // inferred hold at original context instruction. TODO: It may be
1816 // correct to use the original context. IF warranted, explore and
1817 // add sufficient tests to cover.
1819 RecQ.CxtI = P;
1820 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1821 switch (Opcode) {
1822 case Instruction::Shl:
1823 // A shl recurrence will only increase the tailing zeros
1824 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1825 break;
1826 case Instruction::LShr:
1827 case Instruction::UDiv:
1828 case Instruction::URem:
1829 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1830 // the start value.
1831 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1832 break;
1833 case Instruction::AShr:
1834 // An ashr recurrence will extend the initial sign bit
1835 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1836 Known.One.setHighBits(Known2.countMinLeadingOnes());
1837 break;
1838 }
1839 break;
1840 }
1841
1842 // Check for operations that have the property that if
1843 // both their operands have low zero bits, the result
1844 // will have low zero bits.
1845 case Instruction::Add:
1846 case Instruction::Sub:
1847 case Instruction::And:
1848 case Instruction::Or:
1849 case Instruction::Mul: {
1850 // Change the context instruction to the "edge" that flows into the
1851 // phi. This is important because that is where the value is actually
1852 // "evaluated" even though it is used later somewhere else. (see also
1853 // D69571).
1855
1856 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1857 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1858 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1859
1860 // Ok, we have a PHI of the form L op= R. Check for low
1861 // zero bits.
1862 RecQ.CxtI = RInst;
1863 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1864
1865 // We need to take the minimum number of known bits
1866 KnownBits Known3(BitWidth);
1867 RecQ.CxtI = LInst;
1868 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1869
1870 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1871 Known3.countMinTrailingZeros()));
1872
1873 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1874 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1875 break;
1876
1877 switch (Opcode) {
1878 // If initial value of recurrence is nonnegative, and we are adding
1879 // a nonnegative number with nsw, the result can only be nonnegative
1880 // or poison value regardless of the number of times we execute the
1881 // add in phi recurrence. If initial value is negative and we are
1882 // adding a negative number with nsw, the result can only be
1883 // negative or poison value. Similar arguments apply to sub and mul.
1884 //
1885 // (add non-negative, non-negative) --> non-negative
1886 // (add negative, negative) --> negative
1887 case Instruction::Add: {
1888 if (Known2.isNonNegative() && Known3.isNonNegative())
1889 Known.makeNonNegative();
1890 else if (Known2.isNegative() && Known3.isNegative())
1891 Known.makeNegative();
1892 break;
1893 }
1894
1895 // (sub nsw non-negative, negative) --> non-negative
1896 // (sub nsw negative, non-negative) --> negative
1897 case Instruction::Sub: {
1898 if (BO->getOperand(0) != I)
1899 break;
1900 if (Known2.isNonNegative() && Known3.isNegative())
1901 Known.makeNonNegative();
1902 else if (Known2.isNegative() && Known3.isNonNegative())
1903 Known.makeNegative();
1904 break;
1905 }
1906
1907 // (mul nsw non-negative, non-negative) --> non-negative
1908 case Instruction::Mul:
1909 if (Known2.isNonNegative() && Known3.isNonNegative())
1910 Known.makeNonNegative();
1911 break;
1912
1913 default:
1914 break;
1915 }
1916 break;
1917 }
1918
1919 default:
1920 break;
1921 }
1922 }
1923
1924 // Unreachable blocks may have zero-operand PHI nodes.
1925 if (P->getNumIncomingValues() == 0)
1926 break;
1927
1928 // Otherwise take the unions of the known bit sets of the operands,
1929 // taking conservative care to avoid excessive recursion.
1930 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1931 // Skip if every incoming value references to ourself.
1932 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1933 break;
1934
1935 Known.setAllConflict();
1936 for (const Use &U : P->operands()) {
1937 Value *IncValue;
1938 const PHINode *CxtPhi;
1939 Instruction *CxtI;
1940 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1941 // Skip direct self references.
1942 if (IncValue == P)
1943 continue;
1944
1945 // Change the context instruction to the "edge" that flows into the
1946 // phi. This is important because that is where the value is actually
1947 // "evaluated" even though it is used later somewhere else. (see also
1948 // D69571).
1950
1951 Known2 = KnownBits(BitWidth);
1952
1953 // Recurse, but cap the recursion to one level, because we don't
1954 // want to waste time spinning around in loops.
1955 // TODO: See if we can base recursion limiter on number of incoming phi
1956 // edges so we don't overly clamp analysis.
1957 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1959
1960 // See if we can further use a conditional branch into the phi
1961 // to help us determine the range of the value.
1962 if (!Known2.isConstant()) {
1963 CmpPredicate Pred;
1964 const APInt *RHSC;
1965 BasicBlock *TrueSucc, *FalseSucc;
1966 // TODO: Use RHS Value and compute range from its known bits.
1967 if (match(RecQ.CxtI,
1968 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1969 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1970 // Check for cases of duplicate successors.
1971 if ((TrueSucc == CxtPhi->getParent()) !=
1972 (FalseSucc == CxtPhi->getParent())) {
1973 // If we're using the false successor, invert the predicate.
1974 if (FalseSucc == CxtPhi->getParent())
1975 Pred = CmpInst::getInversePredicate(Pred);
1976 // Get the knownbits implied by the incoming phi condition.
1977 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
1978 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
1979 // We can have conflicts here if we are analyzing deadcode (its
1980 // impossible for us reach this BB based the icmp).
1981 if (KnownUnion.hasConflict()) {
1982 // No reason to continue analyzing in a known dead region, so
1983 // just resetAll and break. This will cause us to also exit the
1984 // outer loop.
1985 Known.resetAll();
1986 break;
1987 }
1988 Known2 = KnownUnion;
1989 }
1990 }
1991 }
1992
1993 Known = Known.intersectWith(Known2);
1994 // If all bits have been ruled out, there's no need to check
1995 // more operands.
1996 if (Known.isUnknown())
1997 break;
1998 }
1999 }
2000 break;
2001 }
2002 case Instruction::Call:
2003 case Instruction::Invoke: {
2004 // If range metadata is attached to this call, set known bits from that,
2005 // and then intersect with known bits based on other properties of the
2006 // function.
2007 if (MDNode *MD =
2008 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2010
2011 const auto *CB = cast<CallBase>(I);
2012
2013 if (std::optional<ConstantRange> Range = CB->getRange())
2014 Known = Known.unionWith(Range->toKnownBits());
2015
2016 if (const Value *RV = CB->getReturnedArgOperand()) {
2017 if (RV->getType() == I->getType()) {
2018 computeKnownBits(RV, Known2, Q, Depth + 1);
2019 Known = Known.unionWith(Known2);
2020 // If the function doesn't return properly for all input values
2021 // (e.g. unreachable exits) then there might be conflicts between the
2022 // argument value and the range metadata. Simply discard the known bits
2023 // in case of conflicts.
2024 if (Known.hasConflict())
2025 Known.resetAll();
2026 }
2027 }
2028 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2029 switch (II->getIntrinsicID()) {
2030 default:
2031 break;
2032 case Intrinsic::abs: {
2033 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2034 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2035 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2036 break;
2037 }
2038 case Intrinsic::bitreverse:
2039 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2040 Known = Known.unionWith(Known2.reverseBits());
2041 break;
2042 case Intrinsic::bswap:
2043 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2044 Known = Known.unionWith(Known2.byteSwap());
2045 break;
2046 case Intrinsic::ctlz: {
2047 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2048 // If we have a known 1, its position is our upper bound.
2049 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2050 // If this call is poison for 0 input, the result will be less than 2^n.
2051 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2052 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2053 unsigned LowBits = llvm::bit_width(PossibleLZ);
2054 Known.Zero.setBitsFrom(LowBits);
2055 break;
2056 }
2057 case Intrinsic::cttz: {
2058 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2059 // If we have a known 1, its position is our upper bound.
2060 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2061 // If this call is poison for 0 input, the result will be less than 2^n.
2062 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2063 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2064 unsigned LowBits = llvm::bit_width(PossibleTZ);
2065 Known.Zero.setBitsFrom(LowBits);
2066 break;
2067 }
2068 case Intrinsic::ctpop: {
2069 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2070 // We can bound the space the count needs. Also, bits known to be zero
2071 // can't contribute to the population.
2072 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2073 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2074 Known.Zero.setBitsFrom(LowBits);
2075 // TODO: we could bound KnownOne using the lower bound on the number
2076 // of bits which might be set provided by popcnt KnownOne2.
2077 break;
2078 }
2079 case Intrinsic::fshr:
2080 case Intrinsic::fshl: {
2081 const APInt *SA;
2082 if (!match(I->getOperand(2), m_APInt(SA)))
2083 break;
2084
2085 KnownBits Known3(BitWidth);
2086 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2087 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2088 Known = II->getIntrinsicID() == Intrinsic::fshl
2089 ? KnownBits::fshl(Known2, Known3, *SA)
2090 : KnownBits::fshr(Known2, Known3, *SA);
2091 break;
2092 }
2093 case Intrinsic::clmul:
2094 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2095 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2096 Known = KnownBits::clmul(Known, Known2);
2097 break;
2098 case Intrinsic::pext:
2099 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2100 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2101 Known = KnownBits::pext(Known, Known2);
2102 break;
2103 case Intrinsic::pdep:
2104 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2105 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2106 Known = KnownBits::pdep(Known, Known2);
2107 break;
2108 case Intrinsic::uadd_sat:
2109 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2110 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2111 Known = KnownBits::uadd_sat(Known, Known2);
2112 break;
2113 case Intrinsic::usub_sat:
2114 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2115 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2116 Known = KnownBits::usub_sat(Known, Known2);
2117 break;
2118 case Intrinsic::sadd_sat:
2119 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2120 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2121 Known = KnownBits::sadd_sat(Known, Known2);
2122 break;
2123 case Intrinsic::ssub_sat:
2124 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2125 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2126 Known = KnownBits::ssub_sat(Known, Known2);
2127 break;
2128 // Vec reverse preserves bits from input vec.
2129 case Intrinsic::vector_reverse:
2130 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2131 Depth + 1);
2132 break;
2133 // for min/max/and/or reduce, any bit common to each element in the
2134 // input vec is set in the output.
2135 case Intrinsic::vector_reduce_and:
2136 case Intrinsic::vector_reduce_or:
2137 case Intrinsic::vector_reduce_umax:
2138 case Intrinsic::vector_reduce_umin:
2139 case Intrinsic::vector_reduce_smax:
2140 case Intrinsic::vector_reduce_smin:
2141 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2142 break;
2143 case Intrinsic::vector_reduce_xor: {
2144 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2145 // The zeros common to all vecs are zero in the output.
2146 // If the number of elements is odd, then the common ones remain. If the
2147 // number of elements is even, then the common ones becomes zeros.
2148 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2149 // Even, so the ones become zeros.
2150 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2151 if (EvenCnt)
2152 Known.Zero |= Known.One;
2153 // Maybe even element count so need to clear ones.
2154 if (VecTy->isScalableTy() || EvenCnt)
2155 Known.One.clearAllBits();
2156 break;
2157 }
2158 case Intrinsic::vector_reduce_add: {
2159 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2160 if (!VecTy)
2161 break;
2162 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2163 Known = Known.reduceAdd(VecTy->getNumElements());
2164 break;
2165 }
2166 case Intrinsic::umin:
2167 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2168 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2169 Known = KnownBits::umin(Known, Known2);
2170 break;
2171 case Intrinsic::umax:
2172 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2173 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2174 Known = KnownBits::umax(Known, Known2);
2175 break;
2176 case Intrinsic::smin:
2177 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2178 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2179 Known = KnownBits::smin(Known, Known2);
2181 break;
2182 case Intrinsic::smax:
2183 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2184 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2185 Known = KnownBits::smax(Known, Known2);
2187 break;
2188 case Intrinsic::ptrmask: {
2189 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2190
2191 const Value *Mask = I->getOperand(1);
2192 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2193 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2194 // TODO: 1-extend would be more precise.
2195 Known &= Known2.anyextOrTrunc(BitWidth);
2196 break;
2197 }
2198 case Intrinsic::x86_sse2_pmulh_w:
2199 case Intrinsic::x86_avx2_pmulh_w:
2200 case Intrinsic::x86_avx512_pmulh_w_512:
2201 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2202 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2203 Known = KnownBits::mulhs(Known, Known2);
2204 break;
2205 case Intrinsic::x86_sse2_pmulhu_w:
2206 case Intrinsic::x86_avx2_pmulhu_w:
2207 case Intrinsic::x86_avx512_pmulhu_w_512:
2208 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2209 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2210 Known = KnownBits::mulhu(Known, Known2);
2211 break;
2212 case Intrinsic::x86_sse42_crc32_64_64:
2213 Known.Zero.setBitsFrom(32);
2214 break;
2215 case Intrinsic::x86_ssse3_phadd_d_128:
2216 case Intrinsic::x86_ssse3_phadd_w_128:
2217 case Intrinsic::x86_avx2_phadd_d:
2218 case Intrinsic::x86_avx2_phadd_w: {
2220 I, DemandedElts, Q, Depth,
2221 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2222 return KnownBits::add(KnownLHS, KnownRHS);
2223 });
2224 break;
2225 }
2226 case Intrinsic::x86_ssse3_phadd_sw_128:
2227 case Intrinsic::x86_avx2_phadd_sw: {
2229 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2230 break;
2231 }
2232 case Intrinsic::x86_ssse3_phsub_d_128:
2233 case Intrinsic::x86_ssse3_phsub_w_128:
2234 case Intrinsic::x86_avx2_phsub_d:
2235 case Intrinsic::x86_avx2_phsub_w: {
2237 I, DemandedElts, Q, Depth,
2238 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2239 return KnownBits::sub(KnownLHS, KnownRHS);
2240 });
2241 break;
2242 }
2243 case Intrinsic::x86_ssse3_phsub_sw_128:
2244 case Intrinsic::x86_avx2_phsub_sw: {
2246 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2247 break;
2248 }
2249 case Intrinsic::riscv_vsetvli:
2250 case Intrinsic::riscv_vsetvlimax: {
2251 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2252 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2254 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2255 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2256 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2257 uint64_t MaxVLEN =
2258 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2259 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2260
2261 // Result of vsetvli must be not larger than AVL.
2262 if (HasAVL)
2263 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2264 MaxVL = std::min(MaxVL, CI->getZExtValue());
2265
2266 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2267 if (BitWidth > KnownZeroFirstBit)
2268 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2269 break;
2270 }
2271 case Intrinsic::amdgcn_mbcnt_hi:
2272 case Intrinsic::amdgcn_mbcnt_lo: {
2273 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2274 // most 31 + src1.
2275 Known.Zero.setBitsFrom(
2276 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2277 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2278 Known = KnownBits::add(Known, Known2);
2279 break;
2280 }
2281 case Intrinsic::vscale: {
2282 if (!II->getParent() || !II->getFunction())
2283 break;
2284
2285 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2286 break;
2287 }
2288 case Intrinsic::stepvector: {
2289 auto *VecTy = cast<VectorType>(II->getType());
2290 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2291 if (!isUIntN(BitWidth, MinNumElts))
2292 break;
2293
2294 bool Overflow = false;
2295 APInt MaxNumElts(BitWidth, MinNumElts);
2296 if (VecTy->isScalableTy()) {
2297 if (!II->getParent() || !II->getFunction())
2298 break;
2299 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2301 .umul_ov(MaxNumElts, Overflow);
2302 }
2303
2304 // Give up if the lane count could wrap. Stepvector truncates lane
2305 // indices that do not fit in the element type.
2306 if (Overflow)
2307 break;
2308
2309 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2310 break;
2311 }
2312 }
2313 }
2314 break;
2315 }
2316 case Instruction::ShuffleVector: {
2317 if (auto *Splat = getSplatValue(I)) {
2319 break;
2320 }
2321
2322 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2323 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2324 if (!Shuf) {
2325 Known.resetAll();
2326 return;
2327 }
2328 // For undef elements, we don't know anything about the common state of
2329 // the shuffle result.
2330 APInt DemandedLHS, DemandedRHS;
2331 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2332 Known.resetAll();
2333 return;
2334 }
2335 Known.setAllConflict();
2336 if (!!DemandedLHS) {
2337 const Value *LHS = Shuf->getOperand(0);
2338 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2339 // If we don't know any bits, early out.
2340 if (Known.isUnknown())
2341 break;
2342 }
2343 if (!!DemandedRHS) {
2344 const Value *RHS = Shuf->getOperand(1);
2345 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2346 Known = Known.intersectWith(Known2);
2347 }
2348 break;
2349 }
2350 case Instruction::InsertElement: {
2351 if (isa<ScalableVectorType>(I->getType())) {
2352 Known.resetAll();
2353 return;
2354 }
2355 const Value *Vec = I->getOperand(0);
2356 const Value *Elt = I->getOperand(1);
2357 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2358 unsigned NumElts = DemandedElts.getBitWidth();
2359 APInt DemandedVecElts = DemandedElts;
2360 bool NeedsElt = true;
2361 // If we know the index we are inserting too, clear it from Vec check.
2362 if (CIdx && CIdx->getValue().ult(NumElts)) {
2363 DemandedVecElts.clearBit(CIdx->getZExtValue());
2364 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2365 }
2366
2367 Known.setAllConflict();
2368 if (NeedsElt) {
2369 computeKnownBits(Elt, Known, Q, Depth + 1);
2370 // If we don't know any bits, early out.
2371 if (Known.isUnknown())
2372 break;
2373 }
2374
2375 if (!DemandedVecElts.isZero()) {
2376 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2377 Known = Known.intersectWith(Known2);
2378 }
2379 break;
2380 }
2381 case Instruction::ExtractElement: {
2382 // Look through extract element. If the index is non-constant or
2383 // out-of-range demand all elements, otherwise just the extracted element.
2384 const Value *Vec = I->getOperand(0);
2385 const Value *Idx = I->getOperand(1);
2386 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2387 if (isa<ScalableVectorType>(Vec->getType())) {
2388 // FIXME: there's probably *something* we can do with scalable vectors
2389 Known.resetAll();
2390 break;
2391 }
2392 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2393 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2394 if (CIdx && CIdx->getValue().ult(NumElts))
2395 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2396 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2397 break;
2398 }
2399 case Instruction::ExtractValue:
2400 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2402 if (EVI->getNumIndices() != 1) break;
2403 if (EVI->getIndices()[0] == 0) {
2404 switch (II->getIntrinsicID()) {
2405 default: break;
2406 case Intrinsic::uadd_with_overflow:
2407 case Intrinsic::sadd_with_overflow:
2409 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2410 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2411 break;
2412 case Intrinsic::usub_with_overflow:
2413 case Intrinsic::ssub_with_overflow:
2415 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2416 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2417 break;
2418 case Intrinsic::umul_with_overflow:
2419 case Intrinsic::smul_with_overflow:
2420 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2421 false, DemandedElts, Known, Known2, Q, Depth);
2422 break;
2423 }
2424 }
2425 }
2426 break;
2427 case Instruction::Freeze:
2428 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2429 Depth + 1))
2430 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2431 break;
2432 }
2433}
2434
2435/// Determine which bits of V are known to be either zero or one and return
2436/// them.
2437KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2438 const SimplifyQuery &Q, unsigned Depth) {
2439 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2440 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2441 return Known;
2442}
2443
2444/// Determine which bits of V are known to be either zero or one and return
2445/// them.
2447 unsigned Depth) {
2448 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2450 return Known;
2451}
2452
2453/// Determine which bits of V are known to be either zero or one and return
2454/// them in the Known bit set.
2455///
2456/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2457/// we cannot optimize based on the assumption that it is zero without changing
2458/// it to be an explicit zero. If we don't change it to zero, other code could
2459/// optimized based on the contradictory assumption that it is non-zero.
2460/// Because instcombine aggressively folds operations with undef args anyway,
2461/// this won't lose us code quality.
2462///
2463/// This function is defined on values with integer type, values with pointer
2464/// type, and vectors of integers. In the case
2465/// where V is a vector, known zero, and known one values are the
2466/// same width as the vector element, and the bit is set only if it is true
2467/// for all of the demanded elements in the vector specified by DemandedElts.
2468void computeKnownBits(const Value *V, const APInt &DemandedElts,
2469 KnownBits &Known, const SimplifyQuery &Q,
2470 unsigned Depth) {
2471 if (!DemandedElts) {
2472 // No demanded elts, better to assume we don't know anything.
2473 Known.resetAll();
2474 return;
2475 }
2476
2477 assert(V && "No Value?");
2478 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2479
2480#ifndef NDEBUG
2481 Type *Ty = V->getType();
2482 unsigned BitWidth = Known.getBitWidth();
2483
2484 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2485 "Not integer or pointer type!");
2486
2487 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2488 assert(
2489 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2490 "DemandedElt width should equal the fixed vector number of elements");
2491 } else {
2492 assert(DemandedElts == APInt(1, 1) &&
2493 "DemandedElt width should be 1 for scalars or scalable vectors");
2494 }
2495
2496 Type *ScalarTy = Ty->getScalarType();
2497 if (ScalarTy->isPointerTy()) {
2498 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2499 "V and Known should have same BitWidth");
2500 } else {
2501 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2502 "V and Known should have same BitWidth");
2503 }
2504#endif
2505
2506 const APInt *C;
2507 if (match(V, m_APInt(C))) {
2508 // We know all of the bits for a scalar constant or a splat vector constant!
2510 return;
2511 }
2512 // Null and aggregate-zero are all-zeros.
2514 Known.setAllZero();
2515 return;
2516 }
2517 // Handle a constant vector by taking the intersection of the known bits of
2518 // each element.
2520 assert(!isa<ScalableVectorType>(V->getType()));
2521 // We know that CDV must be a vector of integers. Take the intersection of
2522 // each element.
2523 Known.setAllConflict();
2524 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2525 if (!DemandedElts[i])
2526 continue;
2527 APInt Elt = CDV->getElementAsAPInt(i);
2528 Known.Zero &= ~Elt;
2529 Known.One &= Elt;
2530 }
2531 if (Known.hasConflict())
2532 Known.resetAll();
2533 return;
2534 }
2535
2536 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2537 assert(!isa<ScalableVectorType>(V->getType()));
2538 // We know that CV must be a vector of integers. Take the intersection of
2539 // each element.
2540 Known.setAllConflict();
2541 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2542 if (!DemandedElts[i])
2543 continue;
2544 Constant *Element = CV->getAggregateElement(i);
2545 if (isa<PoisonValue>(Element))
2546 continue;
2547 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2548 if (!ElementCI) {
2549 Known.resetAll();
2550 return;
2551 }
2552 const APInt &Elt = ElementCI->getValue();
2553 Known.Zero &= ~Elt;
2554 Known.One &= Elt;
2555 }
2556 if (Known.hasConflict())
2557 Known.resetAll();
2558 return;
2559 }
2560
2561 // Start out not knowing anything.
2562 Known.resetAll();
2563
2564 // We can't imply anything about undefs.
2565 if (isa<UndefValue>(V))
2566 return;
2567
2568 // There's no point in looking through other users of ConstantData for
2569 // assumptions. Confirm that we've handled them all.
2570 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2571
2572 if (const auto *A = dyn_cast<Argument>(V))
2573 if (std::optional<ConstantRange> Range = A->getRange())
2574 Known = Range->toKnownBits();
2575
2576 // All recursive calls that increase depth must come after this.
2578 return;
2579
2580 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2581 // the bits of its aliasee.
2582 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2583 if (!GA->isInterposable())
2584 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2585 return;
2586 }
2587
2588 if (const Operator *I = dyn_cast<Operator>(V))
2589 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2590 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2591 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2592 Known = CR->toKnownBits();
2593 }
2594
2595 // Aligned pointers have trailing zeros - refine Known.Zero set
2596 if (isa<PointerType>(V->getType())) {
2597 Align Alignment = V->getPointerAlignment(Q.DL);
2598 Known.Zero.setLowBits(Log2(Alignment));
2599 }
2600
2601 // computeKnownBitsFromContext strictly refines Known.
2602 // Therefore, we run them after computeKnownBitsFromOperator.
2603
2604 // Check whether we can determine known bits from context such as assumes.
2606}
2607
2608/// Try to detect a recurrence that the value of the induction variable is
2609/// always a power of two (or zero).
2610static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2611 SimplifyQuery &Q, unsigned Depth) {
2612 BinaryOperator *BO = nullptr;
2613 Value *Start = nullptr, *Step = nullptr;
2614 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2615 return false;
2616
2617 // Initial value must be a power of two.
2618 for (const Use &U : PN->operands()) {
2619 if (U.get() == Start) {
2620 // Initial value comes from a different BB, need to adjust context
2621 // instruction for analysis.
2622 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2623 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2624 return false;
2625 }
2626 }
2627
2628 // Except for Mul, the induction variable must be on the left side of the
2629 // increment expression, otherwise its value can be arbitrary.
2630 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2631 return false;
2632
2633 Q.CxtI = BO->getParent()->getTerminator();
2634 switch (BO->getOpcode()) {
2635 case Instruction::Mul:
2636 // Power of two is closed under multiplication.
2637 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2638 Q.IIQ.hasNoSignedWrap(BO)) &&
2639 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2640 case Instruction::SDiv:
2641 // Start value must not be signmask for signed division, so simply being a
2642 // power of two is not sufficient, and it has to be a constant.
2643 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2644 return false;
2645 [[fallthrough]];
2646 case Instruction::UDiv:
2647 // Divisor must be a power of two.
2648 // If OrZero is false, cannot guarantee induction variable is non-zero after
2649 // division, same for Shr, unless it is exact division.
2650 return (OrZero || Q.IIQ.isExact(BO)) &&
2651 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2652 case Instruction::Shl:
2653 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2654 case Instruction::AShr:
2655 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2656 return false;
2657 [[fallthrough]];
2658 case Instruction::LShr:
2659 return OrZero || Q.IIQ.isExact(BO);
2660 default:
2661 return false;
2662 }
2663}
2664
2665/// Return true if we can infer that \p V is known to be a power of 2 from
2666/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2667static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2668 const Value *Cond,
2669 bool CondIsTrue) {
2670 CmpPredicate Pred;
2671 const APInt *RHSC;
2672 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2673 return false;
2674 if (!CondIsTrue)
2675 Pred = ICmpInst::getInversePredicate(Pred);
2676 // ctpop(V) u< 2
2677 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2678 return true;
2679 // ctpop(V) == 1
2680 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2681}
2682
2683/// Return true if the given value is known to have exactly one
2684/// bit set when defined. For vectors return true if every element is known to
2685/// be a power of two when defined. Supports values with integer or pointer
2686/// types and vectors of integers.
2687bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2688 const SimplifyQuery &Q, unsigned Depth) {
2689 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2690
2691 if (isa<Constant>(V))
2692 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2693
2694 // i1 is by definition a power of 2 or zero.
2695 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2696 return true;
2697
2698 // Try to infer from assumptions.
2699 if (Q.AC && Q.CxtI) {
2700 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2701 if (!AssumeVH)
2702 continue;
2703 CallInst *I = cast<CallInst>(AssumeVH);
2704 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2705 /*CondIsTrue=*/true) &&
2707 return true;
2708 }
2709 }
2710
2711 // Handle dominating conditions.
2712 if (Q.DC && Q.CxtI && Q.DT) {
2713 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2714 Value *Cond = BI->getCondition();
2715
2716 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2718 /*CondIsTrue=*/true) &&
2719 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2720 return true;
2721
2722 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2724 /*CondIsTrue=*/false) &&
2725 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2726 return true;
2727 }
2728 }
2729
2730 auto *I = dyn_cast<Instruction>(V);
2731 if (!I)
2732 return false;
2733
2734 if (Q.CxtI && match(V, m_VScale())) {
2735 const Function *F = Q.CxtI->getFunction();
2736 // The vscale_range indicates vscale is a power-of-two.
2737 return F->hasFnAttribute(Attribute::VScaleRange);
2738 }
2739
2740 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2741 // it is shifted off the end then the result is undefined.
2742 if (match(I, m_Shl(m_One(), m_Value())))
2743 return true;
2744
2745 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2746 // the bottom. If it is shifted off the bottom then the result is undefined.
2747 if (match(I, m_LShr(m_SignMask(), m_Value())))
2748 return true;
2749
2750 // The remaining tests are all recursive, so bail out if we hit the limit.
2752 return false;
2753
2754 switch (I->getOpcode()) {
2755 case Instruction::ZExt:
2756 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2757 case Instruction::Trunc:
2758 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2759 case Instruction::Shl:
2760 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2761 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2762 return false;
2763 case Instruction::LShr:
2764 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2765 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2766 return false;
2767 case Instruction::UDiv:
2769 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2770 return false;
2771 case Instruction::Mul:
2772 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2773 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2774 (OrZero || isKnownNonZero(I, Q, Depth));
2775 case Instruction::And:
2776 // A power of two and'd with anything is a power of two or zero.
2777 if (OrZero &&
2778 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2779 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2780 return true;
2781 // X & (-X) is always a power of two or zero.
2782 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2783 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2784 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2785 return false;
2786 case Instruction::Add: {
2787 // Adding a power-of-two or zero to the same power-of-two or zero yields
2788 // either the original power-of-two, a larger power-of-two or zero.
2790 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2791 Q.IIQ.hasNoSignedWrap(VOBO)) {
2792 if (match(I->getOperand(0),
2793 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2794 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2795 return true;
2796 if (match(I->getOperand(1),
2797 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2798 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2799 return true;
2800
2801 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2802 KnownBits LHSBits(BitWidth);
2803 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2804
2805 KnownBits RHSBits(BitWidth);
2806 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2807 // If i8 V is a power of two or zero:
2808 // ZeroBits: 1 1 1 0 1 1 1 1
2809 // ~ZeroBits: 0 0 0 1 0 0 0 0
2810 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2811 // If OrZero isn't set, we cannot give back a zero result.
2812 // Make sure either the LHS or RHS has a bit set.
2813 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2814 return true;
2815 }
2816
2817 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2818 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2819 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2820 return true;
2821 return false;
2822 }
2823 case Instruction::Select:
2824 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2825 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2826 case Instruction::PHI: {
2827 // A PHI node is power of two if all incoming values are power of two, or if
2828 // it is an induction variable where in each step its value is a power of
2829 // two.
2830 auto *PN = cast<PHINode>(I);
2832
2833 // Check if it is an induction variable and always power of two.
2834 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2835 return true;
2836
2837 // Recursively check all incoming values. Limit recursion to 2 levels, so
2838 // that search complexity is limited to number of operands^2.
2839 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2840 return llvm::all_of(PN->operands(), [&](const Use &U) {
2841 // Value is power of 2 if it is coming from PHI node itself by induction.
2842 if (U.get() == PN)
2843 return true;
2844
2845 // Change the context instruction to the incoming block where it is
2846 // evaluated.
2847 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2848 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2849 });
2850 }
2851 case Instruction::Invoke:
2852 case Instruction::Call: {
2853 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2854 switch (II->getIntrinsicID()) {
2855 case Intrinsic::umax:
2856 case Intrinsic::smax:
2857 case Intrinsic::umin:
2858 case Intrinsic::smin:
2859 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2860 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2861 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2862 // thus dont change pow2/non-pow2 status.
2863 case Intrinsic::bitreverse:
2864 case Intrinsic::bswap:
2865 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2866 case Intrinsic::fshr:
2867 case Intrinsic::fshl:
2868 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2869 if (II->getArgOperand(0) == II->getArgOperand(1))
2870 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2871 break;
2872 case Intrinsic::riscv_vsetvlimax:
2873 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2874 // for any valid vtype, so it is a power of two regardless of OrZero.
2875 return true;
2876 default:
2877 break;
2878 }
2879 }
2880 return false;
2881 }
2882 default:
2883 return false;
2884 }
2885}
2886
2887/// Test whether a GEP's result is known to be non-null.
2888///
2889/// Uses properties inherent in a GEP to try to determine whether it is known
2890/// to be non-null.
2891///
2892/// Currently this routine does not support vector GEPs.
2893static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2894 unsigned Depth) {
2895 const Function *F = nullptr;
2896 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2897 F = I->getFunction();
2898
2899 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2900 // may be null iff the base pointer is null and the offset is zero.
2901 if (!GEP->hasNoUnsignedWrap() &&
2902 !(GEP->isInBounds() &&
2903 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2904 return false;
2905
2906 // FIXME: Support vector-GEPs.
2907 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2908
2909 // If the base pointer is non-null, we cannot walk to a null address with an
2910 // inbounds GEP in address space zero.
2911 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2912 return true;
2913
2914 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2915 // If so, then the GEP cannot produce a null pointer, as doing so would
2916 // inherently violate the inbounds contract within address space zero.
2918 GTI != GTE; ++GTI) {
2919 // Struct types are easy -- they must always be indexed by a constant.
2920 if (StructType *STy = GTI.getStructTypeOrNull()) {
2921 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2922 unsigned ElementIdx = OpC->getZExtValue();
2923 const StructLayout *SL = Q.DL.getStructLayout(STy);
2924 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2925 if (ElementOffset > 0)
2926 return true;
2927 continue;
2928 }
2929
2930 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2931 if (GTI.getSequentialElementStride(Q.DL).isZero())
2932 continue;
2933
2934 // Fast path the constant operand case both for efficiency and so we don't
2935 // increment Depth when just zipping down an all-constant GEP.
2936 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2937 if (!OpC->isZero())
2938 return true;
2939 continue;
2940 }
2941
2942 // We post-increment Depth here because while isKnownNonZero increments it
2943 // as well, when we pop back up that increment won't persist. We don't want
2944 // to recurse 10k times just because we have 10k GEP operands. We don't
2945 // bail completely out because we want to handle constant GEPs regardless
2946 // of depth.
2948 continue;
2949
2950 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2951 return true;
2952 }
2953
2954 return false;
2955}
2956
2958 const Instruction *CtxI,
2959 const DominatorTree *DT) {
2960 assert(!isa<Constant>(V) && "Called for constant?");
2961
2962 if (!CtxI || !DT)
2963 return false;
2964
2965 unsigned NumUsesExplored = 0;
2966 for (auto &U : V->uses()) {
2967 // Avoid massive lists
2968 if (NumUsesExplored >= DomConditionsMaxUses)
2969 break;
2970 NumUsesExplored++;
2971
2972 const Instruction *UI = cast<Instruction>(U.getUser());
2973 // If the value is used as an argument to a call or invoke, then argument
2974 // attributes may provide an answer about null-ness.
2975 if (V->getType()->isPointerTy()) {
2976 if (const auto *CB = dyn_cast<CallBase>(UI)) {
2977 if (CB->isArgOperand(&U) &&
2978 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
2979 /*AllowUndefOrPoison=*/false) &&
2980 DT->dominates(CB, CtxI))
2981 return true;
2982 }
2983 }
2984
2985 // If the value is used as a load/store, then the pointer must be non null.
2986 if (V == getLoadStorePointerOperand(UI)) {
2989 DT->dominates(UI, CtxI))
2990 return true;
2991 }
2992
2993 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
2994 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
2995 isValidAssumeForContext(UI, CtxI, DT))
2996 return true;
2997
2998 // Consider only compare instructions uniquely controlling a branch
2999 Value *RHS;
3000 CmpPredicate Pred;
3001 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3002 continue;
3003
3004 bool NonNullIfTrue;
3005 if (cmpExcludesZero(Pred, RHS))
3006 NonNullIfTrue = true;
3008 NonNullIfTrue = false;
3009 else
3010 continue;
3011
3014 for (const auto *CmpU : UI->users()) {
3015 assert(WorkList.empty() && "Should be!");
3016 if (Visited.insert(CmpU).second)
3017 WorkList.push_back(CmpU);
3018
3019 while (!WorkList.empty()) {
3020 auto *Curr = WorkList.pop_back_val();
3021
3022 // If a user is an AND, add all its users to the work list. We only
3023 // propagate "pred != null" condition through AND because it is only
3024 // correct to assume that all conditions of AND are met in true branch.
3025 // TODO: Support similar logic of OR and EQ predicate?
3026 if (NonNullIfTrue)
3027 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3028 for (const auto *CurrU : Curr->users())
3029 if (Visited.insert(CurrU).second)
3030 WorkList.push_back(CurrU);
3031 continue;
3032 }
3033
3034 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3035 BasicBlock *NonNullSuccessor =
3036 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3037 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3038 if (DT->dominates(Edge, CtxI->getParent()))
3039 return true;
3040 } else if (NonNullIfTrue && isGuard(Curr) &&
3041 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3042 return true;
3043 }
3044 }
3045 }
3046 }
3047
3048 return false;
3049}
3050
3051/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3052/// ensure that the value it's attached to is never Value? 'RangeType' is
3053/// is the type of the value described by the range.
3054static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3055 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3056 assert(NumRanges >= 1);
3057 for (unsigned i = 0; i < NumRanges; ++i) {
3059 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3061 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3062 ConstantRange Range(Lower->getValue(), Upper->getValue());
3063 if (Range.contains(Value))
3064 return false;
3065 }
3066 return true;
3067}
3068
3069/// Try to detect a recurrence that monotonically increases/decreases from a
3070/// non-zero starting value. These are common as induction variables.
3071static bool isNonZeroRecurrence(const PHINode *PN) {
3072 BinaryOperator *BO = nullptr;
3073 Value *Start = nullptr, *Step = nullptr;
3074 const APInt *StartC, *StepC;
3075 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3076 !match(Start, m_APInt(StartC)) || StartC->isZero())
3077 return false;
3078
3079 switch (BO->getOpcode()) {
3080 case Instruction::Add:
3081 // Starting from non-zero and stepping away from zero can never wrap back
3082 // to zero.
3083 return BO->hasNoUnsignedWrap() ||
3084 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3085 StartC->isNegative() == StepC->isNegative());
3086 case Instruction::Mul:
3087 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3088 match(Step, m_APInt(StepC)) && !StepC->isZero();
3089 case Instruction::Shl:
3090 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3091 case Instruction::AShr:
3092 case Instruction::LShr:
3093 return BO->isExact();
3094 default:
3095 return false;
3096 }
3097}
3098
3099static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3101 m_Specific(Op1), m_Zero()))) ||
3103 m_Specific(Op0), m_Zero())));
3104}
3105
3106static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3107 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3108 bool NUW, unsigned Depth) {
3109 // (X + (X != 0)) is non zero
3110 if (matchOpWithOpEqZero(X, Y))
3111 return true;
3112
3113 if (NUW)
3114 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3115 isKnownNonZero(X, DemandedElts, Q, Depth);
3116
3117 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3118 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3119
3120 // If X and Y are both non-negative (as signed values) then their sum is not
3121 // zero unless both X and Y are zero.
3122 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3123 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3124 isKnownNonZero(X, DemandedElts, Q, Depth))
3125 return true;
3126
3127 // If X and Y are both negative (as signed values) then their sum is not
3128 // zero unless both X and Y equal INT_MIN.
3129 if (XKnown.isNegative() && YKnown.isNegative()) {
3131 // The sign bit of X is set. If some other bit is set then X is not equal
3132 // to INT_MIN.
3133 if (XKnown.One.intersects(Mask))
3134 return true;
3135 // The sign bit of Y is set. If some other bit is set then Y is not equal
3136 // to INT_MIN.
3137 if (YKnown.One.intersects(Mask))
3138 return true;
3139 }
3140
3141 // The sum of a non-negative number and a power of two is not zero.
3142 if (XKnown.isNonNegative() &&
3143 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3144 return true;
3145 if (YKnown.isNonNegative() &&
3146 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3147 return true;
3148
3149 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3150}
3151
3152static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3153 unsigned BitWidth, Value *X, Value *Y,
3154 unsigned Depth) {
3155 // (X - (X != 0)) is non zero
3156 // ((X != 0) - X) is non zero
3157 if (matchOpWithOpEqZero(X, Y))
3158 return true;
3159
3160 // TODO: Move this case into isKnownNonEqual().
3161 if (auto *C = dyn_cast<Constant>(X))
3162 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3163 return true;
3164
3165 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3166}
3167
3168static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3169 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3170 bool NUW, unsigned Depth) {
3171 // If X and Y are non-zero then so is X * Y as long as the multiplication
3172 // does not overflow.
3173 if (NSW || NUW)
3174 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3175 isKnownNonZero(Y, DemandedElts, Q, Depth);
3176
3177 // If either X or Y is odd, then if the other is non-zero the result can't
3178 // be zero.
3179 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3180 if (XKnown.One[0])
3181 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3182
3183 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3184 if (YKnown.One[0])
3185 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3186
3187 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3188 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3189 // the lowest known One of X and Y. If they are non-zero, the result
3190 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3191 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3192 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3193 BitWidth;
3194}
3195
3196static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3197 const SimplifyQuery &Q, const KnownBits &KnownVal,
3198 unsigned Depth) {
3199 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3200 switch (I->getOpcode()) {
3201 case Instruction::Shl:
3202 return Lhs.shl(Rhs);
3203 case Instruction::LShr:
3204 return Lhs.lshr(Rhs);
3205 case Instruction::AShr:
3206 return Lhs.ashr(Rhs);
3207 default:
3208 llvm_unreachable("Unknown Shift Opcode");
3209 }
3210 };
3211
3212 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3213 switch (I->getOpcode()) {
3214 case Instruction::Shl:
3215 return Lhs.lshr(Rhs);
3216 case Instruction::LShr:
3217 case Instruction::AShr:
3218 return Lhs.shl(Rhs);
3219 default:
3220 llvm_unreachable("Unknown Shift Opcode");
3221 }
3222 };
3223
3224 if (KnownVal.isUnknown())
3225 return false;
3226
3227 KnownBits KnownCnt =
3228 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3229 APInt MaxShift = KnownCnt.getMaxValue();
3230 unsigned NumBits = KnownVal.getBitWidth();
3231 if (MaxShift.uge(NumBits))
3232 return false;
3233
3234 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3235 return true;
3236
3237 // If all of the bits shifted out are known to be zero, and Val is known
3238 // non-zero then at least one non-zero bit must remain.
3239 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3240 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3241 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3242 return true;
3243
3244 return false;
3245}
3246
3248 const APInt &DemandedElts,
3249 const SimplifyQuery &Q, unsigned Depth) {
3250 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3251 switch (I->getOpcode()) {
3252 case Instruction::Alloca:
3253 // Alloca never returns null, malloc might.
3254 return I->getType()->getPointerAddressSpace() == 0;
3255 case Instruction::GetElementPtr:
3256 if (I->getType()->isPointerTy())
3258 break;
3259 case Instruction::BitCast: {
3260 // We need to be a bit careful here. We can only peek through the bitcast
3261 // if the scalar size of elements in the operand are smaller than and a
3262 // multiple of the size they are casting too. Take three cases:
3263 //
3264 // 1) Unsafe:
3265 // bitcast <2 x i16> %NonZero to <4 x i8>
3266 //
3267 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3268 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3269 // guranteed (imagine just sign bit set in the 2 i16 elements).
3270 //
3271 // 2) Unsafe:
3272 // bitcast <4 x i3> %NonZero to <3 x i4>
3273 //
3274 // Even though the scalar size of the src (`i3`) is smaller than the
3275 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3276 // its possible for the `3 x i4` elements to be zero because there are
3277 // some elements in the destination that don't contain any full src
3278 // element.
3279 //
3280 // 3) Safe:
3281 // bitcast <4 x i8> %NonZero to <2 x i16>
3282 //
3283 // This is always safe as non-zero in the 4 i8 elements implies
3284 // non-zero in the combination of any two adjacent ones. Since i8 is a
3285 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3286 // This all implies the 2 i16 elements are non-zero.
3287 Type *FromTy = I->getOperand(0)->getType();
3288 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3289 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3290 return isKnownNonZero(I->getOperand(0), Q, Depth);
3291 } break;
3292 case Instruction::IntToPtr:
3293 // Note that we have to take special care to avoid looking through
3294 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3295 // as casts that can alter the value, e.g., AddrSpaceCasts.
3296 if (!isa<ScalableVectorType>(I->getType()) &&
3297 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3298 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3299 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3300 break;
3301 case Instruction::PtrToAddr:
3302 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3303 // so we can directly forward.
3304 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3305 case Instruction::PtrToInt:
3306 // For inttoptr, make sure the result size is >= the address size. If the
3307 // address is non-zero, any larger value is also non-zero.
3308 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3309 I->getType()->getScalarSizeInBits())
3310 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3311 break;
3312 case Instruction::Trunc:
3313 // nuw/nsw trunc preserves zero/non-zero status of input.
3314 if (auto *TI = dyn_cast<TruncInst>(I))
3315 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3316 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3317 break;
3318
3319 // Iff x - y != 0, then x ^ y != 0
3320 // Therefore we can do the same exact checks
3321 case Instruction::Xor:
3322 case Instruction::Sub:
3323 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3324 I->getOperand(1), Depth);
3325 case Instruction::Or:
3326 // (X | (X != 0)) is non zero
3327 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3328 return true;
3329 // X | Y != 0 if X != Y.
3330 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3331 Depth))
3332 return true;
3333 // X | Y != 0 if X != 0 or Y != 0.
3334 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3335 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3336 case Instruction::SExt:
3337 case Instruction::ZExt:
3338 // ext X != 0 if X != 0.
3339 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3340
3341 case Instruction::Shl: {
3342 // shl nsw/nuw can't remove any non-zero bits.
3344 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3345 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3346
3347 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3348 // if the lowest bit is shifted off the end.
3350 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3351 if (Known.One[0])
3352 return true;
3353
3354 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3355 }
3356 case Instruction::LShr:
3357 case Instruction::AShr: {
3358 // shr exact can only shift out zero bits.
3360 if (BO->isExact())
3361 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3362
3363 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3364 // defined if the sign bit is shifted off the end.
3366 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3367 if (Known.isNegative())
3368 return true;
3369
3370 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3371 // position >= C, because the sum >= max(A, B).
3372 Value *A, *B;
3373 const APInt *C;
3374 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3375 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3376 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3377 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3378 if (!KnownA.One.lshr(*C).isZero())
3379 return true;
3380 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3381 if (!KnownB.One.lshr(*C).isZero())
3382 return true;
3383 }
3384
3385 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3386 }
3387 case Instruction::UDiv:
3388 case Instruction::SDiv: {
3389 // X / Y
3390 // div exact can only produce a zero if the dividend is zero.
3391 if (cast<PossiblyExactOperator>(I)->isExact())
3392 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3393
3394 KnownBits XKnown =
3395 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3396 // If X is fully unknown we won't be able to figure anything out so don't
3397 // both computing knownbits for Y.
3398 if (XKnown.isUnknown())
3399 return false;
3400
3401 KnownBits YKnown =
3402 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3403 if (I->getOpcode() == Instruction::SDiv) {
3404 // For signed division need to compare abs value of the operands.
3405 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3406 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3407 }
3408 // If X u>= Y then div is non zero (0/0 is UB).
3409 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3410 // If X is total unknown or X u< Y we won't be able to prove non-zero
3411 // with compute known bits so just return early.
3412 return XUgeY && *XUgeY;
3413 }
3414 case Instruction::Add: {
3415 // X + Y.
3416
3417 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3418 // non-zero.
3420 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3421 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3422 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3423 }
3424 case Instruction::Mul: {
3426 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3427 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3428 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3429 }
3430 case Instruction::Select: {
3431 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3432
3433 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3434 // then see if the select condition implies the arm is non-zero. For example
3435 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3436 // dominated by `X != 0`.
3437 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3438 Value *Op;
3439 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3440 // Op is trivially non-zero.
3441 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3442 return true;
3443
3444 // The condition of the select dominates the true/false arm. Check if the
3445 // condition implies that a given arm is non-zero.
3446 Value *X;
3447 CmpPredicate Pred;
3448 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3449 return false;
3450
3451 if (!IsTrueArm)
3452 Pred = ICmpInst::getInversePredicate(Pred);
3453
3454 return cmpExcludesZero(Pred, X);
3455 };
3456
3457 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3458 SelectArmIsNonZero(/* IsTrueArm */ false))
3459 return true;
3460 break;
3461 }
3462 case Instruction::PHI: {
3463 auto *PN = cast<PHINode>(I);
3465 return true;
3466
3467 // Check if all incoming values are non-zero using recursion.
3469 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3470 return llvm::all_of(PN->operands(), [&](const Use &U) {
3471 if (U.get() == PN)
3472 return true;
3473 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3474 // Check if the branch on the phi excludes zero.
3475 CmpPredicate Pred;
3476 Value *X;
3477 BasicBlock *TrueSucc, *FalseSucc;
3478 if (match(RecQ.CxtI,
3479 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3480 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3481 // Check for cases of duplicate successors.
3482 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3483 // If we're using the false successor, invert the predicate.
3484 if (FalseSucc == PN->getParent())
3485 Pred = CmpInst::getInversePredicate(Pred);
3486 if (cmpExcludesZero(Pred, X))
3487 return true;
3488 }
3489 }
3490 // Finally recurse on the edge and check it directly.
3491 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3492 });
3493 }
3494 case Instruction::InsertElement: {
3495 if (isa<ScalableVectorType>(I->getType()))
3496 break;
3497
3498 const Value *Vec = I->getOperand(0);
3499 const Value *Elt = I->getOperand(1);
3500 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3501
3502 unsigned NumElts = DemandedElts.getBitWidth();
3503 APInt DemandedVecElts = DemandedElts;
3504 bool SkipElt = false;
3505 // If we know the index we are inserting too, clear it from Vec check.
3506 if (CIdx && CIdx->getValue().ult(NumElts)) {
3507 DemandedVecElts.clearBit(CIdx->getZExtValue());
3508 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3509 }
3510
3511 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3512 // are non-zero.
3513 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3514 (DemandedVecElts.isZero() ||
3515 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3516 }
3517 case Instruction::ExtractElement:
3518 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3519 const Value *Vec = EEI->getVectorOperand();
3520 const Value *Idx = EEI->getIndexOperand();
3521 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3522 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3523 unsigned NumElts = VecTy->getNumElements();
3524 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3525 if (CIdx && CIdx->getValue().ult(NumElts))
3526 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3527 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3528 }
3529 }
3530 break;
3531 case Instruction::ShuffleVector: {
3532 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3533 if (!Shuf)
3534 break;
3535 APInt DemandedLHS, DemandedRHS;
3536 // For undef elements, we don't know anything about the common state of
3537 // the shuffle result.
3538 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3539 break;
3540 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3541 return (DemandedRHS.isZero() ||
3542 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3543 (DemandedLHS.isZero() ||
3544 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3545 }
3546 case Instruction::Freeze:
3547 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3548 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3549 Depth);
3550 case Instruction::Load: {
3551 auto *LI = cast<LoadInst>(I);
3552 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3553 // is never null.
3554 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3555 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3556 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3557 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3558 return true;
3559 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3561 }
3562
3563 // No need to fall through to computeKnownBits as range metadata is already
3564 // handled in isKnownNonZero.
3565 return false;
3566 }
3567 case Instruction::ExtractValue: {
3568 const WithOverflowInst *WO;
3570 switch (WO->getBinaryOp()) {
3571 default:
3572 break;
3573 case Instruction::Add:
3574 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3575 WO->getArgOperand(1),
3576 /*NSW=*/false,
3577 /*NUW=*/false, Depth);
3578 case Instruction::Sub:
3579 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3580 WO->getArgOperand(1), Depth);
3581 case Instruction::Mul:
3582 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3583 WO->getArgOperand(1),
3584 /*NSW=*/false, /*NUW=*/false, Depth);
3585 break;
3586 }
3587 }
3588 break;
3589 }
3590 case Instruction::Call:
3591 case Instruction::Invoke: {
3592 const auto *Call = cast<CallBase>(I);
3593 if (I->getType()->isPointerTy()) {
3594 if (Call->isReturnNonNull())
3595 return true;
3596 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3597 Call, /*MustPreserveOffset=*/true))
3598 return isKnownNonZero(RP, Q, Depth);
3599 } else {
3600 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3602 if (std::optional<ConstantRange> Range = Call->getRange()) {
3603 const APInt ZeroValue(Range->getBitWidth(), 0);
3604 if (!Range->contains(ZeroValue))
3605 return true;
3606 }
3607 if (const Value *RV = Call->getReturnedArgOperand())
3608 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3609 return true;
3610 }
3611
3612 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3613 switch (II->getIntrinsicID()) {
3614 case Intrinsic::sshl_sat:
3615 case Intrinsic::ushl_sat:
3616 case Intrinsic::abs:
3617 case Intrinsic::bitreverse:
3618 case Intrinsic::bswap:
3619 case Intrinsic::ctpop:
3620 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3621 // NB: We don't do usub_sat here as in any case we can prove its
3622 // non-zero, we will fold it to `sub nuw` in InstCombine.
3623 case Intrinsic::ssub_sat:
3624 // For most types, if x != y then ssub.sat x, y != 0. But
3625 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3626 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3627 if (BitWidth == 1)
3628 return false;
3629 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3630 II->getArgOperand(1), Depth);
3631 case Intrinsic::sadd_sat:
3632 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3633 II->getArgOperand(1),
3634 /*NSW=*/true, /* NUW=*/false, Depth);
3635 // Vec reverse preserves zero/non-zero status from input vec.
3636 case Intrinsic::vector_reverse:
3637 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3638 Q, Depth);
3639 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3640 case Intrinsic::vector_reduce_or:
3641 case Intrinsic::vector_reduce_umax:
3642 case Intrinsic::vector_reduce_umin:
3643 case Intrinsic::vector_reduce_smax:
3644 case Intrinsic::vector_reduce_smin:
3645 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3646 case Intrinsic::umax:
3647 case Intrinsic::uadd_sat:
3648 // umax(X, (X != 0)) is non zero
3649 // X +usat (X != 0) is non zero
3650 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3651 return true;
3652
3653 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3654 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3655 case Intrinsic::smax: {
3656 // If either arg is strictly positive the result is non-zero. Otherwise
3657 // the result is non-zero if both ops are non-zero.
3658 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3659 const KnownBits &OpKnown) {
3660 if (!OpNonZero.has_value())
3661 OpNonZero = OpKnown.isNonZero() ||
3662 isKnownNonZero(Op, DemandedElts, Q, Depth);
3663 return *OpNonZero;
3664 };
3665 // Avoid re-computing isKnownNonZero.
3666 std::optional<bool> Op0NonZero, Op1NonZero;
3667 KnownBits Op1Known =
3668 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3669 if (Op1Known.isNonNegative() &&
3670 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3671 return true;
3672 KnownBits Op0Known =
3673 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3674 if (Op0Known.isNonNegative() &&
3675 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3676 return true;
3677 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3678 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3679 }
3680 case Intrinsic::smin: {
3681 // If either arg is negative the result is non-zero. Otherwise
3682 // the result is non-zero if both ops are non-zero.
3683 KnownBits Op1Known =
3684 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3685 if (Op1Known.isNegative())
3686 return true;
3687 KnownBits Op0Known =
3688 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3689 if (Op0Known.isNegative())
3690 return true;
3691
3692 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3693 return true;
3694 }
3695 [[fallthrough]];
3696 case Intrinsic::umin:
3697 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3698 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3699 case Intrinsic::cttz:
3700 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3701 .Zero[0];
3702 case Intrinsic::ctlz:
3703 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3704 .isNonNegative();
3705 case Intrinsic::fshr:
3706 case Intrinsic::fshl:
3707 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3708 if (II->getArgOperand(0) == II->getArgOperand(1))
3709 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3710 break;
3711 case Intrinsic::vscale:
3712 return true;
3713 case Intrinsic::experimental_get_vector_length:
3714 return isKnownNonZero(I->getOperand(0), Q, Depth);
3715 default:
3716 break;
3717 }
3718 break;
3719 }
3720
3721 return false;
3722 }
3723 }
3724
3726 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3727 return Known.One != 0;
3728}
3729
3730/// Return true if the given value is known to be non-zero when defined. For
3731/// vectors, return true if every demanded element is known to be non-zero when
3732/// defined. For pointers, if the context instruction and dominator tree are
3733/// specified, perform context-sensitive analysis and return true if the
3734/// pointer couldn't possibly be null at the specified instruction.
3735/// Supports values with integer or pointer type and vectors of integers.
3736bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3737 const SimplifyQuery &Q, unsigned Depth) {
3738 Type *Ty = V->getType();
3739
3740#ifndef NDEBUG
3741 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3742
3743 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3744 assert(
3745 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3746 "DemandedElt width should equal the fixed vector number of elements");
3747 } else {
3748 assert(DemandedElts == APInt(1, 1) &&
3749 "DemandedElt width should be 1 for scalars");
3750 }
3751#endif
3752
3753 if (auto *C = dyn_cast<Constant>(V)) {
3754 if (C->isNullValue())
3755 return false;
3756 if (isa<ConstantInt>(C))
3757 // Must be non-zero due to null test above.
3758 return true;
3759
3760 // For constant vectors, check that all elements are poison or known
3761 // non-zero to determine that the whole vector is known non-zero.
3762 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3763 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3764 if (!DemandedElts[i])
3765 continue;
3766 Constant *Elt = C->getAggregateElement(i);
3767 if (!Elt || Elt->isNullValue())
3768 return false;
3769 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3770 return false;
3771 }
3772 return true;
3773 }
3774
3775 // Constant ptrauth can be null, iff the base pointer can be.
3776 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3777 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3778
3779 // A global variable in address space 0 is non null unless extern weak
3780 // or an absolute symbol reference. Other address spaces may have null as a
3781 // valid address for a global, so we can't assume anything.
3782 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3783 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3784 GV->getType()->getAddressSpace() == 0)
3785 return true;
3786 }
3787
3788 // For constant expressions, fall through to the Operator code below.
3789 if (!isa<ConstantExpr>(V))
3790 return false;
3791 }
3792
3793 if (const auto *A = dyn_cast<Argument>(V))
3794 if (std::optional<ConstantRange> Range = A->getRange()) {
3795 const APInt ZeroValue(Range->getBitWidth(), 0);
3796 if (!Range->contains(ZeroValue))
3797 return true;
3798 }
3799
3800 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3801 return true;
3802
3803 // Some of the tests below are recursive, so bail out if we hit the limit.
3805 return false;
3806
3807 // Check for pointer simplifications.
3808
3809 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3810 // A byval, inalloca may not be null in a non-default addres space. A
3811 // nonnull argument is assumed never 0.
3812 if (const Argument *A = dyn_cast<Argument>(V)) {
3813 if (((A->hasPassPointeeByValueCopyAttr() &&
3814 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3815 A->hasNonNullAttr()))
3816 return true;
3817 }
3818 }
3819
3820 if (const auto *I = dyn_cast<Operator>(V))
3821 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3822 return true;
3823
3824 if (!isa<Constant>(V) &&
3826 return true;
3827
3828 if (const Value *Stripped = stripNullTest(V))
3829 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3830
3831 return false;
3832}
3833
3835 unsigned Depth) {
3836 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3837 APInt DemandedElts =
3838 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3839 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3840}
3841
3842/// If the pair of operators are the same invertible function, return the
3843/// the operands of the function corresponding to each input. Otherwise,
3844/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3845/// every input value to exactly one output value. This is equivalent to
3846/// saying that Op1 and Op2 are equal exactly when the specified pair of
3847/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3848static std::optional<std::pair<Value*, Value*>>
3850 const Operator *Op2) {
3851 if (Op1->getOpcode() != Op2->getOpcode())
3852 return std::nullopt;
3853
3854 auto getOperands = [&](unsigned OpNum) -> auto {
3855 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3856 };
3857
3858 switch (Op1->getOpcode()) {
3859 default:
3860 break;
3861 case Instruction::Or:
3862 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3863 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3864 break;
3865 [[fallthrough]];
3866 case Instruction::Xor:
3867 case Instruction::Add: {
3868 Value *Other;
3869 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3870 return std::make_pair(Op1->getOperand(1), Other);
3871 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3872 return std::make_pair(Op1->getOperand(0), Other);
3873 break;
3874 }
3875 case Instruction::Sub:
3876 if (Op1->getOperand(0) == Op2->getOperand(0))
3877 return getOperands(1);
3878 if (Op1->getOperand(1) == Op2->getOperand(1))
3879 return getOperands(0);
3880 break;
3881 case Instruction::Mul: {
3882 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3883 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3884 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3885 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3886 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3887 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3888 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3889 break;
3890
3891 // Assume operand order has been canonicalized
3892 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3893 isa<ConstantInt>(Op1->getOperand(1)) &&
3894 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3895 return getOperands(0);
3896 break;
3897 }
3898 case Instruction::Shl: {
3899 // Same as multiplies, with the difference that we don't need to check
3900 // for a non-zero multiply. Shifts always multiply by non-zero.
3901 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3902 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3903 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3904 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3905 break;
3906
3907 if (Op1->getOperand(1) == Op2->getOperand(1))
3908 return getOperands(0);
3909 break;
3910 }
3911 case Instruction::AShr:
3912 case Instruction::LShr: {
3913 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3914 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3915 if (!PEO1->isExact() || !PEO2->isExact())
3916 break;
3917
3918 if (Op1->getOperand(1) == Op2->getOperand(1))
3919 return getOperands(0);
3920 break;
3921 }
3922 case Instruction::SExt:
3923 case Instruction::ZExt:
3924 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3925 return getOperands(0);
3926 break;
3927 case Instruction::PHI: {
3928 const PHINode *PN1 = cast<PHINode>(Op1);
3929 const PHINode *PN2 = cast<PHINode>(Op2);
3930
3931 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3932 // are a single invertible function of the start values? Note that repeated
3933 // application of an invertible function is also invertible
3934 BinaryOperator *BO1 = nullptr;
3935 Value *Start1 = nullptr, *Step1 = nullptr;
3936 BinaryOperator *BO2 = nullptr;
3937 Value *Start2 = nullptr, *Step2 = nullptr;
3938 if (PN1->getParent() != PN2->getParent() ||
3939 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3940 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3941 break;
3942
3944 cast<Operator>(BO2));
3945 if (!Values)
3946 break;
3947
3948 // We have to be careful of mutually defined recurrences here. Ex:
3949 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3950 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3951 // The invertibility of these is complicated, and not worth reasoning
3952 // about (yet?).
3953 if (Values->first != PN1 || Values->second != PN2)
3954 break;
3955
3956 return std::make_pair(Start1, Start2);
3957 }
3958 }
3959 return std::nullopt;
3960}
3961
3962/// Return true if V1 == (binop V2, X), where X is known non-zero.
3963/// Only handle a small subset of binops where (binop V2, X) with non-zero X
3964/// implies V2 != V1.
3965static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
3966 const APInt &DemandedElts,
3967 const SimplifyQuery &Q, unsigned Depth) {
3969 if (!BO)
3970 return false;
3971 switch (BO->getOpcode()) {
3972 default:
3973 break;
3974 case Instruction::Or:
3975 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
3976 break;
3977 [[fallthrough]];
3978 case Instruction::Xor:
3979 case Instruction::Add:
3980 Value *Op = nullptr;
3981 if (V2 == BO->getOperand(0))
3982 Op = BO->getOperand(1);
3983 else if (V2 == BO->getOperand(1))
3984 Op = BO->getOperand(0);
3985 else
3986 return false;
3987 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
3988 }
3989 return false;
3990}
3991
3992/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
3993/// the multiplication is nuw or nsw.
3994static bool isNonEqualMul(const Value *V1, const Value *V2,
3995 const APInt &DemandedElts, const SimplifyQuery &Q,
3996 unsigned Depth) {
3997 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3998 const APInt *C;
3999 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4000 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4001 !C->isZero() && !C->isOne() &&
4002 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4003 }
4004 return false;
4005}
4006
4007/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4008/// the shift is nuw or nsw.
4009static bool isNonEqualShl(const Value *V1, const Value *V2,
4010 const APInt &DemandedElts, const SimplifyQuery &Q,
4011 unsigned Depth) {
4012 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4013 const APInt *C;
4014 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4015 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4016 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4017 }
4018 return false;
4019}
4020
4021static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4022 const APInt &DemandedElts, const SimplifyQuery &Q,
4023 unsigned Depth) {
4024 // Check two PHIs are in same block.
4025 if (PN1->getParent() != PN2->getParent())
4026 return false;
4027
4029 bool UsedFullRecursion = false;
4030 for (const BasicBlock *IncomBB : PN1->blocks()) {
4031 if (!VisitedBBs.insert(IncomBB).second)
4032 continue; // Don't reprocess blocks that we have dealt with already.
4033 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4034 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4035 const APInt *C1, *C2;
4036 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4037 continue;
4038
4039 // Only one pair of phi operands is allowed for full recursion.
4040 if (UsedFullRecursion)
4041 return false;
4042
4044 RecQ.CxtI = IncomBB->getTerminator();
4045 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4046 return false;
4047 UsedFullRecursion = true;
4048 }
4049 return true;
4050}
4051
4052static bool isNonEqualSelect(const Value *V1, const Value *V2,
4053 const APInt &DemandedElts, const SimplifyQuery &Q,
4054 unsigned Depth) {
4055 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4056 if (!SI1)
4057 return false;
4058
4059 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4060 const Value *Cond1 = SI1->getCondition();
4061 const Value *Cond2 = SI2->getCondition();
4062 if (Cond1 == Cond2)
4063 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4064 DemandedElts, Q, Depth + 1) &&
4065 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4066 DemandedElts, Q, Depth + 1);
4067 }
4068 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4069 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4070}
4071
4072// Check to see if A is both a GEP and is the incoming value for a PHI in the
4073// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4074// one of them being the recursive GEP A and the other a ptr at same base and at
4075// the same/higher offset than B we are only incrementing the pointer further in
4076// loop if offset of recursive GEP is greater than 0.
4078 const SimplifyQuery &Q) {
4079 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4080 return false;
4081
4082 auto *GEPA = dyn_cast<GEPOperator>(A);
4083 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4084 return false;
4085
4086 // Handle 2 incoming PHI values with one being a recursive GEP.
4087 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4088 if (!PN || PN->getNumIncomingValues() != 2)
4089 return false;
4090
4091 // Search for the recursive GEP as an incoming operand, and record that as
4092 // Step.
4093 Value *Start = nullptr;
4094 Value *Step = const_cast<Value *>(A);
4095 if (PN->getIncomingValue(0) == Step)
4096 Start = PN->getIncomingValue(1);
4097 else if (PN->getIncomingValue(1) == Step)
4098 Start = PN->getIncomingValue(0);
4099 else
4100 return false;
4101
4102 // Other incoming node base should match the B base.
4103 // StartOffset >= OffsetB && StepOffset > 0?
4104 // StartOffset <= OffsetB && StepOffset < 0?
4105 // Is non-equal if above are true.
4106 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4107 // optimisation to inbounds GEPs only.
4108 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4109 APInt StartOffset(IndexWidth, 0);
4110 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4111 APInt StepOffset(IndexWidth, 0);
4112 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4113
4114 // Check if Base Pointer of Step matches the PHI.
4115 if (Step != PN)
4116 return false;
4117 APInt OffsetB(IndexWidth, 0);
4118 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4119 return Start == B &&
4120 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4121 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4122}
4123
4124static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4125 const SimplifyQuery &Q, unsigned Depth) {
4126 if (!Q.CxtI)
4127 return false;
4128
4129 // Try to infer NonEqual based on information from dominating conditions.
4130 if (Q.DC && Q.DT) {
4131 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4132 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4133 Value *Cond = BI->getCondition();
4134 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4135 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4137 /*LHSIsTrue=*/true, Depth)
4138 .value_or(false))
4139 return true;
4140
4141 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4142 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4144 /*LHSIsTrue=*/false, Depth)
4145 .value_or(false))
4146 return true;
4147 }
4148
4149 return false;
4150 };
4151
4152 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4153 IsKnownNonEqualFromDominatingCondition(V2))
4154 return true;
4155 }
4156
4157 if (!Q.AC)
4158 return false;
4159
4160 // Try to infer NonEqual based on information from assumptions.
4161 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4162 if (!AssumeVH)
4163 continue;
4164 CallInst *I = cast<CallInst>(AssumeVH);
4165
4166 assert(I->getFunction() == Q.CxtI->getFunction() &&
4167 "Got assumption for the wrong function!");
4168 assert(I->getIntrinsicID() == Intrinsic::assume &&
4169 "must be an assume intrinsic");
4170
4171 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4172 /*LHSIsTrue=*/true, Depth)
4173 .value_or(false) &&
4175 return true;
4176 }
4177
4178 return false;
4179}
4180
4181static bool isNonEqualURem(const Value *X, const Value *Rem,
4182 const SimplifyQuery &Q) {
4183 const Value *Y;
4184 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4185 return false;
4186
4187 // For a defined urem, X != X urem Y exactly when X u>= Y.
4188 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4190 return true;
4191
4192 std::optional<bool> Implied =
4194 return Implied && *Implied;
4195}
4196
4197/// Return true if it is known that V1 != V2.
4198static bool isKnownNonEqual(const Value *V1, const Value *V2,
4199 const APInt &DemandedElts, const SimplifyQuery &Q,
4200 unsigned Depth) {
4201 if (V1 == V2)
4202 return false;
4203 if (V1->getType() != V2->getType())
4204 // We can't look through casts yet.
4205 return false;
4206
4208 return false;
4209
4210 // See if we can recurse through (exactly one of) our operands. This
4211 // requires our operation be 1-to-1 and map every input value to exactly
4212 // one output value. Such an operation is invertible.
4213 auto *O1 = dyn_cast<Operator>(V1);
4214 auto *O2 = dyn_cast<Operator>(V2);
4215 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4216 if (auto Values = getInvertibleOperands(O1, O2))
4217 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4218 Depth + 1);
4219
4220 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4221 const PHINode *PN2 = cast<PHINode>(V2);
4222 // FIXME: This is missing a generalization to handle the case where one is
4223 // a PHI and another one isn't.
4224 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4225 return true;
4226 };
4227 }
4228
4229 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4230 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4231 return true;
4232
4233 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4234 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4235 return true;
4236
4237 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4238 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4239 return true;
4240
4241 if (V1->getType()->isIntOrIntVectorTy()) {
4242 // Are any known bits in V1 contradictory to known bits in V2? If V1
4243 // has a known zero where V2 has a known one, they must not be equal.
4244 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4245 if (!Known1.isUnknown()) {
4246 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4247 if (Known1.Zero.intersects(Known2.One) ||
4248 Known2.Zero.intersects(Known1.One))
4249 return true;
4250 }
4251 }
4252
4253 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4254 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4255 return true;
4256
4259 return true;
4260
4261 Value *A, *B;
4262 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4263 // Check PtrToInt type matches the pointer size.
4264 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4266 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4267
4268 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4269 return true;
4270
4271 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4272 return true;
4273
4274 return false;
4275}
4276
4277/// For vector constants, loop over the elements and find the constant with the
4278/// minimum number of sign bits. Return 0 if the value is not a vector constant
4279/// or if any element was not analyzed; otherwise, return the count for the
4280/// element with the minimum number of sign bits.
4282 const APInt &DemandedElts,
4283 unsigned TyBits) {
4284 const auto *CV = dyn_cast<Constant>(V);
4285 if (!CV || !isa<FixedVectorType>(CV->getType()))
4286 return 0;
4287
4288 unsigned MinSignBits = TyBits;
4289 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4290 for (unsigned i = 0; i != NumElts; ++i) {
4291 if (!DemandedElts[i])
4292 continue;
4293 // If we find a non-ConstantInt, bail out.
4294 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4295 if (!Elt)
4296 return 0;
4297
4298 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4299 }
4300
4301 return MinSignBits;
4302}
4303
4304static unsigned ComputeNumSignBitsImpl(const Value *V,
4305 const APInt &DemandedElts,
4306 const SimplifyQuery &Q, unsigned Depth);
4307
4308static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4309 const SimplifyQuery &Q, unsigned Depth) {
4310 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4311 assert(Result > 0 && "At least one sign bit needs to be present!");
4312 return Result;
4313}
4314
4315/// Return the number of times the sign bit of the register is replicated into
4316/// the other bits. We know that at least 1 bit is always equal to the sign bit
4317/// (itself), but other cases can give us information. For example, immediately
4318/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4319/// other, so we return 3. For vectors, return the number of sign bits for the
4320/// vector element with the minimum number of known sign bits of the demanded
4321/// elements in the vector specified by DemandedElts.
4322static unsigned ComputeNumSignBitsImpl(const Value *V,
4323 const APInt &DemandedElts,
4324 const SimplifyQuery &Q, unsigned Depth) {
4325 Type *Ty = V->getType();
4326#ifndef NDEBUG
4327 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4328
4329 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4330 assert(
4331 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4332 "DemandedElt width should equal the fixed vector number of elements");
4333 } else {
4334 assert(DemandedElts == APInt(1, 1) &&
4335 "DemandedElt width should be 1 for scalars");
4336 }
4337#endif
4338
4339 // We return the minimum number of sign bits that are guaranteed to be present
4340 // in V, so for undef we have to conservatively return 1. We don't have the
4341 // same behavior for poison though -- that's a FIXME today.
4342
4343 Type *ScalarTy = Ty->getScalarType();
4344 unsigned TyBits = ScalarTy->isPointerTy() ?
4345 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4346 Q.DL.getTypeSizeInBits(ScalarTy);
4347
4348 unsigned Tmp, Tmp2;
4349 unsigned FirstAnswer = 1;
4350
4351 // Note that ConstantInt is handled by the general computeKnownBits case
4352 // below.
4353
4355 return 1;
4356
4357 if (auto *U = dyn_cast<Operator>(V)) {
4358 switch (Operator::getOpcode(V)) {
4359 default: break;
4360 case Instruction::BitCast: {
4361 Value *Src = U->getOperand(0);
4362 Type *SrcTy = Src->getType();
4363
4364 // Skip if the source type is not an integer or integer vector type
4365 // This ensures we only process integer-like types
4366 if (!SrcTy->isIntOrIntVectorTy())
4367 break;
4368
4369 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4370
4371 // Bitcast 'large element' scalar/vector to 'small element' vector.
4372 if ((SrcBits % TyBits) != 0)
4373 break;
4374
4375 // Only proceed if the destination type is a fixed-size vector
4376 if (isa<FixedVectorType>(Ty)) {
4377 // Fast case - sign splat can be simply split across the small elements.
4378 // This works for both vector and scalar sources
4379 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4380 if (Tmp == SrcBits)
4381 return TyBits;
4382 }
4383 break;
4384 }
4385 case Instruction::SExt:
4386 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4387 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4388 Tmp;
4389
4390 case Instruction::SDiv: {
4391 const APInt *Denominator;
4392 // sdiv X, C -> adds log(C) sign bits.
4393 if (match(U->getOperand(1), m_APInt(Denominator))) {
4394
4395 // Ignore non-positive denominator.
4396 if (!Denominator->isStrictlyPositive())
4397 break;
4398
4399 // Calculate the incoming numerator bits.
4400 unsigned NumBits =
4401 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4402
4403 // Add floor(log(C)) bits to the numerator bits.
4404 return std::min(TyBits, NumBits + Denominator->logBase2());
4405 }
4406 break;
4407 }
4408
4409 case Instruction::SRem: {
4410 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4411
4412 const APInt *Denominator;
4413 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4414 // positive constant. This let us put a lower bound on the number of sign
4415 // bits.
4416 if (match(U->getOperand(1), m_APInt(Denominator))) {
4417
4418 // Ignore non-positive denominator.
4419 if (Denominator->isStrictlyPositive()) {
4420 // Calculate the leading sign bit constraints by examining the
4421 // denominator. Given that the denominator is positive, there are two
4422 // cases:
4423 //
4424 // 1. The numerator is positive. The result range is [0,C) and
4425 // [0,C) u< (1 << ceilLogBase2(C)).
4426 //
4427 // 2. The numerator is negative. Then the result range is (-C,0] and
4428 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4429 //
4430 // Thus a lower bound on the number of sign bits is `TyBits -
4431 // ceilLogBase2(C)`.
4432
4433 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4434 Tmp = std::max(Tmp, ResBits);
4435 }
4436 }
4437 return Tmp;
4438 }
4439
4440 case Instruction::AShr: {
4441 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4442 // ashr X, C -> adds C sign bits. Vectors too.
4443 const APInt *ShAmt;
4444 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4445 if (ShAmt->uge(TyBits))
4446 break; // Bad shift.
4447 unsigned ShAmtLimited = ShAmt->getZExtValue();
4448 Tmp += ShAmtLimited;
4449 if (Tmp > TyBits) Tmp = TyBits;
4450 }
4451 return Tmp;
4452 }
4453 case Instruction::Shl: {
4454 const APInt *ShAmt;
4455 Value *X = nullptr;
4456 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4457 // shl destroys sign bits.
4458 if (ShAmt->uge(TyBits))
4459 break; // Bad shift.
4460 // We can look through a zext (more or less treating it as a sext) if
4461 // all extended bits are shifted out.
4462 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4463 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4464 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4465 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4466 } else
4467 Tmp =
4468 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4469 if (ShAmt->uge(Tmp))
4470 break; // Shifted all sign bits out.
4471 Tmp2 = ShAmt->getZExtValue();
4472 return Tmp - Tmp2;
4473 }
4474 break;
4475 }
4476 case Instruction::And:
4477 case Instruction::Or:
4478 case Instruction::Xor: // NOT is handled here.
4479 // Logical binary ops preserve the number of sign bits at the worst.
4480 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4481 if (Tmp != 1) {
4482 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4483 FirstAnswer = std::min(Tmp, Tmp2);
4484 // We computed what we know about the sign bits as our first
4485 // answer. Now proceed to the generic code that uses
4486 // computeKnownBits, and pick whichever answer is better.
4487 }
4488 break;
4489
4490 case Instruction::Select: {
4491 // If we have a clamp pattern, we know that the number of sign bits will
4492 // be the minimum of the clamp min/max range.
4493 const Value *X;
4494 const APInt *CLow, *CHigh;
4495 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4496 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4497
4498 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4499 if (Tmp == 1)
4500 break;
4501 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4502 return std::min(Tmp, Tmp2);
4503 }
4504
4505 case Instruction::Add:
4506 // Add can have at most one carry bit. Thus we know that the output
4507 // is, at worst, one more bit than the inputs.
4508 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4509 if (Tmp == 1) break;
4510
4511 // Special case decrementing a value (ADD X, -1):
4512 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4513 if (CRHS->isAllOnesValue()) {
4514 KnownBits Known(TyBits);
4515 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4516
4517 // If the input is known to be 0 or 1, the output is 0/-1, which is
4518 // all sign bits set.
4519 if ((Known.Zero | 1).isAllOnes())
4520 return TyBits;
4521
4522 // If we are subtracting one from a positive number, there is no carry
4523 // out of the result.
4524 if (Known.isNonNegative())
4525 return Tmp;
4526 }
4527
4528 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4529 if (Tmp2 == 1)
4530 break;
4531 return std::min(Tmp, Tmp2) - 1;
4532
4533 case Instruction::Sub:
4534 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4535 if (Tmp2 == 1)
4536 break;
4537
4538 // Handle NEG.
4539 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4540 if (CLHS->isNullValue()) {
4541 KnownBits Known(TyBits);
4542 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4543 // If the input is known to be 0 or 1, the output is 0/-1, which is
4544 // all sign bits set.
4545 if ((Known.Zero | 1).isAllOnes())
4546 return TyBits;
4547
4548 // If the input is known to be positive (the sign bit is known clear),
4549 // the output of the NEG has the same number of sign bits as the
4550 // input.
4551 if (Known.isNonNegative())
4552 return Tmp2;
4553
4554 // Otherwise, we treat this like a SUB.
4555 }
4556
4557 // Sub can have at most one carry bit. Thus we know that the output
4558 // is, at worst, one more bit than the inputs.
4559 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4560 if (Tmp == 1)
4561 break;
4562 return std::min(Tmp, Tmp2) - 1;
4563
4564 case Instruction::Mul: {
4565 // The output of the Mul can be at most twice the valid bits in the
4566 // inputs.
4567 unsigned SignBitsOp0 =
4568 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4569 if (SignBitsOp0 == 1)
4570 break;
4571 unsigned SignBitsOp1 =
4572 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4573 if (SignBitsOp1 == 1)
4574 break;
4575 unsigned OutValidBits =
4576 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4577 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4578 }
4579
4580 case Instruction::PHI: {
4581 const PHINode *PN = cast<PHINode>(U);
4582 unsigned NumIncomingValues = PN->getNumIncomingValues();
4583 // Don't analyze large in-degree PHIs.
4584 if (NumIncomingValues > 4) break;
4585 // Unreachable blocks may have zero-operand PHI nodes.
4586 if (NumIncomingValues == 0) break;
4587
4588 // Take the minimum of all incoming values. This can't infinitely loop
4589 // because of our depth threshold.
4591 Tmp = TyBits;
4592 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4593 if (Tmp == 1) return Tmp;
4594 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4595 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4596 DemandedElts, RecQ, Depth + 1));
4597 }
4598 return Tmp;
4599 }
4600
4601 case Instruction::Trunc: {
4602 // If the input contained enough sign bits that some remain after the
4603 // truncation, then we can make use of that. Otherwise we don't know
4604 // anything.
4605 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4606 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4607 if (Tmp > (OperandTyBits - TyBits))
4608 return Tmp - (OperandTyBits - TyBits);
4609
4610 return 1;
4611 }
4612
4613 case Instruction::ExtractElement:
4614 // Look through extract element. At the moment we keep this simple and
4615 // skip tracking the specific element. But at least we might find
4616 // information valid for all elements of the vector (for example if vector
4617 // is sign extended, shifted, etc).
4618 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4619
4620 case Instruction::ShuffleVector: {
4621 // Collect the minimum number of sign bits that are shared by every vector
4622 // element referenced by the shuffle.
4623 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4624 if (!Shuf) {
4625 // FIXME: Add support for shufflevector constant expressions.
4626 return 1;
4627 }
4628 APInt DemandedLHS, DemandedRHS;
4629 // For undef elements, we don't know anything about the common state of
4630 // the shuffle result.
4631 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4632 return 1;
4633 Tmp = std::numeric_limits<unsigned>::max();
4634 if (!!DemandedLHS) {
4635 const Value *LHS = Shuf->getOperand(0);
4636 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4637 }
4638 // If we don't know anything, early out and try computeKnownBits
4639 // fall-back.
4640 if (Tmp == 1)
4641 break;
4642 if (!!DemandedRHS) {
4643 const Value *RHS = Shuf->getOperand(1);
4644 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4645 Tmp = std::min(Tmp, Tmp2);
4646 }
4647 // If we don't know anything, early out and try computeKnownBits
4648 // fall-back.
4649 if (Tmp == 1)
4650 break;
4651 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4652 return Tmp;
4653 }
4654 case Instruction::Call: {
4655 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4656 switch (II->getIntrinsicID()) {
4657 default:
4658 break;
4659 case Intrinsic::abs:
4660 Tmp =
4661 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4662 if (Tmp == 1)
4663 break;
4664
4665 // Absolute value reduces number of sign bits by at most 1.
4666 return Tmp - 1;
4667 case Intrinsic::smin:
4668 case Intrinsic::smax: {
4669 const APInt *CLow, *CHigh;
4670 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4671 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4672 }
4673 }
4674 }
4675 }
4676 }
4677 }
4678
4679 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4680 // use this information.
4681
4682 // If we can examine all elements of a vector constant successfully, we're
4683 // done (we can't do any better than that). If not, keep trying.
4684 if (unsigned VecSignBits =
4685 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4686 return VecSignBits;
4687
4688 KnownBits Known(TyBits);
4689 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4690
4691 // If we know that the sign bit is either zero or one, determine the number of
4692 // identical bits in the top of the input value.
4693 return std::max(FirstAnswer, Known.countMinSignBits());
4694}
4695
4697 const TargetLibraryInfo *TLI) {
4698 const Function *F = CB.getCalledFunction();
4699 if (!F)
4701
4702 if (F->isIntrinsic())
4703 return F->getIntrinsicID();
4704
4705 // We are going to infer semantics of a library function based on mapping it
4706 // to an LLVM intrinsic. Check that the library function is available from
4707 // this callbase and in this environment.
4708 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4710
4711 LibFunc Func = TLI->getLibFunc(CB);
4712 if (Func == NotLibFunc)
4714
4715 switch (Func) {
4716 default:
4717 break;
4718 case LibFunc_sin:
4719 case LibFunc_sinf:
4720 case LibFunc_sinl:
4721 return Intrinsic::sin;
4722 case LibFunc_cos:
4723 case LibFunc_cosf:
4724 case LibFunc_cosl:
4725 return Intrinsic::cos;
4726 case LibFunc_tan:
4727 case LibFunc_tanf:
4728 case LibFunc_tanl:
4729 return Intrinsic::tan;
4730 case LibFunc_asin:
4731 case LibFunc_asinf:
4732 case LibFunc_asinl:
4733 return Intrinsic::asin;
4734 case LibFunc_acos:
4735 case LibFunc_acosf:
4736 case LibFunc_acosl:
4737 return Intrinsic::acos;
4738 case LibFunc_atan:
4739 case LibFunc_atanf:
4740 case LibFunc_atanl:
4741 return Intrinsic::atan;
4742 case LibFunc_atan2:
4743 case LibFunc_atan2f:
4744 case LibFunc_atan2l:
4745 return Intrinsic::atan2;
4746 case LibFunc_sinh:
4747 case LibFunc_sinhf:
4748 case LibFunc_sinhl:
4749 return Intrinsic::sinh;
4750 case LibFunc_cosh:
4751 case LibFunc_coshf:
4752 case LibFunc_coshl:
4753 return Intrinsic::cosh;
4754 case LibFunc_tanh:
4755 case LibFunc_tanhf:
4756 case LibFunc_tanhl:
4757 return Intrinsic::tanh;
4758 case LibFunc_exp:
4759 case LibFunc_expf:
4760 case LibFunc_expl:
4761 return Intrinsic::exp;
4762 case LibFunc_exp2:
4763 case LibFunc_exp2f:
4764 case LibFunc_exp2l:
4765 return Intrinsic::exp2;
4766 case LibFunc_exp10:
4767 case LibFunc_exp10f:
4768 case LibFunc_exp10l:
4769 return Intrinsic::exp10;
4770 case LibFunc_log:
4771 case LibFunc_logf:
4772 case LibFunc_logl:
4773 return Intrinsic::log;
4774 case LibFunc_log10:
4775 case LibFunc_log10f:
4776 case LibFunc_log10l:
4777 return Intrinsic::log10;
4778 case LibFunc_log2:
4779 case LibFunc_log2f:
4780 case LibFunc_log2l:
4781 return Intrinsic::log2;
4782 case LibFunc_fabs:
4783 case LibFunc_fabsf:
4784 case LibFunc_fabsl:
4785 return Intrinsic::fabs;
4786 case LibFunc_fmin:
4787 case LibFunc_fminf:
4788 case LibFunc_fminl:
4789 return Intrinsic::minnum;
4790 case LibFunc_fmax:
4791 case LibFunc_fmaxf:
4792 case LibFunc_fmaxl:
4793 return Intrinsic::maxnum;
4794 case LibFunc_copysign:
4795 case LibFunc_copysignf:
4796 case LibFunc_copysignl:
4797 return Intrinsic::copysign;
4798 case LibFunc_floor:
4799 case LibFunc_floorf:
4800 case LibFunc_floorl:
4801 return Intrinsic::floor;
4802 case LibFunc_ceil:
4803 case LibFunc_ceilf:
4804 case LibFunc_ceill:
4805 return Intrinsic::ceil;
4806 case LibFunc_trunc:
4807 case LibFunc_truncf:
4808 case LibFunc_truncl:
4809 return Intrinsic::trunc;
4810 case LibFunc_rint:
4811 case LibFunc_rintf:
4812 case LibFunc_rintl:
4813 return Intrinsic::rint;
4814 case LibFunc_nearbyint:
4815 case LibFunc_nearbyintf:
4816 case LibFunc_nearbyintl:
4817 return Intrinsic::nearbyint;
4818 case LibFunc_round:
4819 case LibFunc_roundf:
4820 case LibFunc_roundl:
4821 return Intrinsic::round;
4822 case LibFunc_roundeven:
4823 case LibFunc_roundevenf:
4824 case LibFunc_roundevenl:
4825 return Intrinsic::roundeven;
4826 case LibFunc_pow:
4827 case LibFunc_powf:
4828 case LibFunc_powl:
4829 return Intrinsic::pow;
4830 case LibFunc_sqrt:
4831 case LibFunc_sqrtf:
4832 case LibFunc_sqrtl:
4833 return Intrinsic::sqrt;
4834 }
4835
4837}
4838
4839/// Given an exploded icmp instruction, return true if the comparison only
4840/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4841/// the result of the comparison is true when the input value is signed.
4843 bool &TrueIfSigned) {
4844 switch (Pred) {
4845 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4846 TrueIfSigned = true;
4847 return RHS.isZero();
4848 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4849 TrueIfSigned = true;
4850 return RHS.isAllOnes();
4851 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4852 TrueIfSigned = false;
4853 return RHS.isAllOnes();
4854 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4855 TrueIfSigned = false;
4856 return RHS.isZero();
4857 case ICmpInst::ICMP_UGT:
4858 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4859 TrueIfSigned = true;
4860 return RHS.isMaxSignedValue();
4861 case ICmpInst::ICMP_UGE:
4862 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4863 TrueIfSigned = true;
4864 return RHS.isMinSignedValue();
4865 case ICmpInst::ICMP_ULT:
4866 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4867 TrueIfSigned = false;
4868 return RHS.isMinSignedValue();
4869 case ICmpInst::ICMP_ULE:
4870 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4871 TrueIfSigned = false;
4872 return RHS.isMaxSignedValue();
4873 default:
4874 return false;
4875 }
4876}
4877
4879 bool CondIsTrue,
4880 const Instruction *CxtI,
4881 KnownFPClass &KnownFromContext,
4882 unsigned Depth = 0) {
4883 Value *A, *B;
4885 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4886 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4887 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4888 Depth + 1);
4889 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4890 Depth + 1);
4891 return;
4892 }
4894 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4895 Depth + 1);
4896 return;
4897 }
4898 CmpPredicate Pred;
4899 Value *LHS;
4900 uint64_t ClassVal = 0;
4901 const APFloat *CRHS;
4902 const APInt *RHS;
4903 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4904 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4905 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4906 LHS != V);
4907 if (CmpVal == V)
4908 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4910 m_Specific(V), m_ConstantInt(ClassVal)))) {
4911 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4912 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4913 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4914 m_APInt(RHS)))) {
4915 bool TrueIfSigned;
4916 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4917 return;
4918 if (TrueIfSigned == CondIsTrue)
4919 KnownFromContext.signBitMustBeOne();
4920 else
4921 KnownFromContext.signBitMustBeZero();
4922 }
4923}
4924
4925/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4926/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4927/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4928/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4929/// exponent range is [-149, -2], but the 0 edge case is above this range).
4930static std::tuple<int, int, int>
4932 if (!Q.CxtI || !Q.DC || !Q.DT)
4934
4935 // Intersect the bounds implied by every dominating condition, keeping the
4936 // tightest maximum. A value may participate in multiple compares
4937 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4938 int MaxExp = APFloat::IEK_Inf;
4939 int MaxExpNonZero = APFloat::IEK_Inf;
4940
4941 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4942 CmpPredicate Pred;
4943 const APFloat *LimitC;
4944 if (!match(BI->getCondition(),
4945 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4946 continue;
4947
4948 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4949 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4950 continue;
4951
4952 // If fabs(x) <= K, implies the exponent min exp range.
4953 // if fabs(x) >= K, swap the successor
4954 bool IsLessEqual =
4955 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
4956 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
4957 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
4958
4959 bool KnownStrictlyLess =
4960 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
4961 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
4962
4963 BasicBlockEdge Edge1(BI->getParent(),
4964 BI->getSuccessor(IsLessEqual ? 0 : 1));
4965 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
4966 // frexp returns an exponent one greater than ilogb.
4967 int Exp = ilogb(*LimitC) + 1;
4968
4969 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
4970 // exponent drops by one when K is exact power of two.
4971 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
4972 --Exp;
4973
4974 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
4975 // may exclude.
4976
4977 // TODO: Figure out lower bound to detect no-underflow.
4978 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
4979 MaxExp = std::min(MaxExp, std::max(Exp, 0));
4980 }
4981 }
4982
4983 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
4984}
4985
4987 const SimplifyQuery &Q) {
4988 KnownFPClass KnownFromContext;
4989
4990 if (Q.CC && Q.CC->AffectedValues.contains(V))
4992 KnownFromContext);
4993
4994 if (!Q.CxtI)
4995 return KnownFromContext;
4996
4997 if (Q.DC && Q.DT) {
4998 // Handle dominating conditions.
4999 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5000 Value *Cond = BI->getCondition();
5001
5002 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5003 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
5004 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
5005 KnownFromContext);
5006
5007 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5008 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
5009 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
5010 KnownFromContext);
5011 }
5012 }
5013
5014 if (!Q.AC)
5015 return KnownFromContext;
5016
5017 // Try to restrict the floating-point classes based on information from
5018 // assumptions.
5019 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5020 if (!AssumeVH)
5021 continue;
5022 CallInst *I = cast<CallInst>(AssumeVH);
5023
5024 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5025 "Got assumption for the wrong function!");
5026 assert(I->getIntrinsicID() == Intrinsic::assume &&
5027 "must be an assume intrinsic");
5028
5029 if (!isValidAssumeForContext(I, Q))
5030 continue;
5031
5032 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5033 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5034 }
5035
5036 return KnownFromContext;
5037}
5038
5040 Value *Arm, bool Invert,
5041 const SimplifyQuery &SQ,
5042 unsigned Depth) {
5043
5044 KnownFPClass KnownSrc;
5046 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5047 Depth + 1);
5048 KnownSrc = KnownSrc.unionWith(Known);
5049 if (KnownSrc.isUnknown())
5050 return;
5051
5052 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5053 Known = KnownSrc;
5054}
5055
5056void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5057 FPClassTest InterestedClasses, KnownFPClass &Known,
5058 const SimplifyQuery &Q, unsigned Depth);
5059
5061 FPClassTest InterestedClasses,
5062 const SimplifyQuery &Q, unsigned Depth) {
5063 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5064 APInt DemandedElts =
5065 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5066 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5067}
5068
5070 const APInt &DemandedElts,
5071 FPClassTest InterestedClasses,
5073 const SimplifyQuery &Q,
5074 unsigned Depth) {
5075 if ((InterestedClasses &
5077 return;
5078
5079 KnownFPClass KnownSrc;
5080 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5081 KnownSrc, Q, Depth + 1);
5082 Known = KnownFPClass::fptrunc(KnownSrc);
5083}
5084
5086 switch (IID) {
5087 case Intrinsic::minimum:
5089 case Intrinsic::maximum:
5091 case Intrinsic::minimumnum:
5093 case Intrinsic::maximumnum:
5095 case Intrinsic::minnum:
5097 case Intrinsic::maxnum:
5099 default:
5100 llvm_unreachable("not a floating-point min-max intrinsic");
5101 }
5102}
5103
5104/// \return true if this is a floating point value that is known to have a
5105/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5106static bool isAbsoluteValueULEOne(const Value *V) {
5107 // TODO: Handle frexp
5108 // TODO: Other rounding intrinsics?
5109 // TODO: Try computeKnownExponentRangeFromContext
5110
5111 // fabs(x - floor(x)) <= 1
5112 const Value *SubFloorX;
5113 if (match(V, m_FSub(m_Value(SubFloorX),
5115 return true;
5116
5119}
5120
5121void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5122 FPClassTest InterestedClasses, KnownFPClass &Known,
5123 const SimplifyQuery &Q, unsigned Depth) {
5124 assert(Known.isUnknown() && "should not be called with known information");
5125
5126 if (!DemandedElts) {
5127 // No demanded elts, better to assume we don't know anything.
5128 Known.resetAll();
5129 return;
5130 }
5131
5132 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5133
5134 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5135 Known = KnownFPClass(CFP->getValueAPF());
5136 return;
5137 }
5138
5140 Known.KnownFPClasses = fcPosZero;
5141 Known.SignBit = false;
5142 return;
5143 }
5144
5145 if (isa<PoisonValue>(V)) {
5146 Known.KnownFPClasses = fcNone;
5147 Known.SignBit = false;
5148 return;
5149 }
5150
5151 // Try to handle fixed width vector constants
5152 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5153 const Constant *CV = dyn_cast<Constant>(V);
5154 if (VFVTy && CV) {
5155 Known.KnownFPClasses = fcNone;
5156 bool SignBitAllZero = true;
5157 bool SignBitAllOne = true;
5158
5159 // For vectors, verify that each element is not NaN.
5160 unsigned NumElts = VFVTy->getNumElements();
5161 for (unsigned i = 0; i != NumElts; ++i) {
5162 if (!DemandedElts[i])
5163 continue;
5164
5165 Constant *Elt = CV->getAggregateElement(i);
5166 if (!Elt) {
5167 Known = KnownFPClass();
5168 return;
5169 }
5170 if (isa<PoisonValue>(Elt))
5171 continue;
5172 auto *CElt = dyn_cast<ConstantFP>(Elt);
5173 if (!CElt) {
5174 Known = KnownFPClass();
5175 return;
5176 }
5177
5178 const APFloat &C = CElt->getValueAPF();
5179 Known.KnownFPClasses |= C.classify();
5180 if (C.isNegative())
5181 SignBitAllZero = false;
5182 else
5183 SignBitAllOne = false;
5184 }
5185 if (SignBitAllOne != SignBitAllZero)
5186 Known.SignBit = SignBitAllOne;
5187 return;
5188 }
5189
5190 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5191 Known.KnownFPClasses = fcNone;
5192 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5193 Known |= CDS->getElementAsAPFloat(I).classify();
5194 return;
5195 }
5196
5197 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5198 // TODO: Handle complex aggregates
5199 Known.KnownFPClasses = fcNone;
5200 for (const Use &Op : CA->operands()) {
5201 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5202 if (!CFP) {
5203 Known = KnownFPClass();
5204 return;
5205 }
5206
5207 Known |= CFP->getValueAPF().classify();
5208 }
5209
5210 return;
5211 }
5212
5213 FPClassTest KnownNotFromFlags = fcNone;
5214 if (const auto *CB = dyn_cast<CallBase>(V))
5215 KnownNotFromFlags |= CB->getRetNoFPClass();
5216 else if (const auto *Arg = dyn_cast<Argument>(V))
5217 KnownNotFromFlags |= Arg->getNoFPClass();
5218
5219 const Operator *Op = dyn_cast<Operator>(V);
5221 if (FPOp->hasNoNaNs())
5222 KnownNotFromFlags |= fcNan;
5223 if (FPOp->hasNoInfs())
5224 KnownNotFromFlags |= fcInf;
5225 }
5226
5227 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5228 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5229
5230 // We no longer need to find out about these bits from inputs if we can
5231 // assume this from flags/attributes.
5232 InterestedClasses &= ~KnownNotFromFlags;
5233
5234 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5235 Known.knownNot(KnownNotFromFlags);
5236 if (!Known.SignBit && AssumedClasses.SignBit) {
5237 if (*AssumedClasses.SignBit)
5238 Known.signBitMustBeOne();
5239 else
5240 Known.signBitMustBeZero();
5241 }
5242 });
5243
5244 if (!Op)
5245 return;
5246
5247 // All recursive calls that increase depth must come after this.
5249 return;
5250
5251 const unsigned Opc = Op->getOpcode();
5252 switch (Opc) {
5253 case Instruction::FNeg: {
5254 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5255 Known, Q, Depth + 1);
5256 Known.fneg();
5257 break;
5258 }
5259 case Instruction::Select: {
5260 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5261 KnownFPClass Res;
5262 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5263 Depth + 1);
5264 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5265 Depth);
5266 return Res;
5267 };
5268 // Only known if known in both the LHS and RHS.
5269 Known =
5270 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5271 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5272 break;
5273 }
5274 case Instruction::Load: {
5275 const MDNode *NoFPClass =
5276 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5277 if (!NoFPClass)
5278 break;
5279
5280 ConstantInt *MaskVal =
5282 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5283 break;
5284 }
5285 case Instruction::Call: {
5286 const CallInst *II = cast<CallInst>(Op);
5287 const Intrinsic::ID IID = II->getIntrinsicID();
5288 switch (IID) {
5289 case Intrinsic::fabs: {
5290 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5291 // If we only care about the sign bit we don't need to inspect the
5292 // operand.
5293 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5294 InterestedClasses, Known, Q, Depth + 1);
5295 }
5296
5297 Known.fabs();
5298 break;
5299 }
5300 case Intrinsic::copysign: {
5301 KnownFPClass KnownSign;
5302
5303 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5304 Known, Q, Depth + 1);
5305 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5306 KnownSign, Q, Depth + 1);
5307 Known.copysign(KnownSign);
5308 break;
5309 }
5310 case Intrinsic::fma:
5311 case Intrinsic::fmuladd: {
5312 if ((InterestedClasses & fcNegative) == fcNone)
5313 break;
5314
5315 // FIXME: This should check isGuaranteedNotToBeUndef
5316 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5317 KnownFPClass KnownSrc, KnownAddend;
5318 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5319 InterestedClasses, KnownAddend, Q, Depth + 1);
5320 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5321 InterestedClasses, KnownSrc, Q, Depth + 1);
5322
5323 const Function *F = II->getFunction();
5324 const fltSemantics &FltSem =
5325 II->getType()->getScalarType()->getFltSemantics();
5327 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5328
5329 if (KnownNotFromFlags & fcNan) {
5330 KnownSrc.knownNot(fcNan);
5331 KnownAddend.knownNot(fcNan);
5332 }
5333
5334 if (KnownNotFromFlags & fcInf) {
5335 KnownSrc.knownNot(fcInf);
5336 KnownAddend.knownNot(fcInf);
5337 }
5338
5339 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5340 break;
5341 }
5342
5343 KnownFPClass KnownSrc[3];
5344 for (int I = 0; I != 3; ++I) {
5345 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5346 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5347 if (KnownSrc[I].isUnknown())
5348 return;
5349
5350 if (KnownNotFromFlags & fcNan)
5351 KnownSrc[I].knownNot(fcNan);
5352 if (KnownNotFromFlags & fcInf)
5353 KnownSrc[I].knownNot(fcInf);
5354 }
5355
5356 const Function *F = II->getFunction();
5357 const fltSemantics &FltSem =
5358 II->getType()->getScalarType()->getFltSemantics();
5360 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5361 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5362 break;
5363 }
5364 case Intrinsic::sqrt:
5365 case Intrinsic::experimental_constrained_sqrt: {
5366 KnownFPClass KnownSrc;
5367 FPClassTest InterestedSrcs = InterestedClasses;
5368 if (InterestedClasses & fcNan)
5369 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5370
5371 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5372 KnownSrc, Q, Depth + 1);
5373
5375
5376 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5377 if (!HasNSZ) {
5378 const Function *F = II->getFunction();
5379 const fltSemantics &FltSem =
5380 II->getType()->getScalarType()->getFltSemantics();
5381 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5382 }
5383
5384 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5385 if (HasNSZ)
5386 Known.knownNot(fcNegZero);
5387
5388 break;
5389 }
5390 case Intrinsic::sin: {
5391 KnownFPClass KnownSrc;
5392 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5393 KnownSrc, Q, Depth + 1);
5394 Known = KnownFPClass::sin(KnownSrc);
5395 break;
5396 }
5397 case Intrinsic::cos: {
5398 KnownFPClass KnownSrc;
5399 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5400 KnownSrc, Q, Depth + 1);
5401 Known = KnownFPClass::cos(KnownSrc);
5402 break;
5403 }
5404 case Intrinsic::tan: {
5405 KnownFPClass KnownSrc;
5406 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5407 KnownSrc, Q, Depth + 1);
5408 Known = KnownFPClass::tan(KnownSrc);
5409 break;
5410 }
5411 case Intrinsic::sinh: {
5412 KnownFPClass KnownSrc;
5413 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5414 KnownSrc, Q, Depth + 1);
5415 Known = KnownFPClass::sinh(KnownSrc);
5416 break;
5417 }
5418 case Intrinsic::cosh: {
5419 KnownFPClass KnownSrc;
5420 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5421 KnownSrc, Q, Depth + 1);
5422 Known = KnownFPClass::cosh(KnownSrc);
5423 break;
5424 }
5425 case Intrinsic::tanh: {
5426 KnownFPClass KnownSrc;
5427 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5428 KnownSrc, Q, Depth + 1);
5429 Known = KnownFPClass::tanh(KnownSrc);
5430 break;
5431 }
5432 case Intrinsic::asin: {
5433 KnownFPClass KnownSrc;
5434 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5435 KnownSrc, Q, Depth + 1);
5436 Known = KnownFPClass::asin(KnownSrc);
5437 break;
5438 }
5439 case Intrinsic::acos: {
5440 KnownFPClass KnownSrc;
5441 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5442 KnownSrc, Q, Depth + 1);
5443 Known = KnownFPClass::acos(KnownSrc);
5444 break;
5445 }
5446 case Intrinsic::atan: {
5447 KnownFPClass KnownSrc;
5448 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5449 KnownSrc, Q, Depth + 1);
5450 Known = KnownFPClass::atan(KnownSrc);
5451 break;
5452 }
5453 case Intrinsic::atan2: {
5454 FPClassTest InterestedY = InterestedClasses;
5455 FPClassTest InterestedX = InterestedClasses;
5456
5457 // We can rule out zero and subnormal if x cannot have a positive value.
5458 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5459 InterestedX |= fcPositive | fcNegSubnormal;
5460
5461 KnownFPClass KnownY, KnownX;
5462 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5463 KnownY, Q, Depth + 1);
5464 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5465 KnownX, Q, Depth + 1);
5466
5467 const Function *F = II->getFunction();
5469 F ? F->getDenormalMode(
5470 II->getType()->getScalarType()->getFltSemantics())
5472 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5473 break;
5474 }
5475 case Intrinsic::maxnum:
5476 case Intrinsic::minnum:
5477 case Intrinsic::minimum:
5478 case Intrinsic::maximum:
5479 case Intrinsic::minimumnum:
5480 case Intrinsic::maximumnum: {
5481 KnownFPClass KnownLHS, KnownRHS;
5482 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5483 KnownLHS, Q, Depth + 1);
5484 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5485 KnownRHS, Q, Depth + 1);
5486
5487 const Function *F = II->getFunction();
5488
5490 F ? F->getDenormalMode(
5491 II->getType()->getScalarType()->getFltSemantics())
5493
5494 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5495 Mode);
5496 break;
5497 }
5498 case Intrinsic::canonicalize: {
5499 KnownFPClass KnownSrc;
5500 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5501 KnownSrc, Q, Depth + 1);
5502
5503 const Function *F = II->getFunction();
5504 DenormalMode DenormMode =
5505 F ? F->getDenormalMode(
5506 II->getType()->getScalarType()->getFltSemantics())
5508 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5509 break;
5510 }
5511 case Intrinsic::vector_reduce_fmax:
5512 case Intrinsic::vector_reduce_fmin:
5513 case Intrinsic::vector_reduce_fmaximum:
5514 case Intrinsic::vector_reduce_fminimum:
5515 case Intrinsic::vector_reduce_fmaximumnum:
5516 case Intrinsic::vector_reduce_fminimumnum: {
5517 // reduce min/max will choose an element from one of the vector elements,
5518 // so we can infer and class information that is common to all elements.
5519 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5520 InterestedClasses, Q, Depth + 1);
5521 // Can only propagate sign if output is never NaN.
5522 if (!Known.isKnownNeverNaN())
5523 Known.SignBit.reset();
5524 break;
5525 }
5526 // reverse preserves all characteristics of the input vec's element.
5527 case Intrinsic::vector_reverse:
5529 II->getArgOperand(0), DemandedElts.reverseBits(),
5530 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5531 break;
5532 case Intrinsic::trunc:
5533 case Intrinsic::floor:
5534 case Intrinsic::ceil:
5535 case Intrinsic::rint:
5536 case Intrinsic::nearbyint:
5537 case Intrinsic::round:
5538 case Intrinsic::roundeven: {
5539 KnownFPClass KnownSrc;
5540 FPClassTest InterestedSrcs = InterestedClasses;
5541 if (InterestedSrcs & fcPosFinite)
5542 InterestedSrcs |= fcPosFinite;
5543 if (InterestedSrcs & fcNegFinite)
5544 InterestedSrcs |= fcNegFinite;
5545 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5546 KnownSrc, Q, Depth + 1);
5547
5549 KnownSrc, IID == Intrinsic::trunc,
5550 V->getType()->getScalarType()->isMultiUnitFPType());
5551 break;
5552 }
5553 case Intrinsic::exp:
5554 case Intrinsic::exp2:
5555 case Intrinsic::exp10:
5556 case Intrinsic::amdgcn_exp2: {
5557 KnownFPClass KnownSrc;
5558 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5559 KnownSrc, Q, Depth + 1);
5560
5561 Known = KnownFPClass::exp(KnownSrc);
5562
5563 Type *EltTy = II->getType()->getScalarType();
5564 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5565 Known.knownNot(fcSubnormal);
5566
5567 break;
5568 }
5569 case Intrinsic::fptrunc_round: {
5570 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5571 Q, Depth);
5572 break;
5573 }
5574 case Intrinsic::log:
5575 case Intrinsic::log10:
5576 case Intrinsic::log2:
5577 case Intrinsic::experimental_constrained_log:
5578 case Intrinsic::experimental_constrained_log10:
5579 case Intrinsic::experimental_constrained_log2:
5580 case Intrinsic::amdgcn_log: {
5581 Type *EltTy = II->getType()->getScalarType();
5582
5583 // log(+inf) -> +inf
5584 // log([+-]0.0) -> -inf
5585 // log(-inf) -> nan
5586 // log(-x) -> nan
5587 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5588 FPClassTest InterestedSrcs = InterestedClasses;
5589 if ((InterestedClasses & fcNegInf) != fcNone)
5590 InterestedSrcs |= fcZero | fcSubnormal;
5591 if ((InterestedClasses & fcNan) != fcNone)
5592 InterestedSrcs |= fcNan | fcNegative;
5593
5594 KnownFPClass KnownSrc;
5595 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5596 KnownSrc, Q, Depth + 1);
5597
5598 const Function *F = II->getFunction();
5599 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5601 Known = KnownFPClass::log(KnownSrc, Mode);
5602 }
5603
5604 break;
5605 }
5606 case Intrinsic::pow: {
5607 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5608 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5609 if (!WantNaN && !WantNegative)
5610 break;
5611
5612 FPClassTest InterestedLHS = fcNone;
5613 FPClassTest InterestedRHS = fcNone;
5614 if (WantNaN) {
5615 // pow may return NaN if one of the arguments is NaN. NaN may also be
5616 // produced from a negative, non-zero finite base and a non-integer
5617 // exponent.
5618 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5619 InterestedRHS |= fcNan;
5620 }
5621 if (WantNegative) {
5622 // A negative value is returned when a negative base is raised to an odd
5623 // integer power. Only normal values can be odd integers.
5624 InterestedLHS |= fcNegative;
5625 InterestedRHS |= fcNormal;
5626 }
5627
5628 KnownFPClass KnownLHS;
5629 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5630 KnownLHS, Q, Depth + 1);
5631
5632 // If the LHS is unknown, then querying the RHS is only useful for rare
5633 // edge cases.
5634 if (KnownLHS.isUnknown())
5635 break;
5636
5637 KnownFPClass KnownRHS;
5638 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5639 KnownRHS, Q, Depth + 1);
5640 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5641 break;
5642 }
5643 case Intrinsic::powi: {
5644 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5645 break;
5646
5647 // The exponent is always a scalar, even when raising a vector to a power.
5648 const Value *Exp = II->getArgOperand(1);
5649 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5650 KnownBits ExponentKnownBits(BitWidth);
5651 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5652
5653 FPClassTest InterestedSrcs = fcNone;
5654 if (InterestedClasses & fcNan)
5655 InterestedSrcs |= fcNan;
5656 if (!ExponentKnownBits.isZero()) {
5657 if (InterestedClasses & fcInf)
5658 InterestedSrcs |= fcFinite | fcInf;
5659 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5660 InterestedSrcs |= fcNegative;
5661 }
5662
5663 KnownFPClass KnownSrc;
5664 if (InterestedSrcs != fcNone)
5665 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5666 KnownSrc, Q, Depth + 1);
5667
5668 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5669 break;
5670 }
5671 case Intrinsic::ldexp: {
5672 KnownFPClass KnownSrc;
5673 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5674 KnownSrc, Q, Depth + 1);
5675 // Can refine inf/zero handling based on the exponent operand.
5676 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5677
5678 const Value *ExpArg = II->getArgOperand(1);
5679 ConstantRange ExpKnownRange =
5680 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5681 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5682 : ConstantRange::getFull(
5683 ExpArg->getType()->getScalarSizeInBits());
5684
5685 const fltSemantics &Flt =
5686 II->getType()->getScalarType()->getFltSemantics();
5687
5688 const Function *F = II->getFunction();
5690 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5691
5692 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5693 ExpKnownRange.getSignedMax(), Flt, Mode);
5694 break;
5695 }
5696 case Intrinsic::arithmetic_fence: {
5697 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5698 Known, Q, Depth + 1);
5699 break;
5700 }
5701 case Intrinsic::experimental_constrained_sitofp:
5702 case Intrinsic::experimental_constrained_uitofp:
5703 // Cannot produce nan
5704 Known.knownNot(fcNan);
5705
5706 // sitofp and uitofp turn into +0.0 for zero.
5707 Known.knownNot(fcNegZero);
5708
5709 // Integers cannot be subnormal
5710 Known.knownNot(fcSubnormal);
5711
5712 if (IID == Intrinsic::experimental_constrained_uitofp)
5713 Known.signBitMustBeZero();
5714
5715 // TODO: Copy inf handling from instructions
5716 break;
5717
5718 case Intrinsic::amdgcn_fract: {
5719 Known.knownNot(fcInf);
5720
5721 if (InterestedClasses & fcNan) {
5722 KnownFPClass KnownSrc;
5723 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5724 InterestedClasses, KnownSrc, Q, Depth + 1);
5725
5726 if (KnownSrc.isKnownNeverInfOrNaN())
5727 Known.knownNot(fcNan);
5728 else if (KnownSrc.isKnownNever(fcSNan))
5729 Known.knownNot(fcSNan);
5730 }
5731
5732 break;
5733 }
5734 case Intrinsic::amdgcn_rcp: {
5735 KnownFPClass KnownSrc;
5736 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5737 KnownSrc, Q, Depth + 1);
5738
5739 Known.propagateNonNaN(KnownSrc);
5740
5741 Type *EltTy = II->getType()->getScalarType();
5742
5743 // f32 denormal always flushed.
5744 if (EltTy->isFloatTy()) {
5745 Known.knownNot(fcSubnormal);
5746 KnownSrc.knownNot(fcSubnormal);
5747 }
5748
5749 if (KnownSrc.isKnownNever(fcNegative))
5750 Known.knownNot(fcNegative);
5751 if (KnownSrc.isKnownNever(fcPositive))
5752 Known.knownNot(fcPositive);
5753
5754 if (const Function *F = II->getFunction()) {
5755 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5756 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5757 Known.knownNot(fcPosInf);
5758 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5759 Known.knownNot(fcNegInf);
5760 }
5761
5762 break;
5763 }
5764 case Intrinsic::amdgcn_rsq: {
5765 KnownFPClass KnownSrc;
5766 // The only negative value that can be returned is -inf for -0 inputs.
5768
5769 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5770 KnownSrc, Q, Depth + 1);
5771
5772 // Negative -> nan
5773 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5774 Known.knownNot(fcNan);
5775 else if (KnownSrc.isKnownNever(fcSNan))
5776 Known.knownNot(fcSNan);
5777
5778 // +inf -> +0
5779 if (KnownSrc.isKnownNeverPosInfinity())
5780 Known.knownNot(fcPosZero);
5781
5782 Type *EltTy = II->getType()->getScalarType();
5783
5784 // f32 denormal always flushed.
5785 if (EltTy->isFloatTy())
5786 Known.knownNot(fcPosSubnormal);
5787
5788 if (const Function *F = II->getFunction()) {
5789 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5790
5791 // -0 -> -inf
5792 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5793 Known.knownNot(fcNegInf);
5794
5795 // +0 -> +inf
5796 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5797 Known.knownNot(fcPosInf);
5798 }
5799
5800 break;
5801 }
5802 case Intrinsic::amdgcn_trig_preop: {
5803 // Always returns a value [0, 1)
5804 Known.knownNot(fcNan | fcInf | fcNegative);
5805 break;
5806 }
5807 case Intrinsic::convert_from_arbitrary_fp: {
5808 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5809 StringRef FormatStr = cast<MDString>(MD)->getString();
5810
5811 const fltSemantics *SrcSemantics =
5813 if (!SrcSemantics)
5814 break;
5815
5816 const fltSemantics DstSemantics =
5817 II->getType()->getScalarType()->getFltSemantics();
5818
5819 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5820 Known.knownNot(fcNan);
5821
5822 // fcInf can only be cleared if the source format has no Inf encoding
5823 // and the dst max exp can accommodate src max exp.
5824 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5825 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5826 APFloat::semanticsMaxExponent(DstSemantics))
5827 Known.knownNot(fcInf);
5828
5829 // Check and clear all neg flags for formats that do not have signed
5830 // representation.
5831 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5832 Known.knownNot(fcNegative);
5833
5834 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5835 // zero.
5836 if (!APFloat::semanticsHasZero(*SrcSemantics))
5837 Known.knownNot(fcZero);
5838 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5839 Known.knownNot(fcNegZero);
5840
5841 // If src lands normally in dest, the result can never be subnormal.
5842 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5843 Known.knownNot(fcSubnormal);
5844 break;
5845 }
5846 default:
5847 break;
5848 }
5849
5850 break;
5851 }
5852 case Instruction::FAdd:
5853 case Instruction::FSub: {
5854 KnownFPClass KnownLHS, KnownRHS;
5855 bool WantNegative =
5856 Op->getOpcode() == Instruction::FAdd &&
5857 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5858 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5859 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5860
5861 if (!WantNaN && !WantNegative && !WantNegZero)
5862 break;
5863
5864 FPClassTest InterestedSrcs = InterestedClasses;
5865 if (WantNegative)
5866 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5867 if (InterestedClasses & fcNan)
5868 InterestedSrcs |= fcInf;
5869 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5870 KnownRHS, Q, Depth + 1);
5871
5872 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5873 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5874 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5875 Depth + 1);
5876 if (Self)
5877 KnownLHS = KnownRHS;
5878
5879 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5880 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5881 WantNegZero || Opc == Instruction::FSub) {
5882
5883 // FIXME: Context function should always be passed in separately
5884 const Function *F = cast<Instruction>(Op)->getFunction();
5885 const fltSemantics &FltSem =
5886 Op->getType()->getScalarType()->getFltSemantics();
5888 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5889
5890 if (Self && Opc == Instruction::FAdd) {
5891 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5892 } else {
5893 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5894 // there's no point.
5895
5896 if (!Self) {
5897 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5898 KnownLHS, Q, Depth + 1);
5899 }
5900
5901 Known = Opc == Instruction::FAdd
5902 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5903 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5904 }
5905 }
5906
5907 break;
5908 }
5909 case Instruction::FMul: {
5910 const Function *F = cast<Instruction>(Op)->getFunction();
5912 F ? F->getDenormalMode(
5913 Op->getType()->getScalarType()->getFltSemantics())
5915
5916 Value *LHS = Op->getOperand(0);
5917 Value *RHS = Op->getOperand(1);
5918 // X * X is always non-negative or a NaN.
5919 // FIXME: Should check isGuaranteedNotToBeUndef
5920 if (LHS == RHS) {
5921 KnownFPClass KnownSrc;
5922 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5923 Depth + 1);
5924 Known = KnownFPClass::square(KnownSrc, Mode);
5925 break;
5926 }
5927
5928 KnownFPClass KnownLHS, KnownRHS;
5929
5930 const APFloat *CRHS;
5931 if (match(RHS, m_APFloat(CRHS))) {
5932 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5933 Depth + 1);
5934 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5935 } else {
5936 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5937 Depth + 1);
5938 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5939 // additional not-nan if the addend is known-not negative infinity if the
5940 // multiply is known-not infinity.
5941
5942 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5943 Depth + 1);
5944 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5945 }
5946
5947 /// Propgate no-infs if the other source is known smaller than one, such
5948 /// that this cannot introduce overflow.
5949 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5950 Known.knownNot(fcInf);
5951 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5952 Known.knownNot(fcInf);
5953
5954 break;
5955 }
5956 case Instruction::FDiv: {
5957 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
5958
5959 const Function *F = cast<Instruction>(Op)->getFunction();
5960 const fltSemantics &FltSem =
5961 Op->getType()->getScalarType()->getFltSemantics();
5963 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5964
5965 if (Op->getOperand(0) == Op->getOperand(1) &&
5966 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
5967 // X / X is always exactly 1.0 or a NaN.
5968 Known.KnownFPClasses = fcNan | fcPosNormal;
5969
5970 if (!WantNan)
5971 break;
5972
5973 KnownFPClass KnownSrc;
5974 computeKnownFPClass(Op->getOperand(0), DemandedElts,
5975 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
5976 Depth + 1);
5977
5978 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
5979 break;
5980 }
5981
5982 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5983 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
5984 if (!WantNan && !WantNegative && !WantPositive)
5985 break;
5986
5987 KnownFPClass KnownLHS, KnownRHS;
5988 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
5989 Q, Depth + 1);
5990
5991 bool KnowSomethingUseful =
5992 KnownRHS.isKnownNeverNaN() ||
5995
5996 if (KnowSomethingUseful)
5997 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
5998 Q, Depth + 1);
5999
6000 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6001 break;
6002 }
6003 case Instruction::FRem: {
6004 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6005
6006 Known.knownNot(fcInf);
6007
6008 const Function *F = cast<Instruction>(Op)->getFunction();
6010 F ? F->getDenormalMode(
6011 Op->getType()->getScalarType()->getFltSemantics())
6013
6014 if (Op->getOperand(0) == Op->getOperand(1) &&
6015 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6016 // X % X is always exactly [+-]0.0 or a NaN.
6017 Known.KnownFPClasses = fcNan | fcZero;
6018
6019 if (!WantNan)
6020 break;
6021
6022 KnownFPClass KnownSrc;
6023 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6024 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6025 Depth + 1);
6026
6027 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6028 break;
6029 }
6030
6031 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6032 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6033 if (!WantNan && !WantNegative && !WantPositive)
6034 break;
6035
6036 KnownFPClass KnownLHS, KnownRHS;
6037 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6038 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6039 Depth + 1);
6040
6041 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6042 KnownRHS.isKnownNever(fcNegative) ||
6043 KnownRHS.isKnownNever(fcPositive);
6044
6045 if (KnowSomethingUseful || WantPositive)
6046 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6047 Q, Depth + 1);
6048
6049 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6050
6051 break;
6052 }
6053 case Instruction::FPExt: {
6054 KnownFPClass KnownSrc;
6055 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6056 KnownSrc, Q, Depth + 1);
6057
6058 const fltSemantics &DstTy =
6059 Op->getType()->getScalarType()->getFltSemantics();
6060 const fltSemantics &SrcTy =
6061 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6062
6063 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6064 break;
6065 }
6066 case Instruction::FPTrunc: {
6067 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6068 Depth);
6069 break;
6070 }
6071 case Instruction::SIToFP:
6072 case Instruction::UIToFP: {
6073 // Cannot produce nan
6074 Known.knownNot(fcNan);
6075
6076 // Integers cannot be subnormal
6077 Known.knownNot(fcSubnormal);
6078
6079 // sitofp and uitofp turn into +0.0 for zero.
6080 Known.knownNot(fcNegZero);
6081
6082 // UIToFP is always non-negative regardless of known bits.
6083 if (Op->getOpcode() == Instruction::UIToFP)
6084 Known.signBitMustBeZero();
6085
6086 // Only compute known bits if we can learn something useful from them.
6087 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6088 break;
6089
6090 KnownBits IntKnown =
6091 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6092
6093 // If the integer is non-zero, the result cannot be +0.0
6094 if (IntKnown.isNonZero())
6095 Known.knownNot(fcPosZero);
6096
6097 if (Op->getOpcode() == Instruction::SIToFP) {
6098 // If the signed integer is known non-negative, the result is
6099 // non-negative. If the signed integer is known negative, the result is
6100 // negative.
6101 if (IntKnown.isNonNegative()) {
6102 Known.signBitMustBeZero();
6103 } else if (IntKnown.isNegative()) {
6104 Known.signBitMustBeOne();
6105 }
6106 }
6107
6108 // Guard kept for ilogb()
6109 if (InterestedClasses & fcInf) {
6110 // Get width of largest magnitude integer known.
6111 // This still works for a signed minimum value because the largest FP
6112 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6113 int IntSize = IntKnown.getBitWidth();
6114 if (Op->getOpcode() == Instruction::UIToFP)
6115 IntSize -= IntKnown.countMinLeadingZeros();
6116 else if (Op->getOpcode() == Instruction::SIToFP)
6117 IntSize -= IntKnown.countMinSignBits();
6118
6119 // If the exponent of the largest finite FP value can hold the largest
6120 // integer, the result of the cast must be finite.
6121 Type *FPTy = Op->getType()->getScalarType();
6122 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6123 Known.knownNot(fcInf);
6124 }
6125
6126 break;
6127 }
6128 case Instruction::ExtractElement: {
6129 // Look through extract element. If the index is non-constant or
6130 // out-of-range demand all elements, otherwise just the extracted element.
6131 const Value *Vec = Op->getOperand(0);
6132
6133 APInt DemandedVecElts;
6134 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6135 unsigned NumElts = VecTy->getNumElements();
6136 DemandedVecElts = APInt::getAllOnes(NumElts);
6137 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6138 if (CIdx && CIdx->getValue().ult(NumElts))
6139 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6140 } else {
6141 DemandedVecElts = APInt(1, 1);
6142 }
6143
6144 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6145 Q, Depth + 1);
6146 }
6147 case Instruction::InsertElement: {
6148 if (isa<ScalableVectorType>(Op->getType()))
6149 return;
6150
6151 const Value *Vec = Op->getOperand(0);
6152 const Value *Elt = Op->getOperand(1);
6153 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6154 unsigned NumElts = DemandedElts.getBitWidth();
6155 APInt DemandedVecElts = DemandedElts;
6156 bool NeedsElt = true;
6157 // If we know the index we are inserting to, clear it from Vec check.
6158 if (CIdx && CIdx->getValue().ult(NumElts)) {
6159 DemandedVecElts.clearBit(CIdx->getZExtValue());
6160 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6161 }
6162
6163 // Do we demand the inserted element?
6164 if (NeedsElt) {
6165 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6166 // If we don't know any bits, early out.
6167 if (Known.isUnknown())
6168 break;
6169 } else {
6170 Known.KnownFPClasses = fcNone;
6171 }
6172
6173 // Do we need anymore elements from Vec?
6174 if (!DemandedVecElts.isZero()) {
6175 KnownFPClass Known2;
6176 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6177 Depth + 1);
6178 Known |= Known2;
6179 }
6180
6181 break;
6182 }
6183 case Instruction::ShuffleVector: {
6184 // Handle vector splat idiom
6185 if (Value *Splat = getSplatValue(V)) {
6186 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6187 break;
6188 }
6189
6190 // For undef elements, we don't know anything about the common state of
6191 // the shuffle result.
6192 APInt DemandedLHS, DemandedRHS;
6193 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6194 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6195 return;
6196
6197 if (!!DemandedLHS) {
6198 const Value *LHS = Shuf->getOperand(0);
6199 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6200 Depth + 1);
6201
6202 // If we don't know any bits, early out.
6203 if (Known.isUnknown())
6204 break;
6205 } else {
6206 Known.KnownFPClasses = fcNone;
6207 }
6208
6209 if (!!DemandedRHS) {
6210 KnownFPClass Known2;
6211 const Value *RHS = Shuf->getOperand(1);
6212 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6213 Depth + 1);
6214 Known |= Known2;
6215 }
6216
6217 break;
6218 }
6219 case Instruction::ExtractValue: {
6220 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6221 ArrayRef<unsigned> Indices = Extract->getIndices();
6222 const Value *Src = Extract->getAggregateOperand();
6223 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6224 Indices[0] == 0) {
6225 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6226 switch (II->getIntrinsicID()) {
6227 case Intrinsic::frexp: {
6228 Known.knownNot(fcSubnormal);
6229
6230 KnownFPClass KnownSrc;
6231 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6232 InterestedClasses, KnownSrc, Q, Depth + 1);
6233
6234 const Function *F = cast<Instruction>(Op)->getFunction();
6235 const fltSemantics &FltSem =
6236 Op->getType()->getScalarType()->getFltSemantics();
6237
6239 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6240 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6241 return;
6242 }
6243 default:
6244 break;
6245 }
6246 }
6247 }
6248
6249 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6250 Depth + 1);
6251 break;
6252 }
6253 case Instruction::PHI: {
6254 const PHINode *P = cast<PHINode>(Op);
6255 // Unreachable blocks may have zero-operand PHI nodes.
6256 if (P->getNumIncomingValues() == 0)
6257 break;
6258
6259 // Otherwise take the unions of the known bit sets of the operands,
6260 // taking conservative care to avoid excessive recursion.
6261 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6262
6263 if (Depth < PhiRecursionLimit) {
6264 // Skip if every incoming value references to ourself.
6265 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6266 break;
6267
6268 bool First = true;
6269
6270 for (const Use &U : P->operands()) {
6271 Value *IncValue;
6272 Instruction *CxtI;
6273 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6274 // Skip direct self references.
6275 if (IncValue == P)
6276 continue;
6277
6278 KnownFPClass KnownSrc;
6279 // Recurse, but cap the recursion to two levels, because we don't want
6280 // to waste time spinning around in loops. We need at least depth 2 to
6281 // detect known sign bits.
6282 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6284 PhiRecursionLimit);
6285
6286 if (First) {
6287 Known = KnownSrc;
6288 First = false;
6289 } else {
6290 Known |= KnownSrc;
6291 }
6292
6293 if (Known.KnownFPClasses == fcAllFlags)
6294 break;
6295 }
6296 }
6297
6298 // Look for the case of a for loop which has a positive
6299 // initial value and is incremented by a squared value.
6300 // This will propagate sign information out of such loops.
6301 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6302 break;
6303 for (unsigned I = 0; I < 2; I++) {
6304 Value *RecurValue = P->getIncomingValue(1 - I);
6306 if (!II)
6307 continue;
6308 Value *R, *L, *Init;
6309 PHINode *PN;
6311 PN == P) {
6312 switch (II->getIntrinsicID()) {
6313 case Intrinsic::fma:
6314 case Intrinsic::fmuladd: {
6315 KnownFPClass KnownStart;
6316 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6317 Q, Depth + 1);
6318 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6319 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6321 break;
6322 }
6323 }
6324 }
6325 }
6326 break;
6327 }
6328 case Instruction::BitCast: {
6329 const Value *Src;
6330 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6331 !Src->getType()->isIntOrIntVectorTy())
6332 break;
6333
6334 const Type *Ty = Op->getType();
6335
6336 Value *CastLHS, *CastRHS;
6337
6338 // Match bitcast(umax(bitcast(a), bitcast(b)))
6339 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6340 m_BitCast(m_Value(CastRHS)))) &&
6341 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6342 KnownFPClass KnownLHS, KnownRHS;
6343 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6344 Depth + 1);
6345 if (!KnownRHS.isUnknown()) {
6346 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6347 Q, Depth + 1);
6348 Known = KnownLHS | KnownRHS;
6349 }
6350
6351 return;
6352 }
6353
6354 const Type *EltTy = Ty->getScalarType();
6355 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6356 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6357
6359 break;
6360 }
6361 default:
6362 break;
6363 }
6364}
6365
6367 const APInt &DemandedElts,
6368 FPClassTest InterestedClasses,
6369 const SimplifyQuery &SQ,
6370 unsigned Depth) {
6371 KnownFPClass KnownClasses;
6372 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6373 Depth);
6374 return KnownClasses;
6375}
6376
6378 FPClassTest InterestedClasses,
6379 const SimplifyQuery &SQ,
6380 unsigned Depth) {
6382 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6383 return Known;
6384}
6385
6387 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6388 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6389 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6390 return computeKnownFPClass(V, InterestedClasses,
6391 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6392 Depth);
6393}
6394
6396llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6397 FastMathFlags FMF, FPClassTest InterestedClasses,
6398 const SimplifyQuery &SQ, unsigned Depth) {
6399 if (FMF.noNaNs())
6400 InterestedClasses &= ~fcNan;
6401 if (FMF.noInfs())
6402 InterestedClasses &= ~fcInf;
6403
6404 KnownFPClass Result =
6405 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6406
6407 if (FMF.noNaNs())
6408 Result.KnownFPClasses &= ~fcNan;
6409 if (FMF.noInfs())
6410 Result.KnownFPClasses &= ~fcInf;
6411 return Result;
6412}
6413
6415 FPClassTest InterestedClasses,
6416 const SimplifyQuery &SQ,
6417 unsigned Depth) {
6418 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6419 APInt DemandedElts =
6420 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6421 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6422 Depth);
6423}
6424
6426 unsigned Depth) {
6428 return Known.isKnownNeverNegZero();
6429}
6430
6432 unsigned Depth) {
6435 return Known.cannotBeOrderedLessThanZero();
6436}
6437
6439 unsigned Depth) {
6441 return Known.isKnownNeverInfinity();
6442}
6443
6444/// Return true if the floating-point value can never contain a NaN or infinity.
6446 unsigned Depth) {
6448 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6449}
6450
6451/// Return true if the floating-point scalar value is not a NaN or if the
6452/// floating-point vector value has no NaN elements. Return false if a value
6453/// could ever be NaN.
6455 unsigned Depth) {
6457 return Known.isKnownNeverNaN();
6458}
6459
6460/// Return false if we can prove that the specified FP value's sign bit is 0.
6461/// Return true if we can prove that the specified FP value's sign bit is 1.
6462/// Otherwise return std::nullopt.
6463std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6464 const SimplifyQuery &SQ,
6465 unsigned Depth) {
6467 return Known.SignBit;
6468}
6469
6471 auto *User = cast<Instruction>(U.getUser());
6472 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6473 if (FPOp->hasNoSignedZeros())
6474 return true;
6475 }
6476
6477 switch (User->getOpcode()) {
6478 case Instruction::FPToSI:
6479 case Instruction::FPToUI:
6480 return true;
6481 case Instruction::FCmp:
6482 // fcmp treats both positive and negative zero as equal.
6483 return true;
6484 case Instruction::Call:
6485 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6486 switch (II->getIntrinsicID()) {
6487 case Intrinsic::fabs:
6488 return true;
6489 case Intrinsic::copysign:
6490 return U.getOperandNo() == 0;
6491 case Intrinsic::is_fpclass: {
6492 auto Test =
6493 static_cast<FPClassTest>(
6494 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6497 }
6498 default:
6499 return false;
6500 }
6501 }
6502 return false;
6503 default:
6504 return false;
6505 }
6506}
6507
6509 auto *User = cast<Instruction>(U.getUser());
6510 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6511 if (FPOp->hasNoNaNs())
6512 return true;
6513 }
6514
6515 switch (User->getOpcode()) {
6516 case Instruction::FPToSI:
6517 case Instruction::FPToUI:
6518 return true;
6519 // Proper FP math operations ignore the sign bit of NaN.
6520 case Instruction::FAdd:
6521 case Instruction::FSub:
6522 case Instruction::FMul:
6523 case Instruction::FDiv:
6524 case Instruction::FRem:
6525 case Instruction::FPTrunc:
6526 case Instruction::FPExt:
6527 case Instruction::FCmp:
6528 return true;
6529 // Bitwise FP operations should preserve the sign bit of NaN.
6530 case Instruction::FNeg:
6531 case Instruction::Select:
6532 case Instruction::PHI:
6533 return false;
6534 case Instruction::Ret:
6535 return User->getFunction()->getAttributes().getRetNoFPClass() &
6537 case Instruction::Call:
6538 case Instruction::Invoke: {
6539 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6540 switch (II->getIntrinsicID()) {
6541 case Intrinsic::fabs:
6542 return true;
6543 case Intrinsic::copysign:
6544 return U.getOperandNo() == 0;
6545 // Other proper FP math intrinsics ignore the sign bit of NaN.
6546 case Intrinsic::maxnum:
6547 case Intrinsic::minnum:
6548 case Intrinsic::maximum:
6549 case Intrinsic::minimum:
6550 case Intrinsic::maximumnum:
6551 case Intrinsic::minimumnum:
6552 case Intrinsic::canonicalize:
6553 case Intrinsic::fma:
6554 case Intrinsic::fmuladd:
6555 case Intrinsic::sqrt:
6556 case Intrinsic::pow:
6557 case Intrinsic::powi:
6558 case Intrinsic::fptoui_sat:
6559 case Intrinsic::fptosi_sat:
6560 case Intrinsic::is_fpclass:
6561 return true;
6562 default:
6563 return false;
6564 }
6565 }
6566
6567 FPClassTest NoFPClass =
6568 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6569 return NoFPClass & FPClassTest::fcNan;
6570 }
6571 default:
6572 return false;
6573 }
6574}
6575
6577 FastMathFlags FMF) {
6578 if (isa<PoisonValue>(V))
6579 return true;
6580 if (isa<UndefValue>(V))
6581 return false;
6582
6583 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6584 return true;
6585
6587 if (!I)
6588 return false;
6589
6590 switch (I->getOpcode()) {
6591 case Instruction::SIToFP:
6592 case Instruction::UIToFP:
6593 // TODO: Could check nofpclass(inf) on incoming argument
6594 if (FMF.noInfs())
6595 return true;
6596
6597 // Need to check int size cannot produce infinity, which computeKnownFPClass
6598 // knows how to do already.
6599 return isKnownNeverInfinity(I, SQ);
6600 case Instruction::Call: {
6601 const CallInst *CI = cast<CallInst>(I);
6602 switch (CI->getIntrinsicID()) {
6603 case Intrinsic::trunc:
6604 case Intrinsic::floor:
6605 case Intrinsic::ceil:
6606 case Intrinsic::rint:
6607 case Intrinsic::nearbyint:
6608 case Intrinsic::round:
6609 case Intrinsic::roundeven:
6610 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6611 default:
6612 break;
6613 }
6614
6615 break;
6616 }
6617 default:
6618 break;
6619 }
6620
6621 return false;
6622}
6623
6625
6626 // All byte-wide stores are splatable, even of arbitrary variables.
6627 if (V->getType()->isIntegerTy(8))
6628 return V;
6629
6630 LLVMContext &Ctx = V->getContext();
6631
6632 // Undef don't care.
6633 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6634 if (isa<UndefValue>(V))
6635 return UndefInt8;
6636
6637 // Return poison for zero-sized type.
6638 if (DL.getTypeStoreSize(V->getType()).isZero())
6639 return PoisonValue::get(Type::getInt8Ty(Ctx));
6640
6642 if (!C) {
6643 // Conceptually, we could handle things like:
6644 // %a = zext i8 %X to i16
6645 // %b = shl i16 %a, 8
6646 // %c = or i16 %a, %b
6647 // but until there is an example that actually needs this, it doesn't seem
6648 // worth worrying about.
6649 return nullptr;
6650 }
6651
6652 // Handle 'null' ConstantArrayZero etc.
6653 if (C->isNullValue())
6655
6656 // Constant floating-point values can be handled as integer values if the
6657 // corresponding integer value is "byteable". An important case is 0.0.
6658 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6659 Type *ScalarTy = CFP->getType()->getScalarType();
6660 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6661 return isBytewiseValue(
6662 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6663
6664 // Don't handle long double formats, which have strange constraints.
6665 return nullptr;
6666 }
6667
6668 // We can handle constant integers that are multiple of 8 bits.
6669 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6670 if (CI->getBitWidth() % 8 == 0) {
6671 if (!CI->getValue().isSplat(8))
6672 return nullptr;
6673 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6674 }
6675 }
6676
6677 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6678 if (CE->getOpcode() == Instruction::IntToPtr) {
6679 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6680 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6682 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6683 return isBytewiseValue(Op, DL);
6684 }
6685 }
6686 }
6687
6688 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6689 if (LHS == RHS)
6690 return LHS;
6691 if (!LHS || !RHS)
6692 return nullptr;
6693 if (LHS == UndefInt8)
6694 return RHS;
6695 if (RHS == UndefInt8)
6696 return LHS;
6697 return nullptr;
6698 };
6699
6701 Value *Val = UndefInt8;
6702 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6703 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6704 return nullptr;
6705 return Val;
6706 }
6707
6709 Value *Val = UndefInt8;
6710 for (Value *Op : C->operands())
6711 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6712 return nullptr;
6713 return Val;
6714 }
6715
6716 // Don't try to handle the handful of other constants.
6717 return nullptr;
6718}
6719
6720// This is the recursive version of BuildSubAggregate. It takes a few different
6721// arguments. Idxs is the index within the nested struct From that we are
6722// looking at now (which is of type IndexedType). IdxSkip is the number of
6723// indices from Idxs that should be left out when inserting into the resulting
6724// struct. To is the result struct built so far, new insertvalue instructions
6725// build on that.
6726static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6728 unsigned IdxSkip,
6729 BasicBlock::iterator InsertBefore) {
6730 StructType *STy = dyn_cast<StructType>(IndexedType);
6731 if (STy) {
6732 // Save the original To argument so we can modify it
6733 Value *OrigTo = To;
6734 // General case, the type indexed by Idxs is a struct
6735 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6736 // Process each struct element recursively
6737 Idxs.push_back(i);
6738 Value *PrevTo = To;
6739 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6740 InsertBefore);
6741 Idxs.pop_back();
6742 if (!To) {
6743 // Couldn't find any inserted value for this index? Cleanup
6744 while (PrevTo != OrigTo) {
6746 PrevTo = Del->getAggregateOperand();
6747 Del->eraseFromParent();
6748 }
6749 // Stop processing elements
6750 break;
6751 }
6752 }
6753 // If we successfully found a value for each of our subaggregates
6754 if (To)
6755 return To;
6756 }
6757 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6758 // the struct's elements had a value that was inserted directly. In the latter
6759 // case, perhaps we can't determine each of the subelements individually, but
6760 // we might be able to find the complete struct somewhere.
6761
6762 // Find the value that is at that particular spot
6763 Value *V = FindInsertedValue(From, Idxs);
6764
6765 if (!V)
6766 return nullptr;
6767
6768 // Insert the value in the new (sub) aggregate
6769 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6770 InsertBefore);
6771}
6772
6773// This helper takes a nested struct and extracts a part of it (which is again a
6774// struct) into a new value. For example, given the struct:
6775// { a, { b, { c, d }, e } }
6776// and the indices "1, 1" this returns
6777// { c, d }.
6778//
6779// It does this by inserting an insertvalue for each element in the resulting
6780// struct, as opposed to just inserting a single struct. This will only work if
6781// each of the elements of the substruct are known (ie, inserted into From by an
6782// insertvalue instruction somewhere).
6783//
6784// All inserted insertvalue instructions are inserted before InsertBefore
6786 BasicBlock::iterator InsertBefore) {
6787 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6788 idx_range);
6789 Value *To = PoisonValue::get(IndexedType);
6790 SmallVector<unsigned, 10> Idxs(idx_range);
6791 unsigned IdxSkip = Idxs.size();
6792
6793 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6794}
6795
6796/// Given an aggregate and a sequence of indices, see if the scalar value
6797/// indexed is already around as a register, for example if it was inserted
6798/// directly into the aggregate.
6799///
6800/// If InsertBefore is not null, this function will duplicate (modified)
6801/// insertvalues when a part of a nested struct is extracted.
6802Value *
6804 std::optional<BasicBlock::iterator> InsertBefore) {
6805 // Nothing to index? Just return V then (this is useful at the end of our
6806 // recursion).
6807 if (idx_range.empty())
6808 return V;
6809 // We have indices, so V should have an indexable type.
6810 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6811 "Not looking at a struct or array?");
6812 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6813 "Invalid indices for type?");
6814
6815 if (Constant *C = dyn_cast<Constant>(V)) {
6816 C = C->getAggregateElement(idx_range[0]);
6817 if (!C) return nullptr;
6818 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6819 }
6820
6822 // Loop the indices for the insertvalue instruction in parallel with the
6823 // requested indices
6824 const unsigned *req_idx = idx_range.begin();
6825 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6826 i != e; ++i, ++req_idx) {
6827 if (req_idx == idx_range.end()) {
6828 // We can't handle this without inserting insertvalues
6829 if (!InsertBefore)
6830 return nullptr;
6831
6832 // The requested index identifies a part of a nested aggregate. Handle
6833 // this specially. For example,
6834 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6835 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6836 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6837 // This can be changed into
6838 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6839 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6840 // which allows the unused 0,0 element from the nested struct to be
6841 // removed.
6842 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6843 *InsertBefore);
6844 }
6845
6846 // This insert value inserts something else than what we are looking for.
6847 // See if the (aggregate) value inserted into has the value we are
6848 // looking for, then.
6849 if (*req_idx != *i)
6850 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6851 InsertBefore);
6852 }
6853 // If we end up here, the indices of the insertvalue match with those
6854 // requested (though possibly only partially). Now we recursively look at
6855 // the inserted value, passing any remaining indices.
6856 return FindInsertedValue(I->getInsertedValueOperand(),
6857 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6858 }
6859
6861 // If we're extracting a value from an aggregate that was extracted from
6862 // something else, we can extract from that something else directly instead.
6863 // However, we will need to chain I's indices with the requested indices.
6864
6865 // Calculate the number of indices required
6866 unsigned size = I->getNumIndices() + idx_range.size();
6867 // Allocate some space to put the new indices in
6869 Idxs.reserve(size);
6870 // Add indices from the extract value instruction
6871 Idxs.append(I->idx_begin(), I->idx_end());
6872
6873 // Add requested indices
6874 Idxs.append(idx_range.begin(), idx_range.end());
6875
6876 assert(Idxs.size() == size
6877 && "Number of indices added not correct?");
6878
6879 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6880 }
6881 // Otherwise, we don't know (such as, extracting from a function return value
6882 // or load instruction)
6883 return nullptr;
6884}
6885
6886// If V refers to an initialized global constant, set Slice either to
6887// its initializer if the size of its elements equals ElementSize, or,
6888// for ElementSize == 8, to its representation as an array of unsiged
6889// char. Return true on success.
6890// Offset is in the unit "nr of ElementSize sized elements".
6893 unsigned ElementSize, uint64_t Offset) {
6894 assert(V && "V should not be null.");
6895 assert((ElementSize % 8) == 0 &&
6896 "ElementSize expected to be a multiple of the size of a byte.");
6897 unsigned ElementSizeInBytes = ElementSize / 8;
6898
6899 // Drill down into the pointer expression V, ignoring any intervening
6900 // casts, and determine the identity of the object it references along
6901 // with the cumulative byte offset into it.
6902 const GlobalVariable *GV =
6904 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6905 // Fail if V is not based on constant global object.
6906 return false;
6907
6908 const DataLayout &DL = GV->getDataLayout();
6909 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6910
6911 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6912 /*AllowNonInbounds*/ true))
6913 // Fail if a constant offset could not be determined.
6914 return false;
6915
6916 uint64_t StartIdx = Off.getLimitedValue();
6917 if (StartIdx == UINT64_MAX)
6918 // Fail if the constant offset is excessive.
6919 return false;
6920
6921 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6922 // elements. Simply bail out if that isn't possible.
6923 if ((StartIdx % ElementSizeInBytes) != 0)
6924 return false;
6925
6926 Offset += StartIdx / ElementSizeInBytes;
6927 ConstantDataArray *Array = nullptr;
6928 ArrayType *ArrayTy = nullptr;
6929
6930 if (GV->getInitializer()->isNullValue()) {
6931 Type *GVTy = GV->getValueType();
6932 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6933 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6934
6935 Slice.Array = nullptr;
6936 Slice.Offset = 0;
6937 // Return an empty Slice for undersized constants to let callers
6938 // transform even undefined library calls into simpler, well-defined
6939 // expressions. This is preferable to making the calls although it
6940 // prevents sanitizers from detecting such calls.
6941 Slice.Length = Length < Offset ? 0 : Length - Offset;
6942 return true;
6943 }
6944
6945 auto *Init = const_cast<Constant *>(GV->getInitializer());
6946 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6947 Type *InitElTy = ArrayInit->getElementType();
6948 if (InitElTy->isIntegerTy(ElementSize)) {
6949 // If Init is an initializer for an array of the expected type
6950 // and size, use it as is.
6951 Array = ArrayInit;
6952 ArrayTy = ArrayInit->getType();
6953 }
6954 }
6955
6956 if (!Array) {
6957 if (ElementSize != 8)
6958 // TODO: Handle conversions to larger integral types.
6959 return false;
6960
6961 // Otherwise extract the portion of the initializer starting
6962 // at Offset as an array of bytes, and reset Offset.
6964 if (!Init)
6965 return false;
6966
6967 Offset = 0;
6969 ArrayTy = dyn_cast<ArrayType>(Init->getType());
6970 }
6971
6972 uint64_t NumElts = ArrayTy->getArrayNumElements();
6973 if (Offset > NumElts)
6974 return false;
6975
6976 Slice.Array = Array;
6977 Slice.Offset = Offset;
6978 Slice.Length = NumElts - Offset;
6979 return true;
6980}
6981
6982/// Extract bytes from the initializer of the constant array V, which need
6983/// not be a nul-terminated string. On success, store the bytes in Str and
6984/// return true. When TrimAtNul is set, Str will contain only the bytes up
6985/// to but not including the first nul. Return false on failure.
6987 bool TrimAtNul) {
6989 if (!getConstantDataArrayInfo(V, Slice, 8))
6990 return false;
6991
6992 if (Slice.Array == nullptr) {
6993 if (TrimAtNul) {
6994 // Return a nul-terminated string even for an empty Slice. This is
6995 // safe because all existing SimplifyLibcalls callers require string
6996 // arguments and the behavior of the functions they fold is undefined
6997 // otherwise. Folding the calls this way is preferable to making
6998 // the undefined library calls, even though it prevents sanitizers
6999 // from reporting such calls.
7000 Str = StringRef();
7001 return true;
7002 }
7003 if (Slice.Length == 1) {
7004 Str = StringRef("", 1);
7005 return true;
7006 }
7007 // We cannot instantiate a StringRef as we do not have an appropriate string
7008 // of 0s at hand.
7009 return false;
7010 }
7011
7012 // Start out with the entire array in the StringRef.
7013 Str = Slice.Array->getAsString();
7014 // Skip over 'offset' bytes.
7015 Str = Str.substr(Slice.Offset);
7016
7017 if (TrimAtNul) {
7018 // Trim off the \0 and anything after it. If the array is not nul
7019 // terminated, we just return the whole end of string. The client may know
7020 // some other way that the string is length-bound.
7021 Str = Str.substr(0, Str.find('\0'));
7022 }
7023 return true;
7024}
7025
7026// These next two are very similar to the above, but also look through PHI
7027// nodes.
7028// TODO: See if we can integrate these two together.
7029
7030/// If we can compute the length of the string pointed to by
7031/// the specified pointer, return 'len+1'. If we can't, return 0.
7034 unsigned CharSize) {
7035 // Look through noop bitcast instructions.
7036 V = V->stripPointerCasts();
7037
7038 // If this is a PHI node, there are two cases: either we have already seen it
7039 // or we haven't.
7040 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7041 if (!PHIs.insert(PN).second)
7042 return ~0ULL; // already in the set.
7043
7044 // If it was new, see if all the input strings are the same length.
7045 uint64_t LenSoFar = ~0ULL;
7046 for (Value *IncValue : PN->incoming_values()) {
7047 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7048 if (Len == 0) return 0; // Unknown length -> unknown.
7049
7050 if (Len == ~0ULL) continue;
7051
7052 if (Len != LenSoFar && LenSoFar != ~0ULL)
7053 return 0; // Disagree -> unknown.
7054 LenSoFar = Len;
7055 }
7056
7057 // Success, all agree.
7058 return LenSoFar;
7059 }
7060
7061 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7062 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7063 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7064 if (Len1 == 0) return 0;
7065 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7066 if (Len2 == 0) return 0;
7067 if (Len1 == ~0ULL) return Len2;
7068 if (Len2 == ~0ULL) return Len1;
7069 if (Len1 != Len2) return 0;
7070 return Len1;
7071 }
7072
7073 // Otherwise, see if we can read the string.
7075 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7076 return 0;
7077
7078 if (Slice.Array == nullptr)
7079 // Zeroinitializer (including an empty one).
7080 return 1;
7081
7082 // Search for the first nul character. Return a conservative result even
7083 // when there is no nul. This is safe since otherwise the string function
7084 // being folded such as strlen is undefined, and can be preferable to
7085 // making the undefined library call.
7086 unsigned NullIndex = 0;
7087 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7088 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7089 break;
7090 }
7091
7092 return NullIndex + 1;
7093}
7094
7095/// If we can compute the length of the string pointed to by
7096/// the specified pointer, return 'len+1'. If we can't, return 0.
7097uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7098 if (!V->getType()->isPointerTy())
7099 return 0;
7100
7102 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7103 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7104 // an empty string as a length.
7105 return Len == ~0ULL ? 1 : Len;
7106}
7107
7108const Value *
7110 bool MustPreserveOffset) {
7111 assert(Call &&
7112 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7113 if (const Value *RV = Call->getReturnedArgOperand())
7114 return RV;
7115 // This can be used only as a aliasing property.
7117 Call, MustPreserveOffset))
7118 return Call->getArgOperand(0);
7119 return nullptr;
7120}
7121
7123 const CallBase *Call, bool MustPreserveOffset) {
7124 switch (Call->getIntrinsicID()) {
7125 case Intrinsic::launder_invariant_group:
7126 case Intrinsic::strip_invariant_group:
7127 case Intrinsic::aarch64_irg:
7128 case Intrinsic::aarch64_tagp:
7129 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7130 // input pointer (and thus preserves the byte offset, which is the property
7131 // the MustPreserveOffset flag selects). However, it will not necessarily
7132 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7133 // descriptor", which has "all loads return 0, all stores are dropped"
7134 // semantics. Given the context of this intrinsic list, no one should be
7135 // relying on such a strict bit-exact null mapping (and, at time of
7136 // writing, they are not), but we document this fact out of an abundance
7137 // of caution.
7138 case Intrinsic::amdgcn_make_buffer_rsrc:
7139 return true;
7140 case Intrinsic::ptrmask:
7141 return !MustPreserveOffset;
7142 case Intrinsic::threadlocal_address:
7143 // The underlying variable changes with thread ID. The Thread ID may change
7144 // at coroutine suspend points.
7145 return !Call->getParent()->getParent()->isPresplitCoroutine();
7146 default:
7147 return false;
7148 }
7149}
7150
7151/// \p PN defines a loop-variant pointer to an object. Check if the
7152/// previous iteration of the loop was referring to the same object as \p PN.
7154 const LoopInfo *LI) {
7155 // Find the loop-defined value.
7156 Loop *L = LI->getLoopFor(PN->getParent());
7157 if (PN->getNumIncomingValues() != 2)
7158 return true;
7159
7160 // Find the value from previous iteration.
7161 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7162 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7163 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7164 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7165 return true;
7166
7167 // If a new pointer is loaded in the loop, the pointer references a different
7168 // object in every iteration. E.g.:
7169 // for (i)
7170 // int *p = a[i];
7171 // ...
7172 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7173 if (!L->isLoopInvariant(Load->getPointerOperand()))
7174 return false;
7175 return true;
7176}
7177
7178const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7179 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7180 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7181 const Value *PtrOp = GEP->getPointerOperand();
7182 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7183 return V;
7184 V = PtrOp;
7185 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7186 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7187 Value *NewV = cast<Operator>(V)->getOperand(0);
7188 if (!NewV->getType()->isPointerTy())
7189 return V;
7190 V = NewV;
7191 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7192 if (GA->isInterposable())
7193 return V;
7194 V = GA->getAliasee();
7195 } else {
7196 if (auto *PHI = dyn_cast<PHINode>(V)) {
7197 // Look through single-arg phi nodes created by LCSSA.
7198 if (PHI->getNumIncomingValues() == 1) {
7199 V = PHI->getIncomingValue(0);
7200 continue;
7201 }
7202 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7203 // CaptureTracking can know about special capturing properties of some
7204 // intrinsics like launder.invariant.group, that can't be expressed with
7205 // the attributes, but have properties like returning aliasing pointer.
7206 // Because some analysis may assume that nocaptured pointer is not
7207 // returned from some special intrinsic (because function would have to
7208 // be marked with returns attribute), it is crucial to use this function
7209 // because it should be in sync with CaptureTracking. Not using it may
7210 // cause weird miscompilations where 2 aliasing pointers are assumed to
7211 // noalias.
7213 Call, /*MustPreserveOffset=*/false)) {
7214 V = RP;
7215 continue;
7216 }
7217 }
7218
7219 return V;
7220 }
7221 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7222 }
7223 return V;
7224}
7225
7228 const LoopInfo *LI, unsigned MaxLookup) {
7231 Worklist.push_back(V);
7232 do {
7233 const Value *P = Worklist.pop_back_val();
7234 P = getUnderlyingObject(P, MaxLookup);
7235
7236 if (!Visited.insert(P).second)
7237 continue;
7238
7239 if (auto *SI = dyn_cast<SelectInst>(P)) {
7240 Worklist.push_back(SI->getTrueValue());
7241 Worklist.push_back(SI->getFalseValue());
7242 continue;
7243 }
7244
7245 if (auto *PN = dyn_cast<PHINode>(P)) {
7246 // If this PHI changes the underlying object in every iteration of the
7247 // loop, don't look through it. Consider:
7248 // int **A;
7249 // for (i) {
7250 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7251 // Curr = A[i];
7252 // *Prev, *Curr;
7253 //
7254 // Prev is tracking Curr one iteration behind so they refer to different
7255 // underlying objects.
7256 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7258 append_range(Worklist, PN->incoming_values());
7259 else
7260 Objects.push_back(P);
7261 continue;
7262 }
7263
7264 Objects.push_back(P);
7265 } while (!Worklist.empty());
7266}
7267
7269 const unsigned MaxVisited = 8;
7270
7273 Worklist.push_back(V);
7274 const Value *Object = nullptr;
7275 // Used as fallback if we can't find a common underlying object through
7276 // recursion.
7277 bool First = true;
7278 const Value *FirstObject = getUnderlyingObject(V);
7279 do {
7280 const Value *P = Worklist.pop_back_val();
7281 P = First ? FirstObject : getUnderlyingObject(P);
7282 First = false;
7283
7284 if (!Visited.insert(P).second)
7285 continue;
7286
7287 if (Visited.size() == MaxVisited)
7288 return FirstObject;
7289
7290 if (auto *SI = dyn_cast<SelectInst>(P)) {
7291 Worklist.push_back(SI->getTrueValue());
7292 Worklist.push_back(SI->getFalseValue());
7293 continue;
7294 }
7295
7296 if (auto *PN = dyn_cast<PHINode>(P)) {
7297 append_range(Worklist, PN->incoming_values());
7298 continue;
7299 }
7300
7301 if (!Object)
7302 Object = P;
7303 else if (Object != P)
7304 return FirstObject;
7305 } while (!Worklist.empty());
7306
7307 return Object ? Object : FirstObject;
7308}
7309
7310/// This is the function that does the work of looking through basic
7311/// ptrtoint+arithmetic+inttoptr sequences.
7312static const Value *getUnderlyingObjectFromInt(const Value *V) {
7313 do {
7314 if (const Operator *U = dyn_cast<Operator>(V)) {
7315 // If we find a ptrtoint, we can transfer control back to the
7316 // regular getUnderlyingObjectFromInt.
7317 if (U->getOpcode() == Instruction::PtrToInt)
7318 return U->getOperand(0);
7319 // If we find an add of a constant, a multiplied value, or a phi, it's
7320 // likely that the other operand will lead us to the base
7321 // object. We don't have to worry about the case where the
7322 // object address is somehow being computed by the multiply,
7323 // because our callers only care when the result is an
7324 // identifiable object.
7325 if (U->getOpcode() != Instruction::Add ||
7326 (!isa<ConstantInt>(U->getOperand(1)) &&
7327 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7328 !isa<PHINode>(U->getOperand(1))))
7329 return V;
7330 V = U->getOperand(0);
7331 } else {
7332 return V;
7333 }
7334 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7335 } while (true);
7336}
7337
7338/// This is a wrapper around getUnderlyingObjects and adds support for basic
7339/// ptrtoint+arithmetic+inttoptr sequences.
7340/// It returns false if unidentified object is found in getUnderlyingObjects.
7342 SmallVectorImpl<Value *> &Objects) {
7344 SmallVector<const Value *, 4> Working(1, V);
7345 do {
7346 V = Working.pop_back_val();
7347
7349 getUnderlyingObjects(V, Objs);
7350
7351 for (const Value *V : Objs) {
7352 if (!Visited.insert(V).second)
7353 continue;
7354 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7355 const Value *O =
7356 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7357 if (O->getType()->isPointerTy()) {
7358 Working.push_back(O);
7359 continue;
7360 }
7361 }
7362 // If getUnderlyingObjects fails to find an identifiable object,
7363 // getUnderlyingObjectsForCodeGen also fails for safety.
7364 if (!isIdentifiedObject(V)) {
7365 Objects.clear();
7366 return false;
7367 }
7368 Objects.push_back(const_cast<Value *>(V));
7369 }
7370 } while (!Working.empty());
7371 return true;
7372}
7373
7375 AllocaInst *Result = nullptr;
7377 SmallVector<Value *, 4> Worklist;
7378
7379 auto AddWork = [&](Value *V) {
7380 if (Visited.insert(V).second)
7381 Worklist.push_back(V);
7382 };
7383
7384 AddWork(V);
7385 do {
7386 V = Worklist.pop_back_val();
7387 assert(Visited.count(V));
7388
7389 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7390 if (Result && Result != AI)
7391 return nullptr;
7392 Result = AI;
7393 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7394 AddWork(CI->getOperand(0));
7395 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7396 for (Value *IncValue : PN->incoming_values())
7397 AddWork(IncValue);
7398 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7399 AddWork(SI->getTrueValue());
7400 AddWork(SI->getFalseValue());
7402 if (OffsetZero && !GEP->hasAllZeroIndices())
7403 return nullptr;
7404 AddWork(GEP->getPointerOperand());
7405 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7406 Value *Returned = CB->getReturnedArgOperand();
7407 if (Returned)
7408 AddWork(Returned);
7409 else
7410 return nullptr;
7411 } else {
7412 return nullptr;
7413 }
7414 } while (!Worklist.empty());
7415
7416 return Result;
7417}
7418
7420 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7421 for (const User *U : V->users()) {
7423 if (!II)
7424 return false;
7425
7426 if (AllowLifetime && II->isLifetimeStartOrEnd())
7427 continue;
7428
7429 if (AllowDroppable && II->isDroppable())
7430 continue;
7431
7432 return false;
7433 }
7434 return true;
7435}
7436
7439 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7440}
7443 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7444}
7445
7447 if (auto *II = dyn_cast<IntrinsicInst>(I))
7448 return isTriviallyVectorizable(II->getIntrinsicID());
7449 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7450 return (!Shuffle || Shuffle->isSelect()) &&
7452}
7453
7455 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7456 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7457 bool IgnoreUBImplyingAttrs) {
7458 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7459 AC, DT, TLI, UseVariableInfo,
7460 IgnoreUBImplyingAttrs);
7461}
7462
7464 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7465 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7466 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7467#ifndef NDEBUG
7468 if (Inst->getOpcode() != Opcode) {
7469 // Check that the operands are actually compatible with the Opcode override.
7470 auto hasEqualReturnAndLeadingOperandTypes =
7471 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7472 if (Inst->getNumOperands() < NumLeadingOperands)
7473 return false;
7474 const Type *ExpectedType = Inst->getType();
7475 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7476 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7477 return false;
7478 return true;
7479 };
7481 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7482 assert(!Instruction::isUnaryOp(Opcode) ||
7483 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7484 }
7485#endif
7486
7487 switch (Opcode) {
7488 default:
7489 return true;
7490 case Instruction::UDiv:
7491 case Instruction::URem: {
7492 // x / y is undefined if y == 0.
7493 const APInt *V;
7494 if (match(Inst->getOperand(1), m_APInt(V)))
7495 return *V != 0;
7496 return false;
7497 }
7498 case Instruction::SDiv:
7499 case Instruction::SRem: {
7500 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7501 const APInt *Numerator, *Denominator;
7502 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7503 return false;
7504 // We cannot hoist this division if the denominator is 0.
7505 if (*Denominator == 0)
7506 return false;
7507 // It's safe to hoist if the denominator is not 0 or -1.
7508 if (!Denominator->isAllOnes())
7509 return true;
7510 // At this point we know that the denominator is -1. It is safe to hoist as
7511 // long we know that the numerator is not INT_MIN.
7512 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7513 return !Numerator->isMinSignedValue();
7514 // The numerator *might* be MinSignedValue.
7515 return false;
7516 }
7517 case Instruction::Load: {
7518 if (!UseVariableInfo)
7519 return false;
7520
7521 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7522 if (!LI)
7523 return false;
7524 if (mustSuppressSpeculation(*LI))
7525 return false;
7526 const DataLayout &DL = LI->getDataLayout();
7528 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7529 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7530 }
7531 case Instruction::Call: {
7532 auto *CI = dyn_cast<const CallInst>(Inst);
7533 if (!CI)
7534 return false;
7535 const Function *Callee = CI->getCalledFunction();
7536
7537 // The called function could have undefined behavior or side-effects, even
7538 // if marked readnone nounwind.
7539 if (!Callee || !Callee->isSpeculatable())
7540 return false;
7541 // Since the operands may be changed after hoisting, undefined behavior may
7542 // be triggered by some UB-implying attributes.
7543 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7544 }
7545 case Instruction::VAArg:
7546 case Instruction::Alloca:
7547 case Instruction::Invoke:
7548 case Instruction::CallBr:
7549 case Instruction::PHI:
7550 case Instruction::Store:
7551 case Instruction::Ret:
7552 case Instruction::UncondBr:
7553 case Instruction::CondBr:
7554 case Instruction::IndirectBr:
7555 case Instruction::Switch:
7556 case Instruction::Unreachable:
7557 case Instruction::Fence:
7558 case Instruction::AtomicRMW:
7559 case Instruction::AtomicCmpXchg:
7560 case Instruction::LandingPad:
7561 case Instruction::Resume:
7562 case Instruction::CatchSwitch:
7563 case Instruction::CatchPad:
7564 case Instruction::CatchRet:
7565 case Instruction::CleanupPad:
7566 case Instruction::CleanupRet:
7567 return false; // Misc instructions which have effects
7568 }
7569}
7570
7572 if (I.mayReadOrWriteMemory())
7573 // Memory dependency possible
7574 return true;
7576 // Can't move above a maythrow call or infinite loop. Or if an
7577 // inalloca alloca, above a stacksave call.
7578 return true;
7580 // 1) Can't reorder two inf-loop calls, even if readonly
7581 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7582 // safe to speculative execute. (Inverse of above)
7583 return true;
7584 return false;
7585}
7586
7587/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7601
7602/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7605 bool ForSigned,
7606 const SimplifyQuery &SQ) {
7607 ConstantRange CR1 =
7608 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7609 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7612 return CR1.intersectWith(CR2, RangeType);
7613}
7614
7616 const Value *RHS,
7617 const SimplifyQuery &SQ,
7618 bool IsNSW) {
7619 ConstantRange LHSRange =
7620 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7621 ConstantRange RHSRange =
7622 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7623
7624 // mul nsw of two non-negative numbers is also nuw.
7625 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7627
7628 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7629}
7630
7632 const Value *RHS,
7633 const SimplifyQuery &SQ) {
7634 // Multiplying n * m significant bits yields a result of n + m significant
7635 // bits. If the total number of significant bits does not exceed the
7636 // result bit width (minus 1), there is no overflow.
7637 // This means if we have enough leading sign bits in the operands
7638 // we can guarantee that the result does not overflow.
7639 // Ref: "Hacker's Delight" by Henry Warren
7640 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7641
7642 // Note that underestimating the number of sign bits gives a more
7643 // conservative answer.
7644 unsigned SignBits =
7645 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7646
7647 // First handle the easy case: if we have enough sign bits there's
7648 // definitely no overflow.
7649 if (SignBits > BitWidth + 1)
7651
7652 // There are two ambiguous cases where there can be no overflow:
7653 // SignBits == BitWidth + 1 and
7654 // SignBits == BitWidth
7655 // The second case is difficult to check, therefore we only handle the
7656 // first case.
7657 if (SignBits == BitWidth + 1) {
7658 // It overflows only when both arguments are negative and the true
7659 // product is exactly the minimum negative number.
7660 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7661 // For simplicity we just check if at least one side is not negative.
7662 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7663 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7664 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7666 }
7668}
7669
7672 const WithCache<const Value *> &RHS,
7673 const SimplifyQuery &SQ) {
7674 ConstantRange LHSRange =
7675 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7676 ConstantRange RHSRange =
7677 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7678 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7679}
7680
7681static OverflowResult
7684 const AddOperator *Add, const SimplifyQuery &SQ) {
7685 if (Add && Add->hasNoSignedWrap()) {
7687 }
7688
7689 // If LHS and RHS each have at least two sign bits, the addition will look
7690 // like
7691 //
7692 // XX..... +
7693 // YY.....
7694 //
7695 // If the carry into the most significant position is 0, X and Y can't both
7696 // be 1 and therefore the carry out of the addition is also 0.
7697 //
7698 // If the carry into the most significant position is 1, X and Y can't both
7699 // be 0 and therefore the carry out of the addition is also 1.
7700 //
7701 // Since the carry into the most significant position is always equal to
7702 // the carry out of the addition, there is no signed overflow.
7703 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7705
7706 ConstantRange LHSRange =
7707 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7708 ConstantRange RHSRange =
7709 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7710 OverflowResult OR =
7711 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7713 return OR;
7714
7715 // The remaining code needs Add to be available. Early returns if not so.
7716 if (!Add)
7718
7719 // If the sign of Add is the same as at least one of the operands, this add
7720 // CANNOT overflow. If this can be determined from the known bits of the
7721 // operands the above signedAddMayOverflow() check will have already done so.
7722 // The only other way to improve on the known bits is from an assumption, so
7723 // call computeKnownBitsFromContext() directly.
7724 bool LHSOrRHSKnownNonNegative =
7725 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7726 bool LHSOrRHSKnownNegative =
7727 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7728 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7729 KnownBits AddKnown(LHSRange.getBitWidth());
7730 computeKnownBitsFromContext(Add, AddKnown, SQ);
7731 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7732 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7734 }
7735
7737}
7738
7740 const Value *RHS,
7741 const SimplifyQuery &SQ) {
7742 // X - (X % ?)
7743 // The remainder of a value can't have greater magnitude than itself,
7744 // so the subtraction can't overflow.
7745
7746 // X - (X -nuw ?)
7747 // In the minimal case, this would simplify to "?", so there's no subtract
7748 // at all. But if this analysis is used to peek through casts, for example,
7749 // then determining no-overflow may allow other transforms.
7750
7751 // TODO: There are other patterns like this.
7752 // See simplifyICmpWithBinOpOnLHS() for candidates.
7753 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7754 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7755 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7757
7758 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7759 SQ.DL)) {
7760 if (*C)
7763 }
7764
7765 ConstantRange LHSRange =
7766 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7767 ConstantRange RHSRange =
7768 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7769 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7770}
7771
7773 const Value *RHS,
7774 const SimplifyQuery &SQ) {
7775 // X - (X % ?)
7776 // The remainder of a value can't have greater magnitude than itself,
7777 // so the subtraction can't overflow.
7778
7779 // X - (X -nsw ?)
7780 // In the minimal case, this would simplify to "?", so there's no subtract
7781 // at all. But if this analysis is used to peek through casts, for example,
7782 // then determining no-overflow may allow other transforms.
7783 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7784 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7785 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7787
7788 // If LHS and RHS each have at least two sign bits, the subtraction
7789 // cannot overflow.
7790 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7792
7793 ConstantRange LHSRange =
7794 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7795 ConstantRange RHSRange =
7796 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7797 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7798}
7799
7801 const DominatorTree &DT) {
7802 SmallVector<const CondBrInst *, 2> GuardingBranches;
7804
7805 for (const User *U : WO->users()) {
7806 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7807 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7808
7809 if (EVI->getIndices()[0] == 0)
7810 Results.push_back(EVI);
7811 else {
7812 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7813
7814 for (const auto *U : EVI->users())
7815 if (const auto *B = dyn_cast<CondBrInst>(U))
7816 GuardingBranches.push_back(B);
7817 }
7818 } else {
7819 // We are using the aggregate directly in a way we don't want to analyze
7820 // here (storing it to a global, say).
7821 return false;
7822 }
7823 }
7824
7825 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7826 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7827
7828 // Check if all users of the add are provably no-wrap.
7829 for (const auto *Result : Results) {
7830 // If the extractvalue itself is not executed on overflow, the we don't
7831 // need to check each use separately, since domination is transitive.
7832 if (DT.dominates(NoWrapEdge, Result->getParent()))
7833 continue;
7834
7835 for (const auto &RU : Result->uses())
7836 if (!DT.dominates(NoWrapEdge, RU))
7837 return false;
7838 }
7839
7840 return true;
7841 };
7842
7843 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7844}
7845
7846/// Shifts return poison if shiftwidth is larger than the bitwidth.
7847static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7848 auto *C = dyn_cast<Constant>(ShiftAmount);
7849 if (!C)
7850 return false;
7851
7852 // Shifts return poison if shiftwidth is larger than the bitwidth.
7854 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7855 unsigned NumElts = FVTy->getNumElements();
7856 for (unsigned i = 0; i < NumElts; ++i)
7857 ShiftAmounts.push_back(C->getAggregateElement(i));
7858 } else if (isa<ScalableVectorType>(C->getType()))
7859 return false; // Can't tell, just return false to be safe
7860 else
7861 ShiftAmounts.push_back(C);
7862
7863 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7864 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7865 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7866 });
7867
7868 return Safe;
7869}
7870
7872 bool ConsiderFlagsAndMetadata) {
7873
7874 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7875 Op->hasPoisonGeneratingAnnotations())
7876 return true;
7877
7878 unsigned Opcode = Op->getOpcode();
7879
7880 // Check whether opcode is a poison/undef-generating operation
7881 switch (Opcode) {
7882 case Instruction::Shl:
7883 case Instruction::AShr:
7884 case Instruction::LShr:
7885 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7886 case Instruction::FPToSI:
7887 case Instruction::FPToUI:
7888 // fptosi/ui yields poison if the resulting value does not fit in the
7889 // destination type.
7890 return true;
7891 case Instruction::Call:
7892 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7893 switch (II->getIntrinsicID()) {
7894 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7895 case Intrinsic::ctlz:
7896 case Intrinsic::cttz:
7897 case Intrinsic::abs:
7898 // We're not considering flags so it is safe to just return false.
7899 return false;
7900 case Intrinsic::sshl_sat:
7901 case Intrinsic::ushl_sat:
7902 if (!includesPoison(Kind) ||
7903 shiftAmountKnownInRange(II->getArgOperand(1)))
7904 return false;
7905 break;
7906 }
7907 }
7908 [[fallthrough]];
7909 case Instruction::CallBr:
7910 case Instruction::Invoke: {
7911 const auto *CB = cast<CallBase>(Op);
7912 return !CB->hasRetAttr(Attribute::NoUndef) &&
7913 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7914 }
7915 case Instruction::InsertElement:
7916 case Instruction::ExtractElement: {
7917 // If index exceeds the length of the vector, it returns poison
7918 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7919 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7920 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7921 if (includesPoison(Kind))
7922 return !Idx ||
7923 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7924 return false;
7925 }
7926 case Instruction::ShuffleVector: {
7928 ? cast<ConstantExpr>(Op)->getShuffleMask()
7929 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7930 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7931 }
7932 case Instruction::FNeg:
7933 case Instruction::PHI:
7934 case Instruction::Select:
7935 case Instruction::ExtractValue:
7936 case Instruction::InsertValue:
7937 case Instruction::Freeze:
7938 case Instruction::ICmp:
7939 case Instruction::FCmp:
7940 case Instruction::GetElementPtr:
7941 return false;
7942 case Instruction::AddrSpaceCast:
7943 return true;
7944 default: {
7945 const auto *CE = dyn_cast<ConstantExpr>(Op);
7946 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7947 return false;
7948 else if (Instruction::isBinaryOp(Opcode))
7949 return false;
7950 // Be conservative and return true.
7951 return true;
7952 }
7953 }
7954}
7955
7957 bool ConsiderFlagsAndMetadata) {
7958 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
7959 ConsiderFlagsAndMetadata);
7960}
7961
7962bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
7963 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
7964 ConsiderFlagsAndMetadata);
7965}
7966
7967static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
7968 unsigned Depth) {
7969 if (ValAssumedPoison == V)
7970 return true;
7971
7972 const unsigned MaxDepth = 2;
7973 if (Depth >= MaxDepth)
7974 return false;
7975
7976 if (const auto *I = dyn_cast<Instruction>(V)) {
7977 if (any_of(I->operands(), [=](const Use &Op) {
7978 return propagatesPoison(Op) &&
7979 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
7980 }))
7981 return true;
7982
7983 // V = extractvalue V0, idx
7984 // V2 = extractvalue V0, idx2
7985 // V0's elements are all poison or not. (e.g., add_with_overflow)
7986 const WithOverflowInst *II;
7988 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
7989 llvm::is_contained(II->args(), ValAssumedPoison)))
7990 return true;
7991 }
7992 return false;
7993}
7994
7995static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
7996 unsigned Depth) {
7997 if (isGuaranteedNotToBePoison(ValAssumedPoison))
7998 return true;
7999
8000 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8001 return true;
8002
8003 const unsigned MaxDepth = 2;
8004 if (Depth >= MaxDepth)
8005 return false;
8006
8007 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8008 if (I && !canCreatePoison(cast<Operator>(I))) {
8009 return all_of(I->operands(), [=](const Value *Op) {
8010 return impliesPoison(Op, V, Depth + 1);
8011 });
8012 }
8013 return false;
8014}
8015
8016bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8017 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8018}
8019
8020static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8021
8023 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8024 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8026 return false;
8027
8028 if (isa<MetadataAsValue>(V))
8029 return false;
8030
8031 if (const auto *A = dyn_cast<Argument>(V)) {
8032 if (A->hasAttribute(Attribute::NoUndef) ||
8033 A->hasAttribute(Attribute::Dereferenceable) ||
8034 A->hasAttribute(Attribute::DereferenceableOrNull))
8035 return true;
8036 }
8037
8038 if (auto *C = dyn_cast<Constant>(V)) {
8039 if (isa<PoisonValue>(C))
8040 return !includesPoison(Kind);
8041
8042 if (isa<UndefValue>(C))
8043 return !includesUndef(Kind);
8044
8047 return true;
8048
8049 if (C->getType()->isVectorTy()) {
8050 if (isa<ConstantExpr>(C)) {
8051 // Scalable vectors can use a ConstantExpr to build a splat.
8052 if (Constant *SplatC = C->getSplatValue())
8053 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8054 return true;
8055 } else {
8056 if (includesUndef(Kind) && C->containsUndefElement())
8057 return false;
8058 if (includesPoison(Kind) && C->containsPoisonElement())
8059 return false;
8060 return !C->containsConstantExpression();
8061 }
8062 }
8063 }
8064
8065 // Strip cast operations from a pointer value.
8066 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8067 // inbounds with zero offset. To guarantee that the result isn't poison, the
8068 // stripped pointer is checked as it has to be pointing into an allocated
8069 // object or be null `null` to ensure `inbounds` getelement pointers with a
8070 // zero offset could not produce poison.
8071 // It can strip off addrspacecast that do not change bit representation as
8072 // well. We believe that such addrspacecast is equivalent to no-op.
8073 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8074 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8075 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8076 return true;
8077
8078 auto OpCheck = [&](const Value *V) {
8079 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8080 };
8081
8082 if (auto *Opr = dyn_cast<Operator>(V)) {
8083 // If the value is a freeze instruction, then it can never
8084 // be undef or poison.
8085 if (isa<FreezeInst>(V))
8086 return true;
8087
8088 if (const auto *CB = dyn_cast<CallBase>(V)) {
8089 if (CB->hasRetAttr(Attribute::NoUndef) ||
8090 CB->hasRetAttr(Attribute::Dereferenceable) ||
8091 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8092 return true;
8093 }
8094
8095 if (!::canCreateUndefOrPoison(Opr, Kind,
8096 /*ConsiderFlagsAndMetadata=*/true)) {
8097 if (const auto *PN = dyn_cast<PHINode>(V)) {
8098 unsigned Num = PN->getNumIncomingValues();
8099 bool IsWellDefined = true;
8100 for (unsigned i = 0; i < Num; ++i) {
8101 if (PN == PN->getIncomingValue(i))
8102 continue;
8103 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8104 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8105 DT, Depth + 1, Kind)) {
8106 IsWellDefined = false;
8107 break;
8108 }
8109 }
8110 if (IsWellDefined)
8111 return true;
8112 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8113 : nullptr) {
8114 // For splats we only need to check the value being splatted.
8115 if (OpCheck(Splat))
8116 return true;
8117 } else if (all_of(Opr->operands(), OpCheck))
8118 return true;
8119 }
8120 }
8121
8122 if (auto *I = dyn_cast<LoadInst>(V))
8123 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8124 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8125 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8126 return true;
8127
8129 return true;
8130
8131 // CxtI may be null or a cloned instruction.
8132 if (!CtxI || !CtxI->getParent() || !DT)
8133 return false;
8134
8135 auto *DNode = DT->getNode(CtxI->getParent());
8136 if (!DNode)
8137 // Unreachable block
8138 return false;
8139
8140 // If V is used as a branch condition before reaching CtxI, V cannot be
8141 // undef or poison.
8142 // br V, BB1, BB2
8143 // BB1:
8144 // CtxI ; V cannot be undef or poison here
8145 auto *Dominator = DNode->getIDom();
8146 // This check is purely for compile time reasons: we can skip the IDom walk
8147 // if what we are checking for includes undef and the value is not an integer.
8148 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8149 while (Dominator) {
8150 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8151
8152 Value *Cond = nullptr;
8153 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8154 Cond = BI->getCondition();
8155 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8156 Cond = SI->getCondition();
8157 }
8158
8159 if (Cond) {
8160 if (Cond == V)
8161 return true;
8162 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8163 // For poison, we can analyze further
8164 auto *Opr = cast<Operator>(Cond);
8165 if (any_of(Opr->operands(), [V](const Use &U) {
8166 return V == U && propagatesPoison(U);
8167 }))
8168 return true;
8169 }
8170 }
8171
8172 Dominator = Dominator->getIDom();
8173 }
8174
8175 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8176 return true;
8177
8178 return false;
8179}
8180
8182 const Instruction *CtxI,
8183 const DominatorTree *DT,
8184 unsigned Depth) {
8185 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8187}
8188
8190 const Instruction *CtxI,
8191 const DominatorTree *DT, unsigned Depth) {
8192 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8194}
8195
8197 const Instruction *CtxI,
8198 const DominatorTree *DT, unsigned Depth) {
8199 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8201}
8202
8203/// Return true if undefined behavior would provably be executed on the path to
8204/// OnPathTo if Root produced a posion result. Note that this doesn't say
8205/// anything about whether OnPathTo is actually executed or whether Root is
8206/// actually poison. This can be used to assess whether a new use of Root can
8207/// be added at a location which is control equivalent with OnPathTo (such as
8208/// immediately before it) without introducing UB which didn't previously
8209/// exist. Note that a false result conveys no information.
8211 Instruction *OnPathTo,
8212 DominatorTree *DT) {
8213 // Basic approach is to assume Root is poison, propagate poison forward
8214 // through all users we can easily track, and then check whether any of those
8215 // users are provable UB and must execute before out exiting block might
8216 // exit.
8217
8218 // The set of all recursive users we've visited (which are assumed to all be
8219 // poison because of said visit)
8222 Worklist.push_back(Root);
8223 while (!Worklist.empty()) {
8224 const Instruction *I = Worklist.pop_back_val();
8225
8226 // If we know this must trigger UB on a path leading our target.
8227 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8228 return true;
8229
8230 // If we can't analyze propagation through this instruction, just skip it
8231 // and transitive users. Safe as false is a conservative result.
8232 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8233 return KnownPoison.contains(U) && propagatesPoison(U);
8234 }))
8235 continue;
8236
8237 if (KnownPoison.insert(I).second)
8238 for (const User *User : I->users())
8239 Worklist.push_back(cast<Instruction>(User));
8240 }
8241
8242 // Might be non-UB, or might have a path we couldn't prove must execute on
8243 // way to exiting bb.
8244 return false;
8245}
8246
8248 const SimplifyQuery &SQ) {
8249 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8250 Add, SQ);
8251}
8252
8255 const WithCache<const Value *> &RHS,
8256 const SimplifyQuery &SQ) {
8257 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8258}
8259
8261 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8262 // of time because it's possible for another thread to interfere with it for an
8263 // arbitrary length of time, but programs aren't allowed to rely on that.
8264
8265 // If there is no successor, then execution can't transfer to it.
8266 if (isa<ReturnInst>(I))
8267 return false;
8269 return false;
8270
8271 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8272 // Instruction::willReturn.
8273 //
8274 // FIXME: Move this check into Instruction::willReturn.
8275 if (isa<CatchPadInst>(I)) {
8276 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8277 default:
8278 // A catchpad may invoke exception object constructors and such, which
8279 // in some languages can be arbitrary code, so be conservative by default.
8280 return false;
8282 // For CoreCLR, it just involves a type test.
8283 return true;
8284 }
8285 }
8286
8287 // An instruction that returns without throwing must transfer control flow
8288 // to a successor.
8289 return !I->mayThrow() && I->willReturn();
8290}
8291
8293 // TODO: This is slightly conservative for invoke instruction since exiting
8294 // via an exception *is* normal control for them.
8295 for (const Instruction &I : *BB)
8297 return false;
8298 return true;
8299}
8300
8307
8310 assert(ScanLimit && "scan limit must be non-zero");
8311 for (const Instruction &I : Range) {
8312 if (--ScanLimit == 0)
8313 return false;
8315 return false;
8316 }
8317 return true;
8318}
8319
8321 const Loop *L) {
8322 // The loop header is guaranteed to be executed for every iteration.
8323 //
8324 // FIXME: Relax this constraint to cover all basic blocks that are
8325 // guaranteed to be executed at every iteration.
8326 if (I->getParent() != L->getHeader()) return false;
8327
8328 for (const Instruction &LI : *L->getHeader()) {
8329 if (&LI == I) return true;
8330 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8331 }
8332 llvm_unreachable("Instruction not contained in its own parent basic block.");
8333}
8334
8336 switch (IID) {
8337 // TODO: Add more intrinsics.
8338 case Intrinsic::sadd_with_overflow:
8339 case Intrinsic::ssub_with_overflow:
8340 case Intrinsic::smul_with_overflow:
8341 case Intrinsic::uadd_with_overflow:
8342 case Intrinsic::usub_with_overflow:
8343 case Intrinsic::umul_with_overflow:
8344 // If an input is a vector containing a poison element, the
8345 // two output vectors (calculated results, overflow bits)'
8346 // corresponding lanes are poison.
8347 return true;
8348 case Intrinsic::ctpop:
8349 case Intrinsic::ctlz:
8350 case Intrinsic::cttz:
8351 case Intrinsic::abs:
8352 case Intrinsic::smax:
8353 case Intrinsic::smin:
8354 case Intrinsic::umax:
8355 case Intrinsic::umin:
8356 case Intrinsic::scmp:
8357 case Intrinsic::is_fpclass:
8358 case Intrinsic::ptrmask:
8359 case Intrinsic::ucmp:
8360 case Intrinsic::bitreverse:
8361 case Intrinsic::bswap:
8362 case Intrinsic::sadd_sat:
8363 case Intrinsic::ssub_sat:
8364 case Intrinsic::sshl_sat:
8365 case Intrinsic::uadd_sat:
8366 case Intrinsic::usub_sat:
8367 case Intrinsic::ushl_sat:
8368 case Intrinsic::smul_fix:
8369 case Intrinsic::smul_fix_sat:
8370 case Intrinsic::umul_fix:
8371 case Intrinsic::umul_fix_sat:
8372 case Intrinsic::pow:
8373 case Intrinsic::powi:
8374 case Intrinsic::sin:
8375 case Intrinsic::sinh:
8376 case Intrinsic::cos:
8377 case Intrinsic::cosh:
8378 case Intrinsic::sincos:
8379 case Intrinsic::sincospi:
8380 case Intrinsic::tan:
8381 case Intrinsic::tanh:
8382 case Intrinsic::asin:
8383 case Intrinsic::acos:
8384 case Intrinsic::atan:
8385 case Intrinsic::atan2:
8386 case Intrinsic::canonicalize:
8387 case Intrinsic::sqrt:
8388 case Intrinsic::exp:
8389 case Intrinsic::exp2:
8390 case Intrinsic::exp10:
8391 case Intrinsic::log:
8392 case Intrinsic::log2:
8393 case Intrinsic::log10:
8394 case Intrinsic::modf:
8395 case Intrinsic::floor:
8396 case Intrinsic::ceil:
8397 case Intrinsic::trunc:
8398 case Intrinsic::rint:
8399 case Intrinsic::nearbyint:
8400 case Intrinsic::round:
8401 case Intrinsic::roundeven:
8402 case Intrinsic::lrint:
8403 case Intrinsic::llrint:
8404 case Intrinsic::fshl:
8405 case Intrinsic::fshr:
8406 case Intrinsic::frexp:
8407 case Intrinsic::get_active_lane_mask:
8408 return true;
8409 default:
8410 return false;
8411 }
8412}
8413
8414bool llvm::propagatesPoison(const Use &PoisonOp) {
8415 const Operator *I = cast<Operator>(PoisonOp.getUser());
8416 switch (I->getOpcode()) {
8417 case Instruction::Freeze:
8418 case Instruction::PHI:
8419 case Instruction::Invoke:
8420 return false;
8421 case Instruction::Select:
8422 return PoisonOp.getOperandNo() == 0;
8423 case Instruction::Call:
8424 if (auto *II = dyn_cast<IntrinsicInst>(I))
8425 return intrinsicPropagatesPoison(II->getIntrinsicID());
8426 return false;
8427 case Instruction::ICmp:
8428 case Instruction::FCmp:
8429 case Instruction::GetElementPtr:
8430 return true;
8431 default:
8433 return true;
8434
8435 // Be conservative and return false.
8436 return false;
8437 }
8438}
8439
8440/// Enumerates all operands of \p I that are guaranteed to not be undef or
8441/// poison. If the callback \p Handle returns true, stop processing and return
8442/// true. Otherwise, return false.
8443template <typename CallableT>
8445 const CallableT &Handle) {
8446 switch (I->getOpcode()) {
8447 case Instruction::Store:
8448 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8449 return true;
8450 break;
8451
8452 case Instruction::Load:
8453 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8454 return true;
8455 break;
8456
8457 // Since dereferenceable attribute imply noundef, atomic operations
8458 // also implicitly have noundef pointers too
8459 case Instruction::AtomicCmpXchg:
8461 return true;
8462 break;
8463
8464 case Instruction::AtomicRMW:
8465 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8466 return true;
8467 break;
8468
8469 case Instruction::Call:
8470 case Instruction::Invoke: {
8471 const CallBase *CB = cast<CallBase>(I);
8472 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8473 return true;
8474 for (unsigned i = 0; i < CB->arg_size(); ++i)
8475 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8476 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8477 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8478 Handle(CB->getArgOperand(i)))
8479 return true;
8480 break;
8481 }
8482 case Instruction::Ret:
8483 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8484 Handle(I->getOperand(0)))
8485 return true;
8486 break;
8487 case Instruction::Switch:
8488 if (Handle(cast<SwitchInst>(I)->getCondition()))
8489 return true;
8490 break;
8491 case Instruction::CondBr:
8492 if (Handle(cast<CondBrInst>(I)->getCondition()))
8493 return true;
8494 break;
8495 default:
8496 break;
8497 }
8498
8499 return false;
8500}
8501
8502/// Enumerates all operands of \p I that are guaranteed to not be poison.
8503template <typename CallableT>
8505 const CallableT &Handle) {
8506 if (handleGuaranteedWellDefinedOps(I, Handle))
8507 return true;
8508 switch (I->getOpcode()) {
8509 // Divisors of these operations are allowed to be partially undef.
8510 case Instruction::UDiv:
8511 case Instruction::SDiv:
8512 case Instruction::URem:
8513 case Instruction::SRem:
8514 return Handle(I->getOperand(1));
8515 default:
8516 return false;
8517 }
8518}
8519
8521 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8523 I, [&](const Value *V) { return KnownPoison.count(V); });
8524}
8525
8527 bool PoisonOnly) {
8528 // We currently only look for uses of values within the same basic
8529 // block, as that makes it easier to guarantee that the uses will be
8530 // executed given that Inst is executed.
8531 //
8532 // FIXME: Expand this to consider uses beyond the same basic block. To do
8533 // this, look out for the distinction between post-dominance and strong
8534 // post-dominance.
8535 const BasicBlock *BB = nullptr;
8537 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8538 BB = Inst->getParent();
8539 Begin = Inst->getIterator();
8540 Begin++;
8541 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8542 if (Arg->getParent()->isDeclaration())
8543 return false;
8544 BB = &Arg->getParent()->getEntryBlock();
8545 Begin = BB->begin();
8546 } else {
8547 return false;
8548 }
8549
8550 // Limit number of instructions we look at, to avoid scanning through large
8551 // blocks. The current limit is chosen arbitrarily.
8552 unsigned ScanLimit = 32;
8553 BasicBlock::const_iterator End = BB->end();
8554
8555 if (!PoisonOnly) {
8556 // Since undef does not propagate eagerly, be conservative & just check
8557 // whether a value is directly passed to an instruction that must take
8558 // well-defined operands.
8559
8560 for (const auto &I : make_range(Begin, End)) {
8561 if (--ScanLimit == 0)
8562 break;
8563
8564 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8565 return WellDefinedOp == V;
8566 }))
8567 return true;
8568
8570 break;
8571 }
8572 return false;
8573 }
8574
8575 // Set of instructions that we have proved will yield poison if Inst
8576 // does.
8577 SmallPtrSet<const Value *, 16> YieldsPoison;
8579
8580 YieldsPoison.insert(V);
8581 Visited.insert(BB);
8582
8583 while (true) {
8584 for (const auto &I : make_range(Begin, End)) {
8585 if (--ScanLimit == 0)
8586 return false;
8587 if (mustTriggerUB(&I, YieldsPoison))
8588 return true;
8590 return false;
8591
8592 // If an operand is poison and propagates it, mark I as yielding poison.
8593 for (const Use &Op : I.operands()) {
8594 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8595 YieldsPoison.insert(&I);
8596 break;
8597 }
8598 }
8599
8600 // Special handling for select, which returns poison if its operand 0 is
8601 // poison (handled in the loop above) *or* if both its true/false operands
8602 // are poison (handled here).
8603 if (I.getOpcode() == Instruction::Select &&
8604 YieldsPoison.count(I.getOperand(1)) &&
8605 YieldsPoison.count(I.getOperand(2))) {
8606 YieldsPoison.insert(&I);
8607 }
8608 }
8609
8610 BB = BB->getSingleSuccessor();
8611 if (!BB || !Visited.insert(BB).second)
8612 break;
8613
8614 Begin = BB->getFirstNonPHIIt();
8615 End = BB->end();
8616 }
8617 return false;
8618}
8619
8621 return ::programUndefinedIfUndefOrPoison(Inst, false);
8622}
8623
8625 return ::programUndefinedIfUndefOrPoison(Inst, true);
8626}
8627
8628static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8629 if (FMF.noNaNs())
8630 return true;
8631
8632 if (auto *C = dyn_cast<ConstantFP>(V))
8633 return !C->isNaN();
8634
8635 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8636 if (!C->getElementType()->isFloatingPointTy())
8637 return false;
8638 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8639 if (C->getElementAsAPFloat(I).isNaN())
8640 return false;
8641 }
8642 return true;
8643 }
8644
8646 return true;
8647
8648 return false;
8649}
8650
8651static bool isKnownNonZero(const Value *V) {
8652 if (auto *C = dyn_cast<ConstantFP>(V))
8653 return !C->isZero();
8654
8655 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8656 if (!C->getElementType()->isFloatingPointTy())
8657 return false;
8658 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8659 if (C->getElementAsAPFloat(I).isZero())
8660 return false;
8661 }
8662 return true;
8663 }
8664
8665 return false;
8666}
8667
8668/// Match clamp pattern for float types without care about NaNs or signed zeros.
8669/// Given non-min/max outer cmp/select from the clamp pattern this
8670/// function recognizes if it can be substitued by a "canonical" min/max
8671/// pattern.
8673 Value *CmpLHS, Value *CmpRHS,
8674 Value *TrueVal, Value *FalseVal,
8675 Value *&LHS, Value *&RHS) {
8676 // Try to match
8677 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8678 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8679 // and return description of the outer Max/Min.
8680
8681 // First, check if select has inverse order:
8682 if (CmpRHS == FalseVal) {
8683 std::swap(TrueVal, FalseVal);
8684 Pred = CmpInst::getInversePredicate(Pred);
8685 }
8686
8687 // Assume success now. If there's no match, callers should not use these anyway.
8688 LHS = TrueVal;
8689 RHS = FalseVal;
8690
8691 const APFloat *FC1;
8692 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8693 return {SPF_UNKNOWN, SPNB_NA, false};
8694
8695 const APFloat *FC2;
8696 switch (Pred) {
8697 case CmpInst::FCMP_OLT:
8698 case CmpInst::FCMP_OLE:
8699 case CmpInst::FCMP_ULT:
8700 case CmpInst::FCMP_ULE:
8701 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8702 *FC1 < *FC2)
8703 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8704 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8705 *FC1 < *FC2)
8706 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8707 break;
8708 case CmpInst::FCMP_OGT:
8709 case CmpInst::FCMP_OGE:
8710 case CmpInst::FCMP_UGT:
8711 case CmpInst::FCMP_UGE:
8712 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8713 *FC1 > *FC2)
8714 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8715 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8716 *FC1 > *FC2)
8717 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8718 break;
8719 default:
8720 break;
8721 }
8722
8723 return {SPF_UNKNOWN, SPNB_NA, false};
8724}
8725
8726/// Recognize variations of:
8727/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8729 Value *CmpLHS, Value *CmpRHS,
8730 Value *TrueVal, Value *FalseVal) {
8731 // Swap the select operands and predicate to match the patterns below.
8732 if (CmpRHS != TrueVal) {
8733 Pred = ICmpInst::getSwappedPredicate(Pred);
8734 std::swap(TrueVal, FalseVal);
8735 }
8736 const APInt *C1;
8737 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8738 const APInt *C2;
8739 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8740 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8741 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8742 return {SPF_SMAX, SPNB_NA, false};
8743
8744 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8745 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8746 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8747 return {SPF_SMIN, SPNB_NA, false};
8748
8749 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8750 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8751 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8752 return {SPF_UMAX, SPNB_NA, false};
8753
8754 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8755 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8756 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8757 return {SPF_UMIN, SPNB_NA, false};
8758 }
8759 return {SPF_UNKNOWN, SPNB_NA, false};
8760}
8761
8762/// Recognize variations of:
8763/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8765 Value *CmpLHS, Value *CmpRHS,
8766 Value *TVal, Value *FVal,
8767 unsigned Depth) {
8768 // TODO: Allow FP min/max with nnan/nsz.
8769 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8770
8771 Value *A = nullptr, *B = nullptr;
8772 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8773 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8774 return {SPF_UNKNOWN, SPNB_NA, false};
8775
8776 Value *C = nullptr, *D = nullptr;
8777 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8778 if (L.Flavor != R.Flavor)
8779 return {SPF_UNKNOWN, SPNB_NA, false};
8780
8781 // We have something like: x Pred y ? min(a, b) : min(c, d).
8782 // Try to match the compare to the min/max operations of the select operands.
8783 // First, make sure we have the right compare predicate.
8784 switch (L.Flavor) {
8785 case SPF_SMIN:
8786 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8787 Pred = ICmpInst::getSwappedPredicate(Pred);
8788 std::swap(CmpLHS, CmpRHS);
8789 }
8790 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8791 break;
8792 return {SPF_UNKNOWN, SPNB_NA, false};
8793 case SPF_SMAX:
8794 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8795 Pred = ICmpInst::getSwappedPredicate(Pred);
8796 std::swap(CmpLHS, CmpRHS);
8797 }
8798 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8799 break;
8800 return {SPF_UNKNOWN, SPNB_NA, false};
8801 case SPF_UMIN:
8802 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8803 Pred = ICmpInst::getSwappedPredicate(Pred);
8804 std::swap(CmpLHS, CmpRHS);
8805 }
8806 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8807 break;
8808 return {SPF_UNKNOWN, SPNB_NA, false};
8809 case SPF_UMAX:
8810 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8811 Pred = ICmpInst::getSwappedPredicate(Pred);
8812 std::swap(CmpLHS, CmpRHS);
8813 }
8814 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8815 break;
8816 return {SPF_UNKNOWN, SPNB_NA, false};
8817 default:
8818 return {SPF_UNKNOWN, SPNB_NA, false};
8819 }
8820
8821 // If there is a common operand in the already matched min/max and the other
8822 // min/max operands match the compare operands (either directly or inverted),
8823 // then this is min/max of the same flavor.
8824
8825 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8826 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8827 if (D == B) {
8828 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8829 match(A, m_Not(m_Specific(CmpRHS)))))
8830 return {L.Flavor, SPNB_NA, false};
8831 }
8832 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8833 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8834 if (C == B) {
8835 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8836 match(A, m_Not(m_Specific(CmpRHS)))))
8837 return {L.Flavor, SPNB_NA, false};
8838 }
8839 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8840 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8841 if (D == A) {
8842 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8843 match(B, m_Not(m_Specific(CmpRHS)))))
8844 return {L.Flavor, SPNB_NA, false};
8845 }
8846 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8847 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8848 if (C == A) {
8849 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8850 match(B, m_Not(m_Specific(CmpRHS)))))
8851 return {L.Flavor, SPNB_NA, false};
8852 }
8853
8854 return {SPF_UNKNOWN, SPNB_NA, false};
8855}
8856
8857/// If the input value is the result of a 'not' op, constant integer, or vector
8858/// splat of a constant integer, return the bitwise-not source value.
8859/// TODO: This could be extended to handle non-splat vector integer constants.
8861 Value *NotV;
8862 if (match(V, m_Not(m_Value(NotV))))
8863 return NotV;
8864
8865 const APInt *C;
8866 if (match(V, m_APInt(C)))
8867 return ConstantInt::get(V->getType(), ~(*C));
8868
8869 return nullptr;
8870}
8871
8872/// Match non-obvious integer minimum and maximum sequences.
8874 Value *CmpLHS, Value *CmpRHS,
8875 Value *TrueVal, Value *FalseVal,
8876 Value *&LHS, Value *&RHS,
8877 unsigned Depth) {
8878 // Assume success. If there's no match, callers should not use these anyway.
8879 LHS = TrueVal;
8880 RHS = FalseVal;
8881
8882 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8884 return SPR;
8885
8886 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8888 return SPR;
8889
8890 // Look through 'not' ops to find disguised min/max.
8891 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8892 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8893 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8894 switch (Pred) {
8895 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8896 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8897 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8898 case CmpInst::ICMP_ULT: return {