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"
21#include "llvm/ADT/StringRef.h"
30#include "llvm/Analysis/Loads.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
39#include "llvm/IR/Constant.h"
42#include "llvm/IR/Constants.h"
45#include "llvm/IR/Dominators.h"
47#include "llvm/IR/Function.h"
49#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
56#include "llvm/IR/Intrinsics.h"
57#include "llvm/IR/IntrinsicsAArch64.h"
58#include "llvm/IR/IntrinsicsAMDGPU.h"
59#include "llvm/IR/IntrinsicsRISCV.h"
60#include "llvm/IR/IntrinsicsX86.h"
61#include "llvm/IR/LLVMContext.h"
62#include "llvm/IR/Metadata.h"
63#include "llvm/IR/Module.h"
64#include "llvm/IR/Operator.h"
66#include "llvm/IR/Type.h"
67#include "llvm/IR/User.h"
68#include "llvm/IR/Value.h"
78#include <algorithm>
79#include <cassert>
80#include <cstdint>
81#include <optional>
82#include <utility>
83
84using namespace llvm;
85using namespace llvm::PatternMatch;
86
87// Controls the number of uses of the value searched for possible
88// dominating comparisons.
89static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
90 cl::Hidden, cl::init(20));
91
92/// Maximum number of instructions to check between assume and context
93/// instruction.
94static constexpr unsigned MaxInstrsToCheckForFree = 32;
95
96template <typename InstTy>
97static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
98 Value *&Init, Value *&OtherOp);
99
100/// Returns the bitwidth of the given scalar or pointer type. For vector types,
101/// returns the element type's bitwidth.
102static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
103 if (unsigned BitWidth = Ty->getScalarSizeInBits())
104 return BitWidth;
105
106 return DL.getPointerTypeSizeInBits(Ty);
107}
108
109// Given the provided Value and, potentially, a context instruction, return
110// the preferred context instruction (if any).
111static const Instruction *safeCtxI(const Value *V, const Instruction *CtxI) {
112 // If we've been provided with a context instruction, then use that (provided
113 // it has been inserted).
114 if (CtxI && CtxI->getParent())
115 return CtxI;
116
117 // If the value is really an already-inserted instruction, then use that.
118 CtxI = dyn_cast<Instruction>(V);
119 if (CtxI && CtxI->getParent())
120 return CtxI;
121
122 return nullptr;
123}
124
125static void computeKnownBits(const Value *V, const APInt &DemandedElts,
126 KnownBits &Known, const SimplifyQuery &Q,
127 unsigned Depth);
128
130 const SimplifyQuery &Q, unsigned Depth) {
131 // Since the number of lanes in a scalable vector is unknown at compile time,
132 // we track one bit which is implicitly broadcast to all lanes. This means
133 // that all lanes in a scalable vector are considered demanded.
134 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
135 APInt DemandedElts =
136 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
137 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
138}
139
141 const DataLayout &DL, AssumptionCache *AC,
142 const Instruction *CtxI, const DominatorTree *DT,
143 bool UseInstrInfo, unsigned Depth) {
145 SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
146 Depth);
147}
148
150 AssumptionCache *AC, const Instruction *CtxI,
151 const DominatorTree *DT, bool UseInstrInfo,
152 unsigned Depth) {
153 return computeKnownBits(
154 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
155}
156
159 const SimplifyQuery &SQ) {
160 // Look for an inverted mask: (X & ~M) op (Y & M).
161 {
162 Value *M;
163 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
165 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CtxI, SQ.DT)
168 }
169
170 // X op (Y & ~X)
172 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT)
175
176 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
177 // for constant Y.
178 Value *Y;
179 if (match(RHS,
181 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT) &&
182 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT);
183 return IsNoUndef ? NoCommonBitsSetResult::Known
185 }
186
187 // Peek through extends to find a 'not' of the other side:
188 // (ext Y) op ext(~Y)
189 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
191 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT)
194
195 // Look for: (A & B) op ~(A | B)
196 {
197 Value *A, *B;
198 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
200 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CtxI, SQ.DT) &&
201 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CtxI, SQ.DT);
202 return IsNoUndef ? NoCommonBitsSetResult::Known
204 }
205 }
206
207 // Look for: (X << V) op (Y >> (BitWidth - V))
208 // or (X >> V) op (Y << (BitWidth - V))
209 {
210 const Value *V;
211 const APInt *R;
212 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
214 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
215 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
216 R->uge(LHS->getType()->getScalarSizeInBits()))
218 }
219
221}
222
225 const WithCache<const Value *> &RHSCache,
226 const SimplifyQuery &SQ) {
227 const Value *LHS = LHSCache.getValue();
228 const Value *RHS = RHSCache.getValue();
229
230 assert(LHS->getType() == RHS->getType() &&
231 "LHS and RHS should have the same type");
232 assert(LHS->getType()->isIntOrIntVectorTy() &&
233 "LHS and RHS should be integers");
234
236 if (Result == NoCommonBitsSetResult::Known)
238
239 NoCommonBitsSetResult CommuteResult =
241 if (CommuteResult == NoCommonBitsSetResult::Known)
243
245 RHSCache.getKnownBits(SQ)))
247
251
253}
254
256 const WithCache<const Value *> &RHSCache,
257 const SimplifyQuery &SQ) {
258 NoCommonBitsSetResult Result =
259 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
260 return Result == NoCommonBitsSetResult::Known;
261}
262
264 return !I->user_empty() &&
265 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
266}
267
269 return !I->user_empty() && all_of(I->users(), [](const User *U) {
270 CmpPredicate P;
271 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
272 });
273}
274
275static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
276 const SimplifyQuery &Q, unsigned Depth);
277
279 unsigned Depth) {
280 return computeKnownBits(V, SQ, Depth).isNonNegative();
281}
282
284 const SimplifyQuery &SQ, unsigned Depth) {
285 if (auto *CI = dyn_cast<ConstantInt>(V.getValue()))
286 return CI->getValue().isStrictlyPositive();
287
288 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
289 // this updated.
290 KnownBits Known = Depth == 0 ? V.getKnownBits(SQ)
291 : computeKnownBits(V.getValue(), SQ, Depth);
292 return Known.isNonNegative() &&
293 (Known.isNonZero() || isKnownNonZero(V.getValue(), SQ, Depth));
294}
295
297 const SimplifyQuery &SQ, unsigned Depth) {
298 if (Depth == 0)
299 return V.getKnownBits(SQ).isNegative();
300 return computeKnownBits(V.getValue(), SQ, Depth).isNegative();
301}
302
303static bool isKnownNonEqual(const Value *V1, const Value *V2,
304 const APInt &DemandedElts, const SimplifyQuery &Q,
305 unsigned Depth);
306
308 const Value *RHS);
309
310bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
311 const SimplifyQuery &Q, unsigned Depth) {
312 // We don't support looking through casts.
313 if (V1 == V2 || V1->getType() != V2->getType())
314 return false;
315 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
316 APInt DemandedElts =
317 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
318 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
319}
320
321bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
322 const SimplifyQuery &SQ, unsigned Depth) {
323 KnownBits Known(Mask.getBitWidth());
325 return Mask.isSubsetOf(Known.Zero);
326}
327
328static unsigned computeNumSignBits(const Value *V, const APInt &DemandedElts,
329 const SimplifyQuery &Q, unsigned Depth);
330
331unsigned llvm::computeNumSignBits(const Value *V, const SimplifyQuery &Q,
332 unsigned Depth) {
333 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
334 APInt DemandedElts =
335 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
336 return ::computeNumSignBits(V, DemandedElts, Q, Depth);
337}
338
339unsigned llvm::computeNumSignBits(const Value *V, const DataLayout &DL,
340 AssumptionCache *AC, const Instruction *CtxI,
341 const DominatorTree *DT, bool UseInstrInfo,
342 unsigned Depth) {
343 return computeNumSignBits(
344 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
345}
346
348 const SimplifyQuery &SQ,
349 unsigned Depth) {
350 // TODO: Should use the SimplifyQuery API of ComputeNumSignBits.
351 unsigned SignBits = computeNumSignBits(V, SQ.DL, SQ.AC, SQ.CtxI, SQ.DT,
352 /*UseInstrInfo=*/true, Depth);
353 return V->getType()->getScalarSizeInBits() - SignBits + 1;
354}
355
356/// Try to detect the lerp pattern: a * (b - c) + c * d
357/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
358///
359/// In that particular case, we can use the following chain of reasoning:
360///
361/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
362///
363/// Since that is true for arbitrary a, b, c and d within our constraints, we
364/// can conclude that:
365///
366/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
367///
368/// Considering that any result of the lerp would be less or equal to U, it
369/// would have at least the number of leading 0s as in U.
370///
371/// While being quite a specific situation, it is fairly common in computer
372/// graphics in the shape of alpha blending.
373///
374/// Modifies given KnownOut in-place with the inferred information.
375static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
376 const APInt &DemandedElts,
377 KnownBits &KnownOut,
378 const SimplifyQuery &Q,
379 unsigned Depth) {
380
381 Type *Ty = Op0->getType();
382 const unsigned BitWidth = Ty->getScalarSizeInBits();
383
384 // Only handle scalar types for now
385 if (Ty->isVectorTy())
386 return;
387
388 // Try to match: a * (b - c) + c * d.
389 // When a == 1 => A == nullptr, the same applies to d/D as well.
390 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
391 const Instruction *SubBC = nullptr;
392
393 const auto MatchSubBC = [&]() {
394 // (b - c) can have two forms that interest us:
395 //
396 // 1. sub nuw %b, %c
397 // 2. xor %c, %b
398 //
399 // For the first case, nuw flag guarantees our requirement b >= c.
400 //
401 // The second case might happen when the analysis can infer that b is a mask
402 // for c and we can transform sub operation into xor (that is usually true
403 // for constant b's). Even though xor is symmetrical, canonicalization
404 // ensures that the constant will be the RHS. We have additional checks
405 // later on to ensure that this xor operation is equivalent to subtraction.
407 m_Xor(m_Value(C), m_Value(B))));
408 };
409
410 const auto MatchASubBC = [&]() {
411 // Cases:
412 // - a * (b - c)
413 // - (b - c) * a
414 // - (b - c) <- a implicitly equals 1
415 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
416 };
417
418 const auto MatchCD = [&]() {
419 // Cases:
420 // - d * c
421 // - c * d
422 // - c <- d implicitly equals 1
424 };
425
426 const auto Match = [&](const Value *LHS, const Value *RHS) {
427 // We do use m_Specific(C) in MatchCD, so we have to make sure that
428 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
429 // has to evaluate first and return true.
430 //
431 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
432 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
433 };
434
435 if (!Match(Op0, Op1) && !Match(Op1, Op0))
436 return;
437
438 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
439 // For some of the values we use the convention of leaving
440 // it nullptr to signify an implicit constant 1.
441 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
443 };
444
445 // Check that all operands are non-negative
446 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
447 if (!KnownA.isNonNegative())
448 return;
449
450 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
451 if (!KnownD.isNonNegative())
452 return;
453
454 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
455 if (!KnownB.isNonNegative())
456 return;
457
458 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
459 if (!KnownC.isNonNegative())
460 return;
461
462 // If we matched subtraction as xor, we need to actually check that xor
463 // is semantically equivalent to subtraction.
464 //
465 // For that to be true, b has to be a mask for c or that b's known
466 // ones cover all known and possible ones of c.
467 if (SubBC->getOpcode() == Instruction::Xor &&
468 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
469 return;
470
471 const APInt MaxA = KnownA.getMaxValue();
472 const APInt MaxD = KnownD.getMaxValue();
473 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
474 const APInt MaxB = KnownB.getMaxValue();
475
476 // We can't infer leading zeros info if the upper-bound estimate wraps.
477 bool Overflow;
478 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
479
480 if (Overflow)
481 return;
482
483 // If we know that x <= y and both are positive than x has at least the same
484 // number of leading zeros as y.
485 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
486 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
487}
488
489/// Infer non-negativity for R + (R < 0 ? A : 0), where R = srem X, Y.
490/// A must be a non-negative Y or abs(Y).
491static void computeKnownBitsFromEuclideanRem(const Value *Op0, const Value *Op1,
492 const APInt &DemandedElts,
493 KnownBits &KnownOut,
494 const SimplifyQuery &Q,
495 unsigned Depth) {
496 const Value *Divisor = nullptr, *Cond = nullptr, *Remainder = nullptr,
497 *AdjustmentValue = nullptr;
499 const APInt *Threshold = nullptr;
500 bool TrueIfNegative = false;
501
502 const auto Match = [&](const Value *Rem, const Value *Adjustment) {
503 Remainder = Rem;
504
505 // Match an adjustment added only when this remainder is negative.
506 return match(Rem, m_SRem(m_Value(), m_Value(Divisor))) &&
507 match(Adjustment,
508 m_Select(m_Value(Cond), m_Value(AdjustmentValue), m_Zero())) &&
509 match(Cond, m_ICmp(Pred, m_Specific(Rem), m_APInt(Threshold))) &&
510 isSignBitCheck(Pred, *Threshold, TrueIfNegative) && TrueIfNegative;
511 };
512
513 if (!Match(Op0, Op1) && !Match(Op1, Op0))
514 return;
515
516 // Accept Y itself if non-negative, or abs(Y).
517 // For vectors, only check the demanded elements.
518 bool IsPositiveDivisorCase =
519 Divisor == AdjustmentValue &&
520 computeKnownBits(Divisor, DemandedElts, Q, Depth + 1).isNonNegative();
521 bool IsAbsoluteValueCase =
522 match(AdjustmentValue,
524
525 if (!IsPositiveDivisorCase && !IsAbsoluteValueCase)
526 return;
527
528 // Repeated uses must agree. An undef value could break this relationship.
529 // For vectors, this check is conservative (checks the entire vector, not just
530 // the demanded elements).
531 if (!isGuaranteedNotToBeUndef(Remainder, Q.AC, Q.CtxI, Q.DT, Depth + 1) ||
532 !isGuaranteedNotToBeUndef(Divisor, Q.AC, Q.CtxI, Q.DT, Depth + 1))
533 return;
534
535 // For Y other than signed minimum, adding abs(Y) to a negative remainder
536 // gives a non-negative result without overflow. For signed minimum, the
537 // wrapping addition clears the remainder's sign bit. Poison-producing cases
538 // do not invalidate this deduction.
539 KnownOut.makeNonNegative();
540}
541
542static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
543 bool NSW, bool NUW,
544 const APInt &DemandedElts,
545 KnownBits &KnownOut, KnownBits &Known2,
546 const SimplifyQuery &Q, unsigned Depth) {
547 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
548
549 if (KnownOut.isUnknown() && !NSW && !NUW) {
550 if (Add) {
551 // Independent operand bits give no result, but the Euclidean remainder
552 // pattern can establish non-negativity through the operands'
553 // relationship.
554 computeKnownBitsFromEuclideanRem(Op0, Op1, DemandedElts, KnownOut, Q,
555 Depth);
556 }
557 return;
558 }
559
560 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
561 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
562
563 if (!Add && NSW && !KnownOut.isNonNegative() &&
565 .value_or(false) ||
566 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
567 KnownOut.makeNonNegative();
568
569 if (Add) {
570 // Try to match lerp pattern and combine results
571 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
572
573 // Use the relationship between the remainder and its adjustment.
574 computeKnownBitsFromEuclideanRem(Op0, Op1, DemandedElts, KnownOut, Q,
575 Depth);
576 }
577}
578
579static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
580 bool NUW, const APInt &DemandedElts,
581 KnownBits &Known, KnownBits &Known2,
582 const SimplifyQuery &Q, unsigned Depth) {
583 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
584 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
585
586 bool isKnownNegative = false;
587 bool isKnownNonNegative = false;
588 // If the multiplication is known not to overflow, compute the sign bit.
589 if (NSW) {
590 if (Op0 == Op1) {
591 // The product of a number with itself is non-negative.
592 isKnownNonNegative = true;
593 } else {
594 bool isKnownNonNegativeOp1 = Known.isNonNegative();
595 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
596 bool isKnownNegativeOp1 = Known.isNegative();
597 bool isKnownNegativeOp0 = Known2.isNegative();
598 // The product of two numbers with the same sign is non-negative.
599 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
600 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
601 if (!isKnownNonNegative && NUW) {
602 // mul nuw nsw with a factor > 1 is non-negative.
603 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
604 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
605 KnownBits::sgt(Known2, One).value_or(false);
606 }
607
608 // The product of a negative number and a non-negative number is either
609 // negative or zero.
612 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
613 Known2.isNonZero()) ||
614 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
615 }
616 }
617
618 bool SelfMultiply = Op0 == Op1;
619 if (SelfMultiply)
620 SelfMultiply &=
621 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CtxI, Q.DT, Depth + 1);
622 Known = KnownBits::mul(Known, Known2, SelfMultiply);
623
624 if (SelfMultiply) {
625 unsigned SignBits = computeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
626 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
627 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
628
629 if (OutValidBits < TyBits) {
630 APInt KnownZeroMask =
631 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
632 Known.Zero |= KnownZeroMask;
633 }
634 }
635
636 // Only make use of no-wrap flags if we failed to compute the sign bit
637 // directly. This matters if the multiplication always overflows, in
638 // which case we prefer to follow the result of the direct computation,
639 // though as the program is invoking undefined behaviour we can choose
640 // whatever we like here.
641 if (isKnownNonNegative && !Known.isNegative())
642 Known.makeNonNegative();
643 else if (isKnownNegative && !Known.isNonNegative())
644 Known.makeNegative();
645}
646
648 KnownBits &Known) {
649 unsigned BitWidth = Known.getBitWidth();
650 unsigned NumRanges = Ranges.getNumOperands() / 2;
651 assert(NumRanges >= 1);
652
653 Known.setAllConflict();
654
655 for (unsigned i = 0; i < NumRanges; ++i) {
657 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
659 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
660 ConstantRange Range(Lower->getValue(), Upper->getValue());
661 // BitWidth must equal the Ranges BitWidth for the correct number of high
662 // bits to be set.
663 assert(BitWidth == Range.getBitWidth() &&
664 "Known bit width must match range bit width!");
665
666 // The first CommonPrefixBits of all values in Range are equal.
667 unsigned CommonPrefixBits =
668 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
669 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
670 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
671 Known.One &= UnsignedMax & Mask;
672 Known.Zero &= ~UnsignedMax & Mask;
673 }
674}
675
676static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
677 // The instruction defining an assumption's condition itself is always
678 // considered ephemeral to that assumption (even if it has other
679 // non-ephemeral users). See r246696's test case for an example.
680 if (is_contained(I->operands(), E))
681 return true;
682
683 const auto *EI = dyn_cast<Instruction>(E);
684 if (!EI)
685 return false;
686
687 if (EI == I)
688 return true;
689
692 Visited.insert(EI);
693 WorkList.push_back(EI);
694 bool ReachesI = false;
695 while (!WorkList.empty()) {
696 const Instruction *V = WorkList.pop_back_val();
697 for (const Instruction *UI : V->users()) {
698 if (UI == I) {
699 ReachesI = true;
700 continue;
701 }
702 if (UI->mayHaveSideEffects() || UI->isTerminator())
703 return false;
704 if (Visited.insert(UI).second)
705 WorkList.push_back(UI);
706 }
707 }
708 return ReachesI;
709}
710
711// Is this an intrinsic that cannot be speculated but also cannot trap?
713 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
714 return CI->isAssumeLikeIntrinsic();
715
716 return false;
717}
718
720 const Instruction *CtxI,
721 const DominatorTree *DT,
722 bool AllowEphemerals) {
723 // There are two restrictions on the use of an assume:
724 // 1. The assume must dominate the context (or the control flow must
725 // reach the assume whenever it reaches the context).
726 // 2. The context must not be in the assume's set of ephemeral values
727 // (otherwise we will use the assume to prove that the condition
728 // feeding the assume is trivially true, thus causing the removal of
729 // the assume).
730
731 // If the checked instruction and the assume are the same, it's valid exactly
732 // if ephemeral values are allowed.
733 if (Inv == CtxI)
734 return AllowEphemerals;
735
736 if (Inv->getParent() == CtxI->getParent()) {
737 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
738 // in the BB.
739 if (Inv->comesBefore(CtxI))
740 return true;
741
742 // The context comes first, but they're both in the same block.
743 // Make sure there is nothing in between that might interrupt
744 // the control flow, not even CtxI itself.
745 // We limit the scan distance between the assume and its context instruction
746 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
747 // it can be adjusted if needed (could be turned into a cl::opt).
748 auto Range = make_range(CtxI->getIterator(), Inv->getIterator());
750 return false;
751
752 return AllowEphemerals || !isEphemeralValueOf(Inv, CtxI);
753 }
754
755 // Inv and CtxI are in different blocks.
756 if (DT) {
757 if (DT->dominates(Inv, CtxI))
758 return true;
759 } else if (Inv->getParent() == CtxI->getParent()->getSinglePredecessor() ||
760 Inv->getParent()->isEntryBlock()) {
761 // We don't have a DT, but this trivially dominates.
762 return true;
763 }
764
765 return false;
766}
767
770 unsigned &NumChecked) {
771 for (const Instruction &I : make_range(Begin, End)) {
772 if (NumChecked++ > MaxInstrsToCheckForFree)
773 return false;
774 if (auto *CB = dyn_cast<CallBase>(&I)) {
775 if (!CB->hasFnAttr(Attribute::NoFree))
776 return false;
777 } else if (I.maySynchronize()) {
778 return false;
779 }
780 }
781 return true;
782}
783
785 const Instruction *CtxI,
786 const DominatorTree *DT) {
787 const BasicBlock *CtxBB = CtxI->getParent();
788 const BasicBlock *AssumeBB = Assume->getParent();
789 unsigned NumChecked = 0;
790 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
791 if (CtxBB == AssumeBB) {
792 if (Assume != CtxI && !Assume->comesBefore(CtxI))
793 return false;
794 return hasNoFreeInRange(Assume->getIterator(), CtxIter, NumChecked);
795 }
796 if (DT && !DT->dominates(Assume, CtxI))
797 return false;
798 if (!hasNoFreeInRange(CtxBB->begin(), CtxIter, NumChecked))
799 return false;
800 if (pred_empty(CtxBB))
801 return false;
802
803 // Note: CtxBB is NOT pre-inserted into Visited to ensure that loop
804 // backedges returning to CtxBB are enqueued and checked correctly.
807 while (!Worklist.empty()) {
808 const BasicBlock *CurBB = Worklist.pop_back_val();
809 if (!Visited.insert(CurBB).second)
810 continue;
811
812 if (CurBB == AssumeBB) {
813 if (!hasNoFreeInRange(Assume->getIterator(), AssumeBB->end(), NumChecked))
814 return false;
815 continue;
816 }
817 assert((!DT || DT->dominates(AssumeBB, CurBB)) &&
818 "Blocks between Assume and CtxI must be dominated by AssumeBB");
819
820 if (pred_empty(CurBB)) {
821 // Reaching the entry block means there is a path to CtxI that does not
822 // pass through Assume.
823 if (CurBB->isEntryBlock())
824 return false;
825
826 // CurBB is unreachable (for example, emptied by SimplifyCFG but not yet
827 // removed), so nothing in it can execute a free.
828 continue;
829 }
830
831 // If CurBB == CtxBB (due to a loop backedge targeting CtxBB), check
832 // instructions from CtxIter to the end of CtxBB (instructions before
833 // CtxIter were checked above). Otherwise, check the entire block.
834 auto StartIt = (CurBB == CtxBB) ? CtxIter : CurBB->begin();
835 if (!hasNoFreeInRange(StartIt, CurBB->end(), NumChecked))
836 return false;
837 append_range(Worklist, predecessors(CurBB));
838 }
839 return true;
840}
841
842// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
843// we still have enough information about `RHS` to conclude non-zero. For
844// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
845// so the extra compile time may not be worth it, but possibly a second API
846// should be created for use outside of loops.
848 // v u> y implies v != 0.
850 return true;
851
852 // Special-case v != 0 to also handle v != null.
853 if (Pred == ICmpInst::ICMP_NE)
854 return match(RHS, m_Zero());
855
856 // All other predicates - rely on generic ConstantRange handling.
857 const APInt *C;
858 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
859 if (match(RHS, m_APInt(C))) {
861 return !TrueValues.contains(Zero);
862 }
863
865 if (VC == nullptr)
866 return false;
867
868 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
869 ++ElemIdx) {
871 Pred, VC->getElementAsAPInt(ElemIdx));
872 if (TrueValues.contains(Zero))
873 return false;
874 }
875 return true;
876}
877
879 Value *&ValOut, Instruction *&CtxIOut,
880 const PHINode **PhiOut) {
881 ValOut = U->get();
882 if (ValOut == PHI)
883 return;
884 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
885 if (PhiOut)
886 *PhiOut = PHI;
887 Value *V;
888 // If the Use is a select of this phi, compute analysis on other arm to break
889 // recursion.
890 // TODO: Min/Max
891 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
892 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
893 ValOut = V;
894
895 // Same for select, if this phi is 2-operand phi, compute analysis on other
896 // incoming value to break recursion.
897 // TODO: We could handle any number of incoming edges as long as we only have
898 // two unique values.
899 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
900 IncPhi && IncPhi->getNumIncomingValues() == 2) {
901 for (int Idx = 0; Idx < 2; ++Idx) {
902 if (IncPhi->getIncomingValue(Idx) == PHI) {
903 ValOut = IncPhi->getIncomingValue(1 - Idx);
904 if (PhiOut)
905 *PhiOut = IncPhi;
906 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
907 break;
908 }
909 }
910 }
911}
912
913static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
914 // Use of assumptions is context-sensitive. If we don't have a context, we
915 // cannot use them!
916 if (!Q.AC || !Q.CtxI)
917 return false;
918
920 if (!Elem.Assume)
921 continue;
922
923 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
924 assert(I->getFunction() == Q.CtxI->getFunction() &&
925 "Got assumption for the wrong function!");
926
927 if (Elem.Index != AssumptionCache::ExprResultIdx) {
929 I->getOperandBundleAt(Elem.Index)) &&
931 return true;
932 continue;
933 }
934
935 // Warning: This loop can end up being somewhat performance sensitive.
936 // We're running this loop for once for each value queried resulting in a
937 // runtime of ~O(#assumes * #values).
938
939 if (match(I->getArgOperand(0), m_Trunc(m_Specific(V))) &&
941 return true;
942
943 Value *RHS;
946 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
947 continue;
948
950 return true;
951 }
952
953 return false;
954}
955
958 const SimplifyQuery &Q) {
959 if (RHS->getType()->isPointerTy()) {
960 // Handle comparison of pointer to null explicitly, as it will not be
961 // covered by the m_APInt() logic below.
962 if (LHS == V && match(RHS, m_Zero())) {
963 switch (Pred) {
965 Known.setAllZero();
966 break;
969 Known.makeNonNegative();
970 break;
972 Known.makeNegative();
973 break;
974 default:
975 break;
976 }
977 }
978 return;
979 }
980
981 unsigned BitWidth = Known.getBitWidth();
982 auto m_V =
984
985 Value *Y;
986 const APInt *Mask, *C;
987 if (!match(RHS, m_APInt(C)))
988 return;
989
990 uint64_t ShAmt;
991 switch (Pred) {
993 // assume(V = C)
994 if (match(LHS, m_V)) {
995 Known = Known.unionWith(KnownBits::makeConstant(*C));
996 // assume(V & Mask = C)
997 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
998 // For one bits in Mask, we can propagate bits from C to V.
999 Known.One |= *C;
1000 if (match(Y, m_APInt(Mask)))
1001 Known.Zero |= ~*C & *Mask;
1002 // assume(V | Mask = C)
1003 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
1004 // For zero bits in Mask, we can propagate bits from C to V.
1005 Known.Zero |= ~*C;
1006 if (match(Y, m_APInt(Mask)))
1007 Known.One |= *C & ~*Mask;
1008 // assume(V << ShAmt = C)
1009 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
1010 ShAmt < BitWidth) {
1011 // For those bits in C that are known, we can propagate them to known
1012 // bits in V shifted to the right by ShAmt.
1013 KnownBits RHSKnown = KnownBits::makeConstant(*C);
1014 RHSKnown >>= ShAmt;
1015 Known = Known.unionWith(RHSKnown);
1016 // assume(V >> ShAmt = C)
1017 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
1018 ShAmt < BitWidth) {
1019 // For those bits in RHS that are known, we can propagate them to known
1020 // bits in V shifted to the right by C.
1021 KnownBits RHSKnown = KnownBits::makeConstant(*C);
1022 RHSKnown <<= ShAmt;
1023 Known = Known.unionWith(RHSKnown);
1024 }
1025 break;
1026 case ICmpInst::ICMP_NE: {
1027 // assume (V & B != 0) where B is a power of 2
1028 const APInt *BPow2;
1029 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
1030 Known.One |= *BPow2;
1031 break;
1032 }
1033 default: {
1034 const APInt *Offset = nullptr;
1035 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
1037 if (Offset)
1038 LHSRange = LHSRange.sub(*Offset);
1039 Known = Known.unionWith(LHSRange.toKnownBits());
1040 }
1042 // X & Y u> C -> X u> C && Y u> C
1043 // X nuw- Y u> C -> X u> C
1044 if (match(LHS, m_c_And(m_V, m_Value())) ||
1045 match(LHS, m_NUWSub(m_V, m_Value())))
1046 Known.One.setHighBits(
1047 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
1048 }
1050 // X | Y u< C -> X u< C && Y u< C
1051 // X nuw+ Y u< C -> X u< C && Y u< C
1052 if (match(LHS, m_c_Or(m_V, m_Value())) ||
1053 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
1054 Known.Zero.setHighBits(
1055 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
1056 }
1057 }
1058 if (Pred == ICmpInst::ICMP_SGT) {
1059 // X | Y s> -1 -> X s> -1 && Y s> -1
1060 if (C->isAllOnes() && match(LHS, m_c_Or(m_V, m_Value())))
1061 Known.makeNonNegative();
1062 }
1063 if (Pred == ICmpInst::ICMP_SLT) {
1064 // X & Y s< 0 -> X s< 0 && Y s< 0
1065 if (C->isZero() && match(LHS, m_c_And(m_V, m_Value())))
1066 Known.makeNegative();
1067 }
1068 } break;
1069 }
1070}
1071
1074 const SimplifyQuery &SQ, bool Invert) {
1076 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1077 Value *LHS = Cmp->getOperand(0);
1078 Value *RHS = Cmp->getOperand(1);
1079
1080 // Handle icmp pred (trunc V), C
1081 if (match(LHS, m_Trunc(m_Specific(V)))) {
1082 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1083 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1085 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1086 else
1087 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1088 return;
1089 }
1090
1092}
1093
1095 KnownBits &Known, const SimplifyQuery &SQ,
1096 bool Invert, unsigned Depth) {
1097 Value *A, *B;
1100 KnownBits Known2(Known.getBitWidth());
1101 KnownBits Known3(Known.getBitWidth());
1102 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1103 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1104 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1106 Known2 = Known2.unionWith(Known3);
1107 else
1108 Known2 = Known2.intersectWith(Known3);
1109 Known = Known.unionWith(Known2);
1110 return;
1111 }
1112
1113 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1114 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1115 return;
1116 }
1117
1118 if (match(Cond, m_Trunc(m_Specific(V)))) {
1119 KnownBits DstKnown(1);
1120 if (Invert) {
1121 DstKnown.setAllZero();
1122 } else {
1123 DstKnown.setAllOnes();
1124 }
1126 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1127 return;
1128 }
1129 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1130 return;
1131 }
1132
1134 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1135}
1136
1138 const SimplifyQuery &Q, unsigned Depth) {
1139 // Handle injected condition.
1140 if (Q.CC && Q.CC->AffectedValues.contains(V))
1142
1143 if (!Q.CtxI)
1144 return;
1145
1146 if (Q.DC && Q.DT) {
1147 // Handle dominating conditions.
1148 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1149 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1150 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
1151 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1152 /*Invert*/ false, Depth);
1153
1154 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1155 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
1156 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1157 /*Invert*/ true, Depth);
1158 }
1159
1160 if (Known.hasConflict())
1161 Known.resetAll();
1162 }
1163
1164 if (!Q.AC)
1165 return;
1166
1167 unsigned BitWidth = Known.getBitWidth();
1168
1169 // Note that the patterns below need to be kept in sync with the code
1170 // in AssumptionCache::updateAffectedValues.
1171
1172 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1173 if (!Elem.Assume)
1174 continue;
1175
1176 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1177 assert(I->getParent()->getParent() == Q.CtxI->getParent()->getParent() &&
1178 "Got assumption for the wrong function!");
1179
1180 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1181 auto OBU = I->getOperandBundleAt(Elem.Index);
1182 switch (getBundleAttrFromOBU(OBU)) {
1183 case BundleAttr::Align: {
1184 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1185 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1187 Known.Zero |= (*Alignment - 1) & ~*Offset;
1188 Known.One |= (*Alignment - 1) & *Offset;
1189 }
1190 } break;
1191
1192 case BundleAttr::Range: {
1193 auto [Val, Range] = getAssumeRangeInfo(OBU);
1194 if (Val == V && isValidAssumeForContext(I, Q))
1195 Known = Known.unionWith(Range.toKnownBits());
1196 } break;
1197
1198 default:
1199 break;
1200 }
1201 continue;
1202 }
1203
1204 // Warning: This loop can end up being somewhat performance sensitive.
1205 // We're running this loop for once for each value queried resulting in a
1206 // runtime of ~O(#assumes * #values).
1207
1208 Value *Arg = I->getArgOperand(0);
1209
1210 if (Arg == V && isValidAssumeForContext(I, Q)) {
1211 assert(BitWidth == 1 && "assume operand is not i1?");
1212 (void)BitWidth;
1213 Known.setAllOnes();
1214 return;
1215 }
1216 if (match(Arg, m_Not(m_Specific(V))) &&
1218 assert(BitWidth == 1 && "assume operand is not i1?");
1219 (void)BitWidth;
1220 Known.setAllZero();
1221 return;
1222 }
1223 auto *Trunc = dyn_cast<TruncInst>(Arg);
1224 if (Trunc && Trunc->getOperand(0) == V &&
1226 if (Trunc->hasNoUnsignedWrap()) {
1228 return;
1229 }
1230 Known.One.setBit(0);
1231 return;
1232 }
1233
1234 // The remaining tests are all recursive, so bail out if we hit the limit.
1236 continue;
1237
1238 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1239 if (!Cmp)
1240 continue;
1241
1242 if (!isValidAssumeForContext(I, Q))
1243 continue;
1244
1245 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1246 }
1247
1248 // Conflicting assumption: Undefined behavior will occur on this execution
1249 // path.
1250 if (Known.hasConflict())
1251 Known.resetAll();
1252}
1253
1254/// Compute known bits from a shift operator, including those with a
1255/// non-constant shift amount. Known is the output of this function. Known2 is a
1256/// pre-allocated temporary with the same bit width as Known and on return
1257/// contains the known bit of the shift value source. KF is an
1258/// operator-specific function that, given the known-bits and a shift amount,
1259/// compute the implied known-bits of the shift operator's result respectively
1260/// for that shift amount. The results from calling KF are conservatively
1261/// combined for all permitted shift amounts.
1263 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1264 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1265 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1266 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1267 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1268 // To limit compile-time impact, only query isKnownNonZero() if we know at
1269 // least something about the shift amount.
1270 bool ShAmtNonZero =
1271 Known.isNonZero() ||
1272 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1273 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1274 Known = KF(Known2, Known, ShAmtNonZero);
1275}
1276
1277static KnownBits
1278getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1279 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1280 const SimplifyQuery &Q, unsigned Depth) {
1281 unsigned BitWidth = KnownLHS.getBitWidth();
1282 KnownBits KnownOut(BitWidth);
1283 bool IsAnd = false;
1284 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1285 Value *X = nullptr, *Y = nullptr;
1286
1287 switch (I->getOpcode()) {
1288 case Instruction::And:
1289 KnownOut = KnownLHS & KnownRHS;
1290 IsAnd = true;
1291 // and(x, -x) is common idioms that will clear all but lowest set
1292 // bit. If we have a single known bit in x, we can clear all bits
1293 // above it.
1294 // TODO: instcombine often reassociates independent `and` which can hide
1295 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1296 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1297 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1298 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1299 KnownOut = KnownLHS.blsi();
1300 else
1301 KnownOut = KnownRHS.blsi();
1302 }
1303 break;
1304 case Instruction::Or:
1305 KnownOut = KnownLHS | KnownRHS;
1306 break;
1307 case Instruction::Xor:
1308 KnownOut = KnownLHS ^ KnownRHS;
1309 // xor(x, x-1) is common idioms that will clear all but lowest set
1310 // bit. If we have a single known bit in x, we can clear all bits
1311 // above it.
1312 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1313 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1314 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1315 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1316 if (HasKnownOne &&
1318 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1319 KnownOut = XBits.blsmsk();
1320 }
1321 break;
1322 default:
1323 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1324 }
1325
1326 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1327 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1328 // here we handle the more general case of adding any odd number by
1329 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1330 // TODO: This could be generalized to clearing any bit set in y where the
1331 // following bit is known to be unset in y.
1332 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1336 KnownBits KnownY(BitWidth);
1337 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1338 if (KnownY.countMinTrailingOnes() > 0) {
1339 if (IsAnd)
1340 KnownOut.Zero.setBit(0);
1341 else
1342 KnownOut.One.setBit(0);
1343 }
1344 }
1345 return KnownOut;
1346}
1347
1349 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1350 unsigned Depth,
1351 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1352 KnownBitsFunc) {
1353 APInt DemandedEltsLHS, DemandedEltsRHS;
1355 DemandedElts, DemandedEltsLHS,
1356 DemandedEltsRHS);
1357
1358 const auto ComputeForSingleOpFunc =
1359 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1360 return KnownBitsFunc(
1361 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1362 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1363 };
1364
1365 if (DemandedEltsRHS.isZero())
1366 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1367 if (DemandedEltsLHS.isZero())
1368 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1369
1370 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1371 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1372}
1373
1374// Public so this can be used in `SimplifyDemandedUseBits`.
1376 const KnownBits &KnownLHS,
1377 const KnownBits &KnownRHS,
1378 const SimplifyQuery &SQ,
1379 unsigned Depth) {
1380 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1381 APInt DemandedElts =
1382 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1383
1384 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1385 Depth);
1386}
1387
1389 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1390 // Without vscale_range, we only know that vscale is non-zero.
1391 if (!Attr.isValid())
1393
1394 unsigned AttrMin = Attr.getVScaleRangeMin();
1395 // Minimum is larger than vscale width, result is always poison.
1396 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1397 return ConstantRange::getEmpty(BitWidth);
1398
1399 APInt Min(BitWidth, AttrMin);
1400 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1401 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1403
1404 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1405}
1406
1407/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1408/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1409/// target's VLEN range. Callers must ensure the target is RISC-V.
1410static bool isReadVLENB(const IntrinsicInst &II) {
1411 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1412 if (!MAV)
1413 return false;
1414 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1415 if (!MD || MD->getNumOperands() != 1)
1416 return false;
1417 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1418 return RegName && RegName->getString() == "vlenb";
1419}
1420
1421/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1422/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1423/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1424/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1425/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1426/// attribute, when present, pins the subtarget's VLEN in units of
1427/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1428/// RVVBytesPerBlock.
1430 unsigned Width) {
1431 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1432 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1433
1434 const Function *F = II.getFunction();
1435 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1436 ConstantRange VScale = getVScaleRange(F, Width);
1437 Range = Range.intersectWith(
1439 }
1440 return Range;
1441}
1442
1444 Value *Arm, bool Invert,
1445 const SimplifyQuery &Q, unsigned Depth) {
1446 // If we have a constant arm, we are done.
1447 if (Known.isConstant())
1448 return;
1449
1450 // See what condition implies about the bits of the select arm.
1451 KnownBits CondRes(Known.getBitWidth());
1452 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1453 // If we don't get any information from the condition, no reason to
1454 // proceed.
1455 if (CondRes.isUnknown())
1456 return;
1457
1458 // We can have conflict if the condition is dead. I.e if we have
1459 // (x | 64) < 32 ? (x | 64) : y
1460 // we will have conflict at bit 6 from the condition/the `or`.
1461 // In that case just return. Its not particularly important
1462 // what we do, as this select is going to be simplified soon.
1463 CondRes = CondRes.unionWith(Known);
1464 if (CondRes.hasConflict())
1465 return;
1466
1467 // Finally make sure the information we found is valid. This is relatively
1468 // expensive so it's left for the very end.
1469 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CtxI, Q.DT, Depth + 1))
1470 return;
1471
1472 // Finally, we know we get information from the condition and its valid,
1473 // so return it.
1474 Known = std::move(CondRes);
1475}
1476
1477// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1478// Returns the input and lower/upper bounds.
1479static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1480 const APInt *&CLow, const APInt *&CHigh) {
1482 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1483 "Input should be a Select!");
1484
1485 const Value *LHS = nullptr, *RHS = nullptr;
1487 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1488 return false;
1489
1490 if (!match(RHS, m_APInt(CLow)))
1491 return false;
1492
1493 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1495 if (getInverseMinMaxFlavor(SPF) != SPF2)
1496 return false;
1497
1498 if (!match(RHS2, m_APInt(CHigh)))
1499 return false;
1500
1501 if (SPF == SPF_SMIN)
1502 std::swap(CLow, CHigh);
1503
1504 In = LHS2;
1505 return CLow->sle(*CHigh);
1506}
1507
1509 const APInt *&CLow,
1510 const APInt *&CHigh) {
1511 assert((II->getIntrinsicID() == Intrinsic::smin ||
1512 II->getIntrinsicID() == Intrinsic::smax) &&
1513 "Must be smin/smax");
1514
1515 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1516 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1517 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1518 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1519 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1520 return false;
1521
1522 if (II->getIntrinsicID() == Intrinsic::smin)
1523 std::swap(CLow, CHigh);
1524 return CLow->sle(*CHigh);
1525}
1526
1528 KnownBits &Known) {
1529 const APInt *CLow, *CHigh;
1530 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1531 Known = Known.unionWith(
1532 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1533}
1534
1536 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1537 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1538 unsigned Depth) {
1539 // Change the context instruction to the "edge" that flows into the phi. This
1540 // is important because that is where the value is actually "evaluated" even
1541 // though it is used later somewhere else. (see also D69571).
1543 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1544
1545 RecQ.CtxI = P->getIncomingBlock(OpNum)->getTerminator();
1546 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1547
1548 RecQ.CtxI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1549 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1550}
1551
1553 const APInt &DemandedElts,
1555 const SimplifyQuery &Q,
1556 unsigned Depth) {
1557 unsigned BitWidth = Known.getBitWidth();
1558
1559 KnownBits Known2(BitWidth);
1560 switch (I->getOpcode()) {
1561 default: break;
1562 case Instruction::Load:
1563 if (MDNode *MD =
1564 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1566 break;
1567 case Instruction::And:
1568 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1569 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1570
1571 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1572 break;
1573 case Instruction::Or:
1574 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1575 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1576
1577 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1578 break;
1579 case Instruction::Xor:
1580 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1581 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1582
1583 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1584 break;
1585 case Instruction::Mul: {
1588 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1589 DemandedElts, Known, Known2, Q, Depth);
1590 break;
1591 }
1592 case Instruction::UDiv: {
1593 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1594 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1595 Known =
1597 break;
1598 }
1599 case Instruction::SDiv: {
1600 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1601 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1602 Known =
1604 break;
1605 }
1606 case Instruction::Select: {
1607 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1608 KnownBits Res(Known.getBitWidth());
1609 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1610 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1611 return Res;
1612 };
1613 // Only known if known in both the LHS and RHS.
1614 Known =
1615 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1616 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1617 break;
1618 }
1619 case Instruction::FPToSI: {
1620 // fptosi is poison if the rounded value doesn't fit in the result type,
1621 // so we can assume the conversion is well-defined and rounds towards
1622 // zero. +-Inf can never fit in an integer type, so it is always poison,
1623 // like NaN. Negative subnormals and negative zero round to 0. That
1624 // leaves negative normals as the only class that can produce a defined
1625 // negative result.
1626 KnownFPClass SrcFPClass = computeKnownFPClass(
1627 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1628 if (SrcFPClass.isKnownNever(fcNegNormal))
1629 Known.makeNonNegative();
1630 break;
1631 }
1632 case Instruction::FPTrunc:
1633 case Instruction::FPExt:
1634 case Instruction::FPToUI:
1635 case Instruction::SIToFP:
1636 case Instruction::UIToFP:
1637 break; // Can't work with floating point.
1638 case Instruction::PtrToInt:
1639 case Instruction::PtrToAddr:
1640 case Instruction::IntToPtr:
1641 // Fall through and handle them the same as zext/trunc.
1642 [[fallthrough]];
1643 case Instruction::ZExt:
1644 case Instruction::Trunc: {
1645 Type *SrcTy = I->getOperand(0)->getType();
1646
1647 unsigned SrcBitWidth;
1648 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1649 // which fall through here.
1650 Type *ScalarTy = SrcTy->getScalarType();
1651 SrcBitWidth = ScalarTy->isPointerTy() ?
1652 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1653 Q.DL.getTypeSizeInBits(ScalarTy);
1654
1655 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1656 Known = Known.anyextOrTrunc(SrcBitWidth);
1657 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1658 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1659 Inst && Inst->hasNonNeg() && !Known.isNegative())
1660 Known.makeNonNegative();
1661 Known = Known.zextOrTrunc(BitWidth);
1662 break;
1663 }
1664 case Instruction::BitCast: {
1665 Type *SrcTy = I->getOperand(0)->getType();
1666 if (SrcTy->isIntOrPtrTy() &&
1667 // TODO: For now, not handling conversions like:
1668 // (bitcast i64 %x to <2 x i32>)
1669 !I->getType()->isVectorTy()) {
1670 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1671 break;
1672 }
1673
1674 const Value *V;
1675 // Handle bitcast from floating point to integer.
1677 V->getType()->isFPOrFPVectorTy()) {
1678 Type *FPType = V->getType()->getScalarType();
1679 KnownFPClass Result =
1680 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1681
1682 Known = Result.toKnownBits(FPType->getFltSemantics());
1683
1684 break;
1685 }
1686
1687 // Handle cast from vector integer type to scalar or vector integer.
1688 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1689 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1690 !I->getType()->isIntOrIntVectorTy() ||
1691 isa<ScalableVectorType>(I->getType()))
1692 break;
1693
1694 unsigned NumElts = DemandedElts.getBitWidth();
1695 bool IsLE = Q.DL.isLittleEndian();
1696 // Look through a cast from narrow vector elements to wider type.
1697 // Examples: v4i32 -> v2i64, v3i8 -> v24
1698 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1699 if (BitWidth % SubBitWidth == 0) {
1700 // Known bits are automatically intersected across demanded elements of a
1701 // vector. So for example, if a bit is computed as known zero, it must be
1702 // zero across all demanded elements of the vector.
1703 //
1704 // For this bitcast, each demanded element of the output is sub-divided
1705 // across a set of smaller vector elements in the source vector. To get
1706 // the known bits for an entire element of the output, compute the known
1707 // bits for each sub-element sequentially. This is done by shifting the
1708 // one-set-bit demanded elements parameter across the sub-elements for
1709 // consecutive calls to computeKnownBits. We are using the demanded
1710 // elements parameter as a mask operator.
1711 //
1712 // The known bits of each sub-element are then inserted into place
1713 // (dependent on endian) to form the full result of known bits.
1714 unsigned SubScale = BitWidth / SubBitWidth;
1715 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1716 for (unsigned i = 0; i != NumElts; ++i) {
1717 if (DemandedElts[i])
1718 SubDemandedElts.setBit(i * SubScale);
1719 }
1720
1721 KnownBits KnownSrc(SubBitWidth);
1722 for (unsigned i = 0; i != SubScale; ++i) {
1723 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1724 Depth + 1);
1725 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1726 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1727 }
1728 }
1729 // Look through a cast from wider vector elements to narrow type.
1730 // Examples: v2i64 -> v4i32
1731 if (SubBitWidth % BitWidth == 0) {
1732 unsigned SubScale = SubBitWidth / BitWidth;
1733 KnownBits KnownSrc(SubBitWidth);
1734 APInt SubDemandedElts =
1735 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1736 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1737 Depth + 1);
1738
1739 Known.setAllConflict();
1740 for (unsigned i = 0; i != NumElts; ++i) {
1741 if (DemandedElts[i]) {
1742 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1743 unsigned Offset = (Shifts % SubScale) * BitWidth;
1744 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1745 if (Known.isUnknown())
1746 break;
1747 }
1748 }
1749 }
1750 break;
1751 }
1752 case Instruction::SExt: {
1753 // Compute the bits in the result that are not present in the input.
1754 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1755
1756 Known = Known.trunc(SrcBitWidth);
1757 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1758 // If the sign bit of the input is known set or clear, then we know the
1759 // top bits of the result.
1760 Known = Known.sext(BitWidth);
1761 break;
1762 }
1763 case Instruction::Shl: {
1766 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1767 bool ShAmtNonZero) {
1768 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1769 };
1770 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1771 KF);
1772 // X << X is even: X is either zero or shifts by at least one bit. Both
1773 // uses must observe the same value, so X must not be undef.
1774 if (I->getOperand(0) == I->getOperand(1) &&
1775 isGuaranteedNotToBeUndef(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
1776 Depth + 1))
1777 Known.Zero.setBit(0);
1778
1779 // Trailing zeros of a right-shifted constant never decrease.
1780 const APInt *C;
1781 if (match(I->getOperand(0), m_APInt(C)))
1782 Known.Zero.setLowBits(C->countr_zero());
1783
1784 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1785 // lands at bit Y, when BitWidth is a power of 2.
1786 const APInt *YC;
1787 Value *X = I->getOperand(0);
1788 if (isPowerOf2_32(BitWidth) &&
1789 match(I->getOperand(1),
1791 m_SpecificInt(BitWidth - 1)))) &&
1792 YC->ult(BitWidth - 1)) {
1793 unsigned Y = YC->getZExtValue();
1794 Known.One.setBit(Y);
1795 Known.Zero.setBitsFrom(Y + 1);
1796 }
1797 break;
1798 }
1799 case Instruction::LShr: {
1800 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1801 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1802 bool ShAmtNonZero) {
1803 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1804 };
1805 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1806 KF);
1807 // Leading zeros of a left-shifted constant never decrease.
1808 const APInt *C;
1809 if (match(I->getOperand(0), m_APInt(C)))
1810 Known.Zero.setHighBits(C->countl_zero());
1811 break;
1812 }
1813 case Instruction::AShr: {
1814 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1815 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1816 bool ShAmtNonZero) {
1817 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1818 };
1819 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1820 KF);
1821 break;
1822 }
1823 case Instruction::Sub: {
1826 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1827 DemandedElts, Known, Known2, Q, Depth);
1828 break;
1829 }
1830 case Instruction::Add: {
1833 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1834 DemandedElts, Known, Known2, Q, Depth);
1835 break;
1836 }
1837 case Instruction::SRem:
1838 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1839 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1840 Known = KnownBits::srem(Known, Known2);
1841 break;
1842
1843 case Instruction::URem:
1844 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1845 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1846 Known = KnownBits::urem(Known, Known2);
1847 break;
1848 case Instruction::Alloca:
1849 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1850 break;
1851 case Instruction::GetElementPtr: {
1852 // Analyze all of the subscripts of this getelementptr instruction
1853 // to determine if we can prove known low zero bits.
1854 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1855 // Accumulate the constant indices in a separate variable
1856 // to minimize the number of calls to computeForAddSub.
1857 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1858 APInt AccConstIndices(IndexWidth, 0);
1859
1860 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1861 if (IndexWidth == BitWidth) {
1862 // Note that inbounds does *not* guarantee nsw for the addition, as only
1863 // the offset is signed, while the base address is unsigned.
1864 Known = KnownBits::add(Known, IndexBits);
1865 } else {
1866 // If the index width is smaller than the pointer width, only add the
1867 // value to the low bits.
1868 assert(IndexWidth < BitWidth &&
1869 "Index width can't be larger than pointer width");
1870 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1871 }
1872 };
1873
1875 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1876 // TrailZ can only become smaller, short-circuit if we hit zero.
1877 if (Known.isUnknown())
1878 break;
1879
1880 Value *Index = I->getOperand(i);
1881
1882 // Handle case when index is zero.
1883 Constant *CIndex = dyn_cast<Constant>(Index);
1884 if (CIndex && CIndex->isNullValue())
1885 continue;
1886
1887 if (StructType *STy = GTI.getStructTypeOrNull()) {
1888 // Handle struct member offset arithmetic.
1889
1890 assert(CIndex &&
1891 "Access to structure field must be known at compile time");
1892
1893 if (CIndex->getType()->isVectorTy())
1894 Index = CIndex->getSplatValue();
1895
1896 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1897 const StructLayout *SL = Q.DL.getStructLayout(STy);
1898 uint64_t Offset = SL->getElementOffset(Idx);
1899 AccConstIndices += Offset;
1900 continue;
1901 }
1902
1903 // Handle array index arithmetic.
1904 Type *IndexedTy = GTI.getIndexedType();
1905 if (!IndexedTy->isSized()) {
1906 Known.resetAll();
1907 break;
1908 }
1909
1910 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1911 uint64_t StrideInBytes = Stride.getKnownMinValue();
1912 if (!Stride.isScalable()) {
1913 // Fast path for constant offset.
1914 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1915 AccConstIndices +=
1916 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1917 continue;
1918 }
1919 }
1920
1921 KnownBits IndexBits =
1922 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1923 KnownBits ScalingFactor(IndexWidth);
1924 // Multiply by current sizeof type.
1925 // &A[i] == A + i * sizeof(*A[i]).
1926 if (Stride.isScalable()) {
1927 // For scalable types the only thing we know about sizeof is
1928 // that this is a multiple of the minimum size.
1929 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1930 } else {
1931 ScalingFactor =
1932 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1933 }
1934 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1935 }
1936 if (!Known.isUnknown() && !AccConstIndices.isZero())
1937 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1938 break;
1939 }
1940 case Instruction::PHI: {
1941 const PHINode *P = cast<PHINode>(I);
1942 BinaryOperator *BO = nullptr;
1943 Value *Start = nullptr, *Step = nullptr;
1944 KnownBits &KnownStart = Known2;
1945 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1946 // Handle the case of a simple two-predecessor recurrence PHI.
1947 // There's a lot more that could theoretically be done here, but
1948 // this is sufficient to catch some interesting cases.
1949 unsigned Opcode = BO->getOpcode();
1950
1951 switch (Opcode) {
1952 // If this is a shift recurrence, we know the bits being shifted in. We
1953 // can combine that with information about the start value of the
1954 // recurrence to conclude facts about the result. If this is a udiv
1955 // recurrence, we know that the result can never exceed either the
1956 // numerator or the start value, whichever is greater.
1957 case Instruction::LShr:
1958 case Instruction::AShr:
1959 case Instruction::Shl:
1960 case Instruction::UDiv:
1961 if (BO->getOperand(0) != I)
1962 break;
1963 [[fallthrough]];
1964
1965 // For a urem recurrence, the result can never exceed the start value. The
1966 // phi could either be the numerator or the denominator.
1967 case Instruction::URem: {
1968 // We have matched a recurrence of the form:
1969 // %iv = [R, %entry], [%iv.next, %backedge]
1970 // %iv.next = shift_op %iv, L
1971
1972 // Recurse with the phi context to avoid concern about whether facts
1973 // inferred hold at original context instruction. TODO: It may be
1974 // correct to use the original context. IF warranted, explore and
1975 // add sufficient tests to cover.
1977 RecQ.CtxI = P;
1978 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1979 switch (Opcode) {
1980 case Instruction::Shl:
1981 // A shl recurrence will only increase the tailing zeros
1982 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1983 break;
1984 case Instruction::LShr:
1985 case Instruction::UDiv:
1986 case Instruction::URem:
1987 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1988 // the start value.
1989 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1990 break;
1991 case Instruction::AShr:
1992 // An ashr recurrence will extend the initial sign bit
1993 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1994 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1995 break;
1996 }
1997 break;
1998 }
1999
2000 case Instruction::And: {
2001 // Bits that are zero in the start value stay zero, and bits that are
2002 // one in both the start value and the step stay one.
2003 KnownBits KnownStep(BitWidth);
2004 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
2005 KnownStart, KnownStep, Q, Depth);
2006 Known.Zero |= KnownStart.Zero;
2007 Known.One |= KnownStart.One & KnownStep.One;
2008 break;
2009 }
2010
2011 case Instruction::Or: {
2012 // Bits that are zero in both the start value and the step stay zero,
2013 // and bits that are one in the start value stay one.
2014 KnownBits KnownStep(BitWidth);
2015 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
2016 KnownStart, KnownStep, Q, Depth);
2017 Known.Zero |= KnownStart.Zero & KnownStep.Zero;
2018 Known.One |= KnownStart.One;
2019 break;
2020 }
2021
2022 // Check for operations that have the property that if
2023 // both their operands have low zero bits, the result
2024 // will have low zero bits.
2025 case Instruction::Add:
2026 case Instruction::Sub:
2027 case Instruction::Mul: {
2028 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
2029 // zero bits.
2030 KnownBits KnownStep(BitWidth);
2031 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
2032 KnownStart, KnownStep, Q, Depth);
2033
2034 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
2035 KnownStep.countMinTrailingZeros()));
2036
2037 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
2038 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
2039 break;
2040
2041 switch (Opcode) {
2042 // If initial value of recurrence is nonnegative, and we are adding
2043 // a nonnegative number with nsw, the result can only be nonnegative
2044 // or poison value regardless of the number of times we execute the
2045 // add in phi recurrence. If initial value is negative and we are
2046 // adding a negative number with nsw, the result can only be
2047 // negative or poison value. Similar arguments apply to sub and mul.
2048 //
2049 // (add non-negative, non-negative) --> non-negative
2050 // (add negative, negative) --> negative
2051 case Instruction::Add: {
2052 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2053 Known.makeNonNegative();
2054 else if (KnownStart.isNegative() && KnownStep.isNegative())
2055 Known.makeNegative();
2056 break;
2057 }
2058
2059 // (sub nsw non-negative, negative) --> non-negative
2060 // (sub nsw negative, non-negative) --> negative
2061 case Instruction::Sub: {
2062 if (BO->getOperand(0) != I)
2063 break;
2064 if (KnownStart.isNonNegative() && KnownStep.isNegative())
2065 Known.makeNonNegative();
2066 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
2067 Known.makeNegative();
2068 break;
2069 }
2070
2071 // (mul nsw non-negative, non-negative) --> non-negative
2072 case Instruction::Mul:
2073 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2074 Known.makeNonNegative();
2075 break;
2076
2077 default:
2078 break;
2079 }
2080 break;
2081 }
2082
2083 default:
2084 break;
2085 }
2086 } else {
2087 IntrinsicInst *II = nullptr;
2088 GEPOperator *GEP = nullptr;
2089 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
2090 // %iv = [<Start>, %entry], [%iv.next, %backedge]
2091 //
2092 // %iv.next = <II>(%iv, <Step>)
2093 // or
2094 // %iv.next = <II>(<Step>, %iv)
2095 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
2096 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
2097 KnownBits KnownStep(BitWidth);
2099 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
2100
2101 if (IntrinsicID == Intrinsic::umin) {
2102 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2103 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
2104 KnownStep.countMinLeadingOnes()));
2105 } else {
2106 // umax
2107 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
2108 KnownStep.countMinLeadingZeros()));
2109 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2110 }
2111 }
2112 } else if (Known.isUnknown() && I->getType()->isPointerTy() &&
2114 GEP->getPointerOperand() == P) {
2115 // Handle a pointer induction variable, whose step is a getelementptr:
2116 // %p = phi ptr [ %start, %preheader ], [ %next, %latch ]
2117 // %next = getelementptr <ty>, ptr %p, <indices>
2118 // Every value %p takes is %start plus a whole number of steps, and
2119 // tz(a + b) >= min(tz(a), tz(b)), so the trailing zeros of %p - and
2120 // hence its alignment - are at least the smaller of those of %start and
2121 // of the step.
2122
2123 // Evaluate the start value on its own incoming edge.
2124 unsigned StartIdx = P->getIncomingValue(0) == Start ? 0 : 1;
2126 RecQ.CtxI = P->getIncomingBlock(StartIdx)->getTerminator();
2127 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
2128 Known.Zero.setLowBits(
2129 std::min(KnownStart.countMinTrailingZeros(),
2130 Log2(GEP->getMaxPreservedAlignment(Q.DL))));
2131 }
2132 }
2133
2134 // Unreachable blocks may have zero-operand PHI nodes.
2135 if (P->getNumIncomingValues() == 0)
2136 break;
2137
2138 // Otherwise take the unions of the known bit sets of the operands,
2139 // taking conservative care to avoid excessive recursion.
2140 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2141 // Skip if every incoming value references to ourself.
2142 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2143 break;
2144
2145 Known.setAllConflict();
2146 for (const Use &U : P->operands()) {
2147 Value *IncValue;
2148 const PHINode *CtxPhi;
2149 Instruction *CtxI;
2150 breakSelfRecursivePHI(&U, P, IncValue, CtxI, &CtxPhi);
2151 // Skip direct self references.
2152 if (IncValue == P)
2153 continue;
2154
2155 // Change the context instruction to the "edge" that flows into the
2156 // phi. This is important because that is where the value is actually
2157 // "evaluated" even though it is used later somewhere else. (see also
2158 // D69571).
2160
2161 Known2 = KnownBits(BitWidth);
2162
2163 // Recurse, but cap the recursion to one level, because we don't
2164 // want to waste time spinning around in loops.
2165 // TODO: See if we can base recursion limiter on number of incoming phi
2166 // edges so we don't overly clamp analysis.
2167 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2169
2170 // See if we can further use a conditional branch into the phi
2171 // to help us determine the range of the value.
2172 if (!Known2.isConstant() && IncValue->getType()->isIntegerTy()) {
2174 Value *RHSValue = nullptr;
2175 BasicBlock *TrueSucc, *FalseSucc;
2176 if (match(
2177 RecQ.CtxI,
2178 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_Value(RHSValue)),
2179 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2180 // Check for cases of duplicate successors.
2181 if ((TrueSucc == CtxPhi->getParent()) !=
2182 (FalseSucc == CtxPhi->getParent())) {
2183 // If we're using the false successor, invert the predicate.
2184 if (FalseSucc == CtxPhi->getParent())
2186 // ICMP_NE does not usefully bound the range.
2187 if (Pred != CmpInst::ICMP_NE) {
2188 KnownBits RHSKnown =
2189 computeKnownBits(RHSValue, DemandedElts, RecQ,
2191 if (!RHSKnown.isUnknown()) {
2193 RHSKnown, ICmpInst::isSigned(Pred));
2194 auto CR =
2196 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2197 // We can have conflicts here if we are analyzing deadcode
2198 // (its impossible for us reach this BB based the icmp).
2199 if (KnownUnion.hasConflict()) {
2200 // No reason to continue analyzing in a known dead region,
2201 // so just resetAll and break. This will cause us to also
2202 // exit the outer loop.
2203 Known.resetAll();
2204 break;
2205 }
2206 Known2 = KnownUnion;
2207 }
2208 }
2209 }
2210 }
2211 }
2212
2213 Known = Known.intersectWith(Known2);
2214 // If all bits have been ruled out, there's no need to check
2215 // more operands.
2216 if (Known.isUnknown())
2217 break;
2218 }
2219 }
2220 break;
2221 }
2222 case Instruction::Call:
2223 case Instruction::Invoke: {
2224 // If range metadata is attached to this call, set known bits from that,
2225 // and then intersect with known bits based on other properties of the
2226 // function.
2227 if (MDNode *MD =
2228 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2230
2231 const auto *CB = cast<CallBase>(I);
2232
2233 if (std::optional<ConstantRange> Range = CB->getRange())
2234 Known = Known.unionWith(Range->toKnownBits());
2235
2236 if (const Value *RV = CB->getReturnedArgOperand()) {
2237 if (RV->getType() == I->getType()) {
2238 computeKnownBits(RV, Known2, Q, Depth + 1);
2239 Known = Known.unionWith(Known2);
2240 // If the function doesn't return properly for all input values
2241 // (e.g. unreachable exits) then there might be conflicts between the
2242 // argument value and the range metadata. Simply discard the known bits
2243 // in case of conflicts.
2244 if (Known.hasConflict())
2245 Known.resetAll();
2246 }
2247 }
2248 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2249 switch (II->getIntrinsicID()) {
2250 default:
2251 break;
2252 case Intrinsic::abs: {
2253 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2254 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2255 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2256 break;
2257 }
2258 case Intrinsic::bitreverse:
2259 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2260 Known = Known.unionWith(Known2.reverseBits());
2261 break;
2262 case Intrinsic::bswap:
2263 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2264 Known = Known.unionWith(Known2.byteSwap());
2265 break;
2266 case Intrinsic::ctlz: {
2267 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2268 bool ZeroIsPoison = match(II->getArgOperand(1), m_One());
2269 Known = Known.unionWith(Known2.ctlz(ZeroIsPoison));
2270 break;
2271 }
2272 case Intrinsic::cttz: {
2273 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2274 // If we have a known 1, its position is our upper bound.
2275 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2276 // If this call is poison for 0 input, the result will be less than 2^n.
2277 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2278 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2279 unsigned LowBits = llvm::bit_width(PossibleTZ);
2280 Known.Zero.setBitsFrom(LowBits);
2281 break;
2282 }
2283 case Intrinsic::ctpop: {
2284 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2285 // We can bound the space the count needs. Also, bits known to be zero
2286 // can't contribute to the population.
2287 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2288 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2289 Known.Zero.setBitsFrom(LowBits);
2290 // TODO: we could bound KnownOne using the lower bound on the number
2291 // of bits which might be set provided by popcnt KnownOne2.
2292 break;
2293 }
2294 case Intrinsic::fshr:
2295 case Intrinsic::fshl: {
2296 const APInt *SA;
2297 if (!match(I->getOperand(2), m_APInt(SA)))
2298 break;
2299
2300 KnownBits Known3(BitWidth);
2301 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2302 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2303 Known = II->getIntrinsicID() == Intrinsic::fshl
2304 ? KnownBits::fshl(Known2, Known3, *SA)
2305 : KnownBits::fshr(Known2, Known3, *SA);
2306 break;
2307 }
2308 case Intrinsic::clmul:
2309 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2310 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2311 Known = KnownBits::clmul(Known, Known2);
2312 break;
2313 case Intrinsic::pext:
2314 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2315 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2316 Known = KnownBits::pext(Known, Known2);
2317 break;
2318 case Intrinsic::pdep:
2319 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2320 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2321 Known = KnownBits::pdep(Known, Known2);
2322 break;
2323 case Intrinsic::smulh:
2324 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2325 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2326 Known = KnownBits::mulhs(Known, Known2);
2327 break;
2328 case Intrinsic::umulh:
2329 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2330 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2331 Known = KnownBits::mulhu(Known, Known2);
2332 break;
2333 case Intrinsic::uadd_sat:
2334 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2335 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2336 Known = KnownBits::uadd_sat(Known, Known2);
2337 break;
2338 case Intrinsic::usub_sat:
2339 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2340 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2341 Known = KnownBits::usub_sat(Known, Known2);
2342 break;
2343 case Intrinsic::sadd_sat:
2344 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2345 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2346 Known = KnownBits::sadd_sat(Known, Known2);
2347 break;
2348 case Intrinsic::ssub_sat:
2349 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2350 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2351 Known = KnownBits::ssub_sat(Known, Known2);
2352 break;
2353 // Vec reverse preserves bits from input vec.
2354 case Intrinsic::vector_reverse:
2355 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2356 Depth + 1);
2357 break;
2358 // for min/max/and/or reduce, any bit common to each element in the
2359 // input vec is set in the output.
2360 case Intrinsic::vector_reduce_and:
2361 case Intrinsic::vector_reduce_or:
2362 case Intrinsic::vector_reduce_umax:
2363 case Intrinsic::vector_reduce_umin:
2364 case Intrinsic::vector_reduce_smax:
2365 case Intrinsic::vector_reduce_smin:
2366 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2367 break;
2368 case Intrinsic::vector_reduce_xor: {
2369 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2370 // The zeros common to all vecs are zero in the output.
2371 // If the number of elements is odd, then the common ones remain. If the
2372 // number of elements is even, then the common ones becomes zeros.
2373 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2374 // Even, so the ones become zeros.
2375 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2376 if (EvenCnt)
2377 Known.Zero |= Known.One;
2378 // Maybe even element count so need to clear ones.
2379 if (VecTy->isScalableTy() || EvenCnt)
2380 Known.One.clearAllBits();
2381 break;
2382 }
2383 case Intrinsic::vector_reduce_add: {
2384 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2385 if (!VecTy)
2386 break;
2387 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2388 Known = Known.reduceAdd(VecTy->getNumElements());
2389 break;
2390 }
2391 case Intrinsic::umin:
2392 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2393 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2394 Known = KnownBits::umin(Known, Known2);
2395 break;
2396 case Intrinsic::umax:
2397 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2398 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2399 Known = KnownBits::umax(Known, Known2);
2400 break;
2401 case Intrinsic::smin:
2402 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2403 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2404 Known = KnownBits::smin(Known, Known2);
2406 break;
2407 case Intrinsic::smax:
2408 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2409 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2410 Known = KnownBits::smax(Known, Known2);
2412 break;
2413 case Intrinsic::ptrmask: {
2414 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2415
2416 const Value *Mask = I->getOperand(1);
2417 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2418 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2419 // TODO: 1-extend would be more precise.
2420 Known &= Known2.anyextOrTrunc(BitWidth);
2421 break;
2422 }
2423 case Intrinsic::x86_sse42_crc32_64_64:
2424 Known.Zero.setBitsFrom(32);
2425 break;
2426 case Intrinsic::x86_ssse3_phadd_d_128:
2427 case Intrinsic::x86_ssse3_phadd_w_128:
2428 case Intrinsic::x86_avx2_phadd_d:
2429 case Intrinsic::x86_avx2_phadd_w: {
2431 I, DemandedElts, Q, Depth,
2432 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2433 return KnownBits::add(KnownLHS, KnownRHS);
2434 });
2435 break;
2436 }
2437 case Intrinsic::x86_ssse3_phadd_sw_128:
2438 case Intrinsic::x86_avx2_phadd_sw: {
2440 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2441 break;
2442 }
2443 case Intrinsic::x86_ssse3_phsub_d_128:
2444 case Intrinsic::x86_ssse3_phsub_w_128:
2445 case Intrinsic::x86_avx2_phsub_d:
2446 case Intrinsic::x86_avx2_phsub_w: {
2448 I, DemandedElts, Q, Depth,
2449 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2450 return KnownBits::sub(KnownLHS, KnownRHS);
2451 });
2452 break;
2453 }
2454 case Intrinsic::x86_ssse3_phsub_sw_128:
2455 case Intrinsic::x86_avx2_phsub_sw: {
2457 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2458 break;
2459 }
2460 case Intrinsic::riscv_vsetvli:
2461 case Intrinsic::riscv_vsetvlimax: {
2462 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2463 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2465 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2466 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2467 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2468 uint64_t MaxVLEN =
2469 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2470 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2471
2472 // Result of vsetvli must be not larger than AVL.
2473 if (HasAVL)
2474 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2475 MaxVL = std::min(MaxVL, CI->getZExtValue());
2476
2477 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2478 if (BitWidth > KnownZeroFirstBit)
2479 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2480 break;
2481 }
2482 case Intrinsic::amdgcn_mbcnt_hi:
2483 case Intrinsic::amdgcn_mbcnt_lo: {
2484 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2485 // most 31 + src1.
2486 KnownBits MbcntKnown(BitWidth);
2487 MbcntKnown.Zero.setBitsFrom(
2488 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2489 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2490 Known = Known.unionWith(KnownBits::add(MbcntKnown, Known2));
2491 break;
2492 }
2493 case Intrinsic::vscale: {
2494 if (!II->getParent() || !II->getFunction())
2495 break;
2496
2497 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2498 break;
2499 }
2500 case Intrinsic::stepvector: {
2501 auto *VecTy = cast<VectorType>(II->getType());
2502 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2503 if (!isUIntN(BitWidth, MinNumElts))
2504 break;
2505
2506 bool Overflow = false;
2507 APInt MaxNumElts(BitWidth, MinNumElts);
2508 if (VecTy->isScalableTy()) {
2509 if (!II->getParent() || !II->getFunction())
2510 break;
2511 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2513 .umul_ov(MaxNumElts, Overflow);
2514 }
2515
2516 // Give up if the lane count could wrap. Stepvector truncates lane
2517 // indices that do not fit in the element type.
2518 if (Overflow)
2519 break;
2520
2521 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2522 break;
2523 }
2524 }
2525 }
2526 break;
2527 }
2528 case Instruction::ShuffleVector: {
2529 if (auto *Splat = getSplatValue(I)) {
2531 break;
2532 }
2533
2534 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2535 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2536 if (!Shuf) {
2537 Known.resetAll();
2538 return;
2539 }
2540 // For undef elements, we don't know anything about the common state of
2541 // the shuffle result.
2542 APInt DemandedLHS, DemandedRHS;
2543 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2544 Known.resetAll();
2545 return;
2546 }
2547 Known.setAllConflict();
2548 if (!!DemandedLHS) {
2549 const Value *LHS = Shuf->getOperand(0);
2550 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2551 // If we don't know any bits, early out.
2552 if (Known.isUnknown())
2553 break;
2554 }
2555 if (!!DemandedRHS) {
2556 const Value *RHS = Shuf->getOperand(1);
2557 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2558 Known = Known.intersectWith(Known2);
2559 }
2560 break;
2561 }
2562 case Instruction::InsertElement: {
2563 if (isa<ScalableVectorType>(I->getType())) {
2564 Known.resetAll();
2565 return;
2566 }
2567 const Value *Vec = I->getOperand(0);
2568 const Value *Elt = I->getOperand(1);
2569 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2570 unsigned NumElts = DemandedElts.getBitWidth();
2571 APInt DemandedVecElts = DemandedElts;
2572 bool NeedsElt = true;
2573 // If we know the index we are inserting too, clear it from Vec check.
2574 if (CIdx && CIdx->getValue().ult(NumElts)) {
2575 DemandedVecElts.clearBit(CIdx->getZExtValue());
2576 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2577 }
2578
2579 Known.setAllConflict();
2580 if (NeedsElt) {
2581 computeKnownBits(Elt, Known, Q, Depth + 1);
2582 // If we don't know any bits, early out.
2583 if (Known.isUnknown())
2584 break;
2585 }
2586
2587 if (!DemandedVecElts.isZero()) {
2588 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2589 Known = Known.intersectWith(Known2);
2590 }
2591 break;
2592 }
2593 case Instruction::ExtractElement: {
2594 // Look through extract element. If the index is non-constant or
2595 // out-of-range demand all elements, otherwise just the extracted element.
2596 const Value *Vec = I->getOperand(0);
2597 const Value *Idx = I->getOperand(1);
2598 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2599 if (isa<ScalableVectorType>(Vec->getType())) {
2600 // FIXME: there's probably *something* we can do with scalable vectors
2601 Known.resetAll();
2602 break;
2603 }
2604 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2605 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2606 if (CIdx && CIdx->getValue().ult(NumElts))
2607 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2608 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2609 break;
2610 }
2611 case Instruction::ExtractValue:
2612 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2614 if (EVI->getNumIndices() != 1) break;
2615 if (EVI->getIndices()[0] == 0) {
2616 switch (II->getIntrinsicID()) {
2617 default: break;
2618 case Intrinsic::uadd_with_overflow:
2619 case Intrinsic::sadd_with_overflow:
2621 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2622 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2623 break;
2624 case Intrinsic::usub_with_overflow:
2625 case Intrinsic::ssub_with_overflow:
2627 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2628 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2629 break;
2630 case Intrinsic::umul_with_overflow:
2631 case Intrinsic::smul_with_overflow:
2632 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2633 false, DemandedElts, Known, Known2, Q, Depth);
2634 break;
2635 }
2636 }
2637 }
2638 break;
2639 case Instruction::Freeze:
2640 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
2641 Depth + 1))
2642 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2643 break;
2644 }
2645}
2646
2647/// Determine which bits of V are known to be either zero or one and return
2648/// them.
2649KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2650 const SimplifyQuery &Q, unsigned Depth) {
2651 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2652 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2653 return Known;
2654}
2655
2656/// Determine which bits of V are known to be either zero or one and return
2657/// them.
2659 unsigned Depth) {
2660 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2662 return Known;
2663}
2664
2665/// Determine which bits of V are known to be either zero or one and return
2666/// them in the Known bit set.
2667///
2668/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2669/// we cannot optimize based on the assumption that it is zero without changing
2670/// it to be an explicit zero. If we don't change it to zero, other code could
2671/// optimized based on the contradictory assumption that it is non-zero.
2672/// Because instcombine aggressively folds operations with undef args anyway,
2673/// this won't lose us code quality.
2674///
2675/// This function is defined on values with integer type, values with pointer
2676/// type, and vectors of integers. In the case
2677/// where V is a vector, known zero, and known one values are the
2678/// same width as the vector element, and the bit is set only if it is true
2679/// for all of the demanded elements in the vector specified by DemandedElts.
2680void computeKnownBits(const Value *V, const APInt &DemandedElts,
2681 KnownBits &Known, const SimplifyQuery &Q,
2682 unsigned Depth) {
2683 if (!DemandedElts) {
2684 // No demanded elts, better to assume we don't know anything.
2685 Known.resetAll();
2686 return;
2687 }
2688
2689 assert(V && "No Value?");
2690 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2691
2692#ifndef NDEBUG
2693 Type *Ty = V->getType();
2694 unsigned BitWidth = Known.getBitWidth();
2695
2696 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2697 "Not integer or pointer type!");
2698
2699 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2700 assert(
2701 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2702 "DemandedElt width should equal the fixed vector number of elements");
2703 } else {
2704 assert(DemandedElts == APInt(1, 1) &&
2705 "DemandedElt width should be 1 for scalars or scalable vectors");
2706 }
2707
2708 Type *ScalarTy = Ty->getScalarType();
2709 if (ScalarTy->isPointerTy()) {
2710 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2711 "V and Known should have same BitWidth");
2712 } else {
2713 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2714 "V and Known should have same BitWidth");
2715 }
2716#endif
2717
2718 const APInt *C;
2719 if (match(V, m_APInt(C))) {
2720 // We know all of the bits for a scalar constant or a splat vector constant!
2722 return;
2723 }
2724 // Null and aggregate-zero are all-zeros.
2726 Known.setAllZero();
2727 return;
2728 }
2729 // Handle a constant vector by taking the intersection of the known bits of
2730 // each element.
2732 assert(!isa<ScalableVectorType>(V->getType()));
2733 // We know that CDV must be a vector of integers. Take the intersection of
2734 // each element.
2735 Known.setAllConflict();
2736 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2737 if (!DemandedElts[i])
2738 continue;
2739 APInt Elt = CDV->getElementAsAPInt(i);
2740 Known.Zero &= ~Elt;
2741 Known.One &= Elt;
2742 }
2743 if (Known.hasConflict())
2744 Known.resetAll();
2745 return;
2746 }
2747
2748 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2749 assert(!isa<ScalableVectorType>(V->getType()));
2750 // We know that CV must be a vector of integers. Take the intersection of
2751 // each element.
2752 Known.setAllConflict();
2753 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2754 if (!DemandedElts[i])
2755 continue;
2756 Constant *Element = CV->getAggregateElement(i);
2757 if (isa<PoisonValue>(Element))
2758 continue;
2759 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2760 if (!ElementCI) {
2761 Known.resetAll();
2762 return;
2763 }
2764 const APInt &Elt = ElementCI->getValue();
2765 Known.Zero &= ~Elt;
2766 Known.One &= Elt;
2767 }
2768 if (Known.hasConflict())
2769 Known.resetAll();
2770 return;
2771 }
2772
2773 // Start out not knowing anything.
2774 Known.resetAll();
2775
2776 // We can't imply anything about undefs.
2777 if (isa<UndefValue>(V))
2778 return;
2779
2780 // There's no point in looking through other users of ConstantData for
2781 // assumptions. Confirm that we've handled them all.
2782 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2783
2784 if (const auto *A = dyn_cast<Argument>(V))
2785 if (std::optional<ConstantRange> Range = A->getRange())
2786 Known = Range->toKnownBits();
2787
2788 // All recursive calls that increase depth must come after this.
2790 return;
2791
2792 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2793 // the bits of its aliasee.
2794 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2795 if (!GA->isInterposable())
2796 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2797 return;
2798 }
2799
2800 if (const Operator *I = dyn_cast<Operator>(V))
2801 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2802 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2803 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2804 Known = CR->toKnownBits();
2805 }
2806
2807 // Aligned pointers have trailing zeros - refine Known.Zero set
2808 if (isa<PointerType>(V->getType())) {
2809 Align Alignment = V->getPointerAlignment(Q.DL);
2810 Known.Zero.setLowBits(Log2(Alignment));
2811 }
2812
2813 // computeKnownBitsFromContext strictly refines Known.
2814 // Therefore, we run them after computeKnownBitsFromOperator.
2815
2816 // Check whether we can determine known bits from context such as assumes.
2818}
2819
2820/// Try to detect a recurrence that the value of the induction variable is
2821/// always a power of two (or zero).
2822static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2823 SimplifyQuery &Q, unsigned Depth) {
2824 BinaryOperator *BO = nullptr;
2825 Value *Start = nullptr, *Step = nullptr;
2826 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2827 return false;
2828
2829 // Initial value must be a power of two.
2830 for (const Use &U : PN->operands()) {
2831 if (U.get() == Start) {
2832 // Initial value comes from a different BB, need to adjust context
2833 // instruction for analysis.
2834 Q.CtxI = PN->getIncomingBlock(U)->getTerminator();
2835 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2836 return false;
2837 }
2838 }
2839
2840 // Except for Mul, the induction variable must be on the left side of the
2841 // increment expression, otherwise its value can be arbitrary.
2842 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2843 return false;
2844
2845 Q.CtxI = BO->getParent()->getTerminator();
2846 switch (BO->getOpcode()) {
2847 case Instruction::Mul:
2848 // Power of two is closed under multiplication.
2849 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2850 Q.IIQ.hasNoSignedWrap(BO)) &&
2851 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2852 case Instruction::SDiv:
2853 // Start value must not be signmask for signed division, so simply being a
2854 // power of two is not sufficient, and it has to be a constant.
2855 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2856 return false;
2857 [[fallthrough]];
2858 case Instruction::UDiv:
2859 // Divisor must be a power of two.
2860 // If OrZero is false, cannot guarantee induction variable is non-zero after
2861 // division, same for Shr, unless it is exact division.
2862 return (OrZero || Q.IIQ.isExact(BO)) &&
2863 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2864 case Instruction::Shl:
2865 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2866 case Instruction::AShr:
2867 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2868 return false;
2869 [[fallthrough]];
2870 case Instruction::LShr:
2871 return OrZero || Q.IIQ.isExact(BO);
2872 default:
2873 return false;
2874 }
2875}
2876
2877/// Return true if we can infer that \p V is known to be a power of 2 from
2878/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2879static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2880 const Value *Cond,
2881 bool CondIsTrue) {
2883 const APInt *RHSC;
2884 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2885 return false;
2886 if (!CondIsTrue)
2888 // ctpop(V) u< 2
2889 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2890 return true;
2891 // ctpop(V) == 1
2892 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2893}
2894
2895/// Return true if the given value is known to have exactly one
2896/// bit set when defined. For vectors return true if every element is known to
2897/// be a power of two when defined. Supports values with integer or pointer
2898/// types and vectors of integers.
2899bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2900 const SimplifyQuery &Q, unsigned Depth) {
2901 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2902
2903 if (isa<Constant>(V))
2904 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2905
2906 // i1 is by definition a power of 2 or zero.
2907 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2908 return true;
2909
2910 // Try to infer from assumptions.
2911 if (Q.AC && Q.CtxI) {
2912 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2913 if (!AssumeVH)
2914 continue;
2915 CallInst *I = cast<CallInst>(AssumeVH);
2916 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2917 /*CondIsTrue=*/true) &&
2919 return true;
2920 }
2921 }
2922
2923 // Handle dominating conditions.
2924 if (Q.DC && Q.CtxI && Q.DT) {
2925 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2926 Value *Cond = BI->getCondition();
2927
2928 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2930 /*CondIsTrue=*/true) &&
2931 Q.DT->dominates(Edge0, Q.CtxI->getParent()))
2932 return true;
2933
2934 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2936 /*CondIsTrue=*/false) &&
2937 Q.DT->dominates(Edge1, Q.CtxI->getParent()))
2938 return true;
2939 }
2940 }
2941
2942 auto *I = dyn_cast<Instruction>(V);
2943 if (!I)
2944 return false;
2945
2946 if (Q.CtxI && match(V, m_VScale())) {
2947 const Function *F = Q.CtxI->getFunction();
2948 // The vscale_range indicates vscale is a power-of-two.
2949 return F->hasFnAttribute(Attribute::VScaleRange);
2950 }
2951
2952 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2953 // it is shifted off the end then the result is undefined.
2954 if (match(I, m_Shl(m_One(), m_Value())))
2955 return true;
2956
2957 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2958 // the bottom. If it is shifted off the bottom then the result is undefined.
2959 if (match(I, m_LShr(m_SignMask(), m_Value())))
2960 return true;
2961
2962 // The remaining tests are all recursive, so bail out if we hit the limit.
2964 return false;
2965
2966 switch (I->getOpcode()) {
2967 case Instruction::ZExt:
2968 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2969 case Instruction::Trunc:
2970 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2971 case Instruction::Shl:
2972 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2973 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2974 return false;
2975 case Instruction::LShr:
2976 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2977 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2978 return false;
2979 case Instruction::UDiv:
2981 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2982 return false;
2983 case Instruction::Mul:
2984 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2985 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2986 (OrZero || isKnownNonZero(I, Q, Depth));
2987 case Instruction::And:
2988 // A power of two and'd with anything is a power of two or zero.
2989 if (OrZero &&
2990 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2991 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2992 return true;
2993 // X & (-X) is always a power of two or zero.
2994 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2995 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2996 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2997 return false;
2998 case Instruction::Add: {
2999 // Adding a power-of-two or zero to the same power-of-two or zero yields
3000 // either the original power-of-two, a larger power-of-two or zero.
3002 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
3003 Q.IIQ.hasNoSignedWrap(VOBO)) {
3004 if (match(I->getOperand(0),
3005 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
3006 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
3007 return true;
3008 if (match(I->getOperand(1),
3009 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
3010 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
3011 return true;
3012
3013 unsigned BitWidth = V->getType()->getScalarSizeInBits();
3014 KnownBits LHSBits(BitWidth);
3015 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
3016
3017 KnownBits RHSBits(BitWidth);
3018 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
3019 // If i8 V is a power of two or zero:
3020 // ZeroBits: 1 1 1 0 1 1 1 1
3021 // ~ZeroBits: 0 0 0 1 0 0 0 0
3022 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
3023 // If OrZero isn't set, we cannot give back a zero result.
3024 // Make sure either the LHS or RHS has a bit set.
3025 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
3026 return true;
3027 }
3028
3029 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
3030 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
3031 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
3032 return true;
3033 return false;
3034 }
3035 case Instruction::Select:
3036 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
3037 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
3038 case Instruction::PHI: {
3039 // A PHI node is power of two if all incoming values are power of two, or if
3040 // it is an induction variable where in each step its value is a power of
3041 // two.
3042 auto *PN = cast<PHINode>(I);
3044
3045 // Check if it is an induction variable and always power of two.
3046 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
3047 return true;
3048
3049 // Recursively check all incoming values. Limit recursion to 2 levels, so
3050 // that search complexity is limited to number of operands^2.
3051 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3052 return llvm::all_of(PN->operands(), [&](const Use &U) {
3053 // Value is power of 2 if it is coming from PHI node itself by induction.
3054 if (U.get() == PN)
3055 return true;
3056
3057 // Change the context instruction to the incoming block where it is
3058 // evaluated.
3059 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3060 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
3061 });
3062 }
3063 case Instruction::Invoke:
3064 case Instruction::Call: {
3065 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3066 switch (II->getIntrinsicID()) {
3067 case Intrinsic::umax:
3068 case Intrinsic::smax:
3069 case Intrinsic::umin:
3070 case Intrinsic::smin:
3071 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
3072 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3073 // bswap/bitreverse just move around bits, but don't change any 1s/0s
3074 // thus dont change pow2/non-pow2 status.
3075 case Intrinsic::bitreverse:
3076 case Intrinsic::bswap:
3077 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3078 case Intrinsic::fshr:
3079 case Intrinsic::fshl:
3080 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
3081 if (II->getArgOperand(0) == II->getArgOperand(1))
3082 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3083 break;
3084 case Intrinsic::riscv_vsetvlimax:
3085 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
3086 // for any valid vtype, so it is a power of two regardless of OrZero.
3087 return true;
3088 case Intrinsic::read_register:
3089 case Intrinsic::read_volatile_register: {
3090 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
3091 // of two, so it is a power of two regardless of OrZero.
3092 const Module *M = II->getModule();
3093 if (!M || !M->getTargetTriple().isRISCV())
3094 break;
3095 return isReadVLENB(*II);
3096 }
3097 default:
3098 break;
3099 }
3100 }
3101 return false;
3102 }
3103 default:
3104 return false;
3105 }
3106}
3107
3108/// Test whether a GEP's result is known to be non-null.
3109///
3110/// Uses properties inherent in a GEP to try to determine whether it is known
3111/// to be non-null.
3112///
3113/// Currently this routine does not support vector GEPs.
3114static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
3115 unsigned Depth) {
3116 const Function *F = nullptr;
3117 if (const Instruction *I = dyn_cast<Instruction>(GEP))
3118 F = I->getFunction();
3119
3120 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
3121 // may be null iff the base pointer is null and the offset is zero.
3122 if (!GEP->hasNoUnsignedWrap() &&
3123 !(GEP->isInBounds() &&
3124 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
3125 return false;
3126
3127 // FIXME: Support vector-GEPs.
3128 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
3129
3130 // If the base pointer is non-null, we cannot walk to a null address with an
3131 // inbounds GEP in address space zero.
3132 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3133 return true;
3134
3135 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3136 // If so, then the GEP cannot produce a null pointer, as doing so would
3137 // inherently violate the inbounds contract within address space zero.
3139 GTI != GTE; ++GTI) {
3140 // Struct types are easy -- they must always be indexed by a constant.
3141 if (StructType *STy = GTI.getStructTypeOrNull()) {
3142 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3143 unsigned ElementIdx = OpC->getZExtValue();
3144 const StructLayout *SL = Q.DL.getStructLayout(STy);
3145 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3146 if (ElementOffset > 0)
3147 return true;
3148 continue;
3149 }
3150
3151 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3152 if (GTI.getSequentialElementStride(Q.DL).isZero())
3153 continue;
3154
3155 // Fast path the constant operand case both for efficiency and so we don't
3156 // increment Depth when just zipping down an all-constant GEP.
3157 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3158 if (!OpC->isZero())
3159 return true;
3160 continue;
3161 }
3162
3163 // We post-increment Depth here because while isKnownNonZero increments it
3164 // as well, when we pop back up that increment won't persist. We don't want
3165 // to recurse 10k times just because we have 10k GEP operands. We don't
3166 // bail completely out because we want to handle constant GEPs regardless
3167 // of depth.
3169 continue;
3170
3171 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3172 return true;
3173 }
3174
3175 return false;
3176}
3177
3179 const Instruction *CtxI,
3180 const DominatorTree *DT) {
3181 assert(!isa<Constant>(V) && "Called for constant?");
3182
3183 if (!CtxI || !DT)
3184 return false;
3185
3186 unsigned NumUsesExplored = 0;
3187 for (auto &U : V->uses()) {
3188 // Avoid massive lists
3189 if (NumUsesExplored >= DomConditionsMaxUses)
3190 break;
3191 NumUsesExplored++;
3192
3193 const Instruction *UI = cast<Instruction>(U.getUser());
3194 // If the value is used as an argument to a call or invoke, then argument
3195 // attributes may provide an answer about null-ness.
3196 if (V->getType()->isPointerTy()) {
3197 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3198 if (CB->isArgOperand(&U) &&
3199 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3200 /*AllowUndefOrPoison=*/false) &&
3201 DT->dominates(CB, CtxI))
3202 return true;
3203 }
3204 }
3205
3206 // If the value is used as a load/store, then the pointer must be non null.
3207 if (V == getLoadStorePointerOperand(UI)) {
3209 V->getType()->getPointerAddressSpace()) &&
3210 DT->dominates(UI, CtxI))
3211 return true;
3212 }
3213
3214 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3215 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3216 isValidAssumeForContext(UI, CtxI, DT))
3217 return true;
3218
3219 // Consider only compare instructions uniquely controlling a branch
3220 Value *RHS;
3222 bool NonNullIfTrue;
3223 if (match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS)))) {
3224 if (cmpExcludesZero(Pred, RHS))
3225 NonNullIfTrue = true;
3227 NonNullIfTrue = false;
3228 else
3229 continue;
3230 } else if (UI->getType()->isIntegerTy(1) &&
3231 match(UI, m_Trunc(m_Specific(V)))) {
3232 NonNullIfTrue = true;
3233 } else
3234 continue;
3235
3238 for (const auto *CmpU : UI->users()) {
3239 assert(WorkList.empty() && "Should be!");
3240 if (Visited.insert(CmpU).second)
3241 WorkList.push_back(CmpU);
3242
3243 while (!WorkList.empty()) {
3244 auto *Curr = WorkList.pop_back_val();
3245
3246 // If a user is an AND, add all its users to the work list. We only
3247 // propagate "pred != null" condition through AND because it is only
3248 // correct to assume that all conditions of AND are met in true branch.
3249 // TODO: Support similar logic of OR and EQ predicate?
3250 if (NonNullIfTrue)
3251 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3252 for (const auto *CurrU : Curr->users())
3253 if (Visited.insert(CurrU).second)
3254 WorkList.push_back(CurrU);
3255 continue;
3256 }
3257
3258 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3259 BasicBlock *NonNullSuccessor =
3260 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3261 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3262 if (DT->dominates(Edge, CtxI->getParent()))
3263 return true;
3264 } else if (NonNullIfTrue && isGuard(Curr) &&
3265 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3266 return true;
3267 }
3268 }
3269 }
3270 }
3271
3272 return false;
3273}
3274
3275/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3276/// ensure that the value it's attached to is never Value? 'RangeType' is
3277/// is the type of the value described by the range.
3278static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3279 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3280 assert(NumRanges >= 1);
3281 for (unsigned i = 0; i < NumRanges; ++i) {
3283 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3285 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3286 ConstantRange Range(Lower->getValue(), Upper->getValue());
3287 if (Range.contains(Value))
3288 return false;
3289 }
3290 return true;
3291}
3292
3293/// Try to detect a recurrence that monotonically increases/decreases from a
3294/// non-zero starting value. These are common as induction variables.
3295static bool isNonZeroRecurrence(const PHINode *PN) {
3296 BinaryOperator *BO = nullptr;
3297 Value *Start = nullptr, *Step = nullptr;
3298 const APInt *StartC, *StepC;
3299 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3300 !match(Start, m_APInt(StartC)) || StartC->isZero())
3301 return false;
3302
3303 switch (BO->getOpcode()) {
3304 case Instruction::Add:
3305 // Starting from non-zero and stepping away from zero can never wrap back
3306 // to zero.
3307 return BO->hasNoUnsignedWrap() ||
3308 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3309 StartC->isNegative() == StepC->isNegative());
3310 case Instruction::Mul:
3311 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3312 match(Step, m_APInt(StepC)) && !StepC->isZero();
3313 case Instruction::Shl:
3314 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3315 case Instruction::AShr:
3316 case Instruction::LShr:
3317 return BO->isExact();
3318 case Instruction::Or:
3319 return true;
3320 default:
3321 return false;
3322 }
3323}
3324
3325static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3327 m_Specific(Op1), m_Zero()))) ||
3329 m_Specific(Op0), m_Zero())));
3330}
3331
3332/// Return true if "addr(P) + Off" cannot be zero. The object P points to
3333/// cannot cross the unsigned address space boundary, including the address one
3334/// past its end, so an offset that stays within the object cannot wrap around
3335/// to zero. This holds even if the object starts at the zero address, which is
3336/// all that null_pointer_is_valid permits, so a non-zero offset is enough.
3338 Value *Y) {
3339 const APInt *Off;
3340 if (!match(Y, m_APInt(Off)) || Off->isZero())
3341 return false;
3342
3343 // ptrtoaddr always produces the address. ptrtoint only does so when its
3344 // result is at least as wide as the address: a narrower result is truncated
3345 // and may wrap to zero, while bits above the address can only make the
3346 // result more non-zero.
3347 Value *P;
3348 if (!match(X, m_PtrToAddr(m_Value(P))) &&
3349 !(match(X, m_PtrToInt(m_Value(P))) &&
3350 X->getType()->getScalarSizeInBits() >=
3351 Q.DL.getAddressSizeInBits(P->getType())))
3352 return false;
3353
3354 // A vector of pointers has no single object whose size can be taken, and
3355 // getPointerDereferenceableBytes() requires a plain pointer.
3356 if (!P->getType()->isPointerTy())
3357 return false;
3358
3359 bool CanBeNull;
3360 uint64_t DerefBytes = P->getPointerDereferenceableBytes(
3361 Q.DL, CanBeNull, /*CanBeFreed=*/nullptr);
3362 if (CanBeNull || DerefBytes == 0 || !Off->ule(DerefBytes))
3363 return false;
3364
3365 return true;
3366}
3367
3368static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3369 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3370 bool NUW, unsigned Depth) {
3372 return true;
3373
3374 // (X + (X != 0)) is non zero
3375 if (matchOpWithOpEqZero(X, Y))
3376 return true;
3377
3378 if (NUW)
3379 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3380 isKnownNonZero(X, DemandedElts, Q, Depth);
3381
3382 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3383 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3384
3385 // If X and Y are both non-negative (as signed values) then their sum is not
3386 // zero unless both X and Y are zero.
3387 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3388 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3389 isKnownNonZero(X, DemandedElts, Q, Depth))
3390 return true;
3391
3392 // If X and Y are both negative (as signed values) then their sum is not
3393 // zero unless both X and Y equal INT_MIN.
3394 if (XKnown.isNegative() && YKnown.isNegative()) {
3396 // The sign bit of X is set. If some other bit is set then X is not equal
3397 // to INT_MIN.
3398 if (XKnown.One.intersects(Mask))
3399 return true;
3400 // The sign bit of Y is set. If some other bit is set then Y is not equal
3401 // to INT_MIN.
3402 if (YKnown.One.intersects(Mask))
3403 return true;
3404 }
3405
3406 // The sum of a non-negative number and a power of two is not zero.
3407 if (XKnown.isNonNegative() &&
3408 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3409 return true;
3410 if (YKnown.isNonNegative() &&
3411 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3412 return true;
3413
3414 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3415}
3416
3417static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3418 unsigned BitWidth, Value *X, Value *Y,
3419 unsigned Depth) {
3420 // (X - (X != 0)) is non zero
3421 // ((X != 0) - X) is non zero
3422 if (matchOpWithOpEqZero(X, Y))
3423 return true;
3424
3425 // TODO: Move this case into isKnownNonEqual().
3426 if (auto *C = dyn_cast<Constant>(X))
3427 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3428 return true;
3429
3430 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3431}
3432
3433static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3434 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3435 bool NUW, unsigned Depth) {
3436 // If X and Y are non-zero then so is X * Y as long as the multiplication
3437 // does not overflow.
3438 if (NSW || NUW)
3439 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3440 isKnownNonZero(Y, DemandedElts, Q, Depth);
3441
3442 // If either X or Y is odd, then if the other is non-zero the result can't
3443 // be zero.
3444 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3445 if (XKnown.One[0])
3446 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3447
3448 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3449 if (YKnown.One[0])
3450 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3451
3452 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3453 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3454 // the lowest known One of X and Y. If they are non-zero, the result
3455 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3456 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3457 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3458 BitWidth;
3459}
3460
3461static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3462 const SimplifyQuery &Q, const KnownBits &KnownVal,
3463 unsigned Depth) {
3464 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3465 switch (I->getOpcode()) {
3466 case Instruction::Shl:
3467 return Lhs.shl(Rhs);
3468 case Instruction::LShr:
3469 return Lhs.lshr(Rhs);
3470 case Instruction::AShr:
3471 return Lhs.ashr(Rhs);
3472 default:
3473 llvm_unreachable("Unknown Shift Opcode");
3474 }
3475 };
3476
3477 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3478 switch (I->getOpcode()) {
3479 case Instruction::Shl:
3480 return Lhs.lshr(Rhs);
3481 case Instruction::LShr:
3482 case Instruction::AShr:
3483 return Lhs.shl(Rhs);
3484 default:
3485 llvm_unreachable("Unknown Shift Opcode");
3486 }
3487 };
3488
3489 if (KnownVal.isUnknown())
3490 return false;
3491
3492 KnownBits KnownCnt =
3493 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3494 APInt MaxShift = KnownCnt.getMaxValue();
3495 unsigned NumBits = KnownVal.getBitWidth();
3496 if (MaxShift.uge(NumBits))
3497 return false;
3498
3499 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3500 return true;
3501
3502 // If all of the bits shifted out are known to be zero, and Val is known
3503 // non-zero then at least one non-zero bit must remain.
3504 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3505 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3506 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3507 return true;
3508
3509 return false;
3510}
3511
3513 const APInt &DemandedElts,
3514 const SimplifyQuery &Q, unsigned Depth) {
3515 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3516 switch (I->getOpcode()) {
3517 case Instruction::Alloca:
3518 // Alloca never returns null, malloc might.
3519 return I->getType()->getPointerAddressSpace() == 0;
3520 case Instruction::GetElementPtr:
3521 if (I->getType()->isPointerTy())
3523 break;
3524 case Instruction::BitCast: {
3525 // We need to be a bit careful here. We can only peek through the bitcast
3526 // if the scalar size of elements in the operand are smaller than and a
3527 // multiple of the size they are casting too. Take three cases:
3528 //
3529 // 1) Unsafe:
3530 // bitcast <2 x i16> %NonZero to <4 x i8>
3531 //
3532 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3533 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3534 // guranteed (imagine just sign bit set in the 2 i16 elements).
3535 //
3536 // 2) Unsafe:
3537 // bitcast <4 x i3> %NonZero to <3 x i4>
3538 //
3539 // Even though the scalar size of the src (`i3`) is smaller than the
3540 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3541 // its possible for the `3 x i4` elements to be zero because there are
3542 // some elements in the destination that don't contain any full src
3543 // element.
3544 //
3545 // 3) Safe:
3546 // bitcast <4 x i8> %NonZero to <2 x i16>
3547 //
3548 // This is always safe as non-zero in the 4 i8 elements implies
3549 // non-zero in the combination of any two adjacent ones. Since i8 is a
3550 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3551 // This all implies the 2 i16 elements are non-zero.
3552 Type *FromTy = I->getOperand(0)->getType();
3553 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3554 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3555 return isKnownNonZero(I->getOperand(0), Q, Depth);
3556 } break;
3557 case Instruction::IntToPtr:
3558 // Note that we have to take special care to avoid looking through
3559 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3560 // as casts that can alter the value, e.g., AddrSpaceCasts.
3561 if (!isa<ScalableVectorType>(I->getType()) &&
3562 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3563 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3564 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3565 break;
3566 case Instruction::PtrToAddr:
3567 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3568 // so we can directly forward.
3569 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3570 case Instruction::PtrToInt:
3571 // For inttoptr, make sure the result size is >= the address size. If the
3572 // address is non-zero, any larger value is also non-zero.
3573 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3574 I->getType()->getScalarSizeInBits())
3575 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3576 break;
3577 case Instruction::Trunc:
3578 // nuw/nsw trunc preserves zero/non-zero status of input.
3579 if (auto *TI = dyn_cast<TruncInst>(I))
3580 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3581 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3582 break;
3583
3584 // Iff x - y != 0, then x ^ y != 0
3585 // Therefore we can do the same exact checks
3586 case Instruction::Xor:
3587 case Instruction::Sub:
3588 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3589 I->getOperand(1), Depth);
3590 case Instruction::Or:
3591 // (X | (X != 0)) is non zero
3592 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3593 return true;
3594 // X | Y != 0 if X != Y.
3595 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3596 Depth))
3597 return true;
3598 // X | Y != 0 if X != 0 or Y != 0.
3599 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3600 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3601 case Instruction::SExt:
3602 case Instruction::ZExt:
3603 // ext X != 0 if X != 0.
3604 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3605
3606 case Instruction::Shl: {
3607 // shl nsw/nuw can't remove any non-zero bits.
3609 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3610 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3611
3612 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3613 // if the lowest bit is shifted off the end.
3615 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3616 if (Known.One[0])
3617 return true;
3618
3619 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3620 }
3621 case Instruction::LShr:
3622 case Instruction::AShr: {
3623 // shr exact can only shift out zero bits.
3625 if (BO->isExact())
3626 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3627
3628 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3629 // defined if the sign bit is shifted off the end.
3631 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3632 if (Known.isNegative())
3633 return true;
3634
3635 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3636 // position >= C, because the sum >= max(A, B).
3637 Value *A, *B;
3638 const APInt *C;
3639 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3640 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3641 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3642 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3643 if (!KnownA.One.lshr(*C).isZero())
3644 return true;
3645 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3646 if (!KnownB.One.lshr(*C).isZero())
3647 return true;
3648 }
3649
3650 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3651 }
3652 case Instruction::UDiv:
3653 case Instruction::SDiv: {
3654 // X / Y
3655 // div exact can only produce a zero if the dividend is zero.
3656 if (cast<PossiblyExactOperator>(I)->isExact())
3657 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3658
3659 KnownBits XKnown =
3660 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3661 // If X is fully unknown we won't be able to figure anything out so don't
3662 // both computing knownbits for Y.
3663 if (XKnown.isUnknown())
3664 return false;
3665
3666 KnownBits YKnown =
3667 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3668 if (I->getOpcode() == Instruction::SDiv) {
3669 // For signed division need to compare abs value of the operands.
3670 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3671 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3672 }
3673 // If X u>= Y then div is non zero (0/0 is UB).
3674 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3675 // If X is total unknown or X u< Y we won't be able to prove non-zero
3676 // with compute known bits so just return early.
3677 return XUgeY && *XUgeY;
3678 }
3679 case Instruction::Add: {
3680 // X + Y.
3681
3682 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3683 // non-zero.
3685 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3686 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3687 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3688 }
3689 case Instruction::Mul: {
3691 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3692 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3693 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3694 }
3695 case Instruction::Select: {
3696 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3697
3698 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3699 // then see if the select condition implies the arm is non-zero. For example
3700 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3701 // dominated by `X != 0`.
3702 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3703 Value *Op;
3704 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3705 // Op is trivially non-zero.
3706 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3707 return true;
3708
3709 // The condition of the select dominates the true/false arm. Check if the
3710 // condition implies that a given arm is non-zero.
3711 Value *X;
3713 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3714 return false;
3715
3716 if (!IsTrueArm)
3718
3719 return cmpExcludesZero(Pred, X);
3720 };
3721
3722 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3723 SelectArmIsNonZero(/* IsTrueArm */ false))
3724 return true;
3725 break;
3726 }
3727 case Instruction::PHI: {
3728 auto *PN = cast<PHINode>(I);
3730 return true;
3731
3732 // Check if all incoming values are non-zero using recursion.
3734 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3735 return llvm::all_of(PN->operands(), [&](const Use &U) {
3736 if (U.get() == PN)
3737 return true;
3738 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3739 // Check if the branch on the phi excludes zero.
3740 CmpPredicate Pred;
3741 Value *X;
3742 BasicBlock *TrueSucc, *FalseSucc;
3743 if (match(RecQ.CtxI,
3744 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3745 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3746 // Check for cases of duplicate successors.
3747 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3748 // If we're using the false successor, invert the predicate.
3749 if (FalseSucc == PN->getParent())
3750 Pred = CmpInst::getInversePredicate(Pred);
3751 if (cmpExcludesZero(Pred, X))
3752 return true;
3753 }
3754 }
3755 if (match(RecQ.CtxI,
3756 m_Br(m_Trunc(m_Specific(U.get())), m_BasicBlock(TrueSucc),
3757 m_BasicBlock(FalseSucc))) &&
3758 TrueSucc == PN->getParent() && FalseSucc != TrueSucc)
3759 return true;
3760 // Finally recurse on the edge and check it directly.
3761 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3762 });
3763 }
3764 case Instruction::InsertElement: {
3765 if (isa<ScalableVectorType>(I->getType()))
3766 break;
3767
3768 const Value *Vec = I->getOperand(0);
3769 const Value *Elt = I->getOperand(1);
3770 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3771
3772 unsigned NumElts = DemandedElts.getBitWidth();
3773 APInt DemandedVecElts = DemandedElts;
3774 bool SkipElt = false;
3775 // If we know the index we are inserting too, clear it from Vec check.
3776 if (CIdx && CIdx->getValue().ult(NumElts)) {
3777 DemandedVecElts.clearBit(CIdx->getZExtValue());
3778 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3779 }
3780
3781 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3782 // are non-zero.
3783 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3784 (DemandedVecElts.isZero() ||
3785 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3786 }
3787 case Instruction::ExtractElement:
3788 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3789 const Value *Vec = EEI->getVectorOperand();
3790 const Value *Idx = EEI->getIndexOperand();
3791 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3792 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3793 unsigned NumElts = VecTy->getNumElements();
3794 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3795 if (CIdx && CIdx->getValue().ult(NumElts))
3796 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3797 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3798 }
3799 }
3800 break;
3801 case Instruction::ShuffleVector: {
3802 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3803 if (!Shuf)
3804 break;
3805 APInt DemandedLHS, DemandedRHS;
3806 // For undef elements, we don't know anything about the common state of
3807 // the shuffle result.
3808 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3809 break;
3810 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3811 return (DemandedRHS.isZero() ||
3812 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3813 (DemandedLHS.isZero() ||
3814 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3815 }
3816 case Instruction::Freeze:
3817 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3818 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3819 Depth);
3820 case Instruction::Load: {
3821 auto *LI = cast<LoadInst>(I);
3822 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3823 // is never null.
3824 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3825 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3826 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3827 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3828 return true;
3829 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3831 }
3832
3833 // No need to fall through to computeKnownBits as range metadata is already
3834 // handled in isKnownNonZero.
3835 return false;
3836 }
3837 case Instruction::ExtractValue: {
3838 const WithOverflowInst *WO;
3840 switch (WO->getBinaryOp()) {
3841 default:
3842 break;
3843 case Instruction::Add:
3844 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3845 WO->getArgOperand(1),
3846 /*NSW=*/false,
3847 /*NUW=*/false, Depth);
3848 case Instruction::Sub:
3849 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3850 WO->getArgOperand(1), Depth);
3851 case Instruction::Mul:
3852 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3853 WO->getArgOperand(1),
3854 /*NSW=*/false, /*NUW=*/false, Depth);
3855 break;
3856 }
3857 }
3858 break;
3859 }
3860 case Instruction::Call:
3861 case Instruction::Invoke: {
3862 const auto *Call = cast<CallBase>(I);
3863 if (I->getType()->isPointerTy()) {
3864 if (Call->isReturnNonNull())
3865 return true;
3866 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3867 Call, /*MustPreserveOffset=*/true))
3868 return isKnownNonZero(RP, Q, Depth);
3869 } else {
3870 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3872 if (std::optional<ConstantRange> Range = Call->getRange()) {
3873 const APInt ZeroValue(Range->getBitWidth(), 0);
3874 if (!Range->contains(ZeroValue))
3875 return true;
3876 }
3877 if (const Value *RV = Call->getReturnedArgOperand())
3878 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3879 return true;
3880 }
3881
3882 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3883 switch (II->getIntrinsicID()) {
3884 case Intrinsic::sshl_sat:
3885 case Intrinsic::ushl_sat:
3886 case Intrinsic::abs:
3887 case Intrinsic::bitreverse:
3888 case Intrinsic::bswap:
3889 case Intrinsic::ctpop:
3890 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3891 // NB: We don't do usub_sat here as in any case we can prove its
3892 // non-zero, we will fold it to `sub nuw` in InstCombine.
3893 case Intrinsic::ssub_sat:
3894 // For most types, if x != y then ssub.sat x, y != 0. But
3895 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3896 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3897 if (BitWidth == 1)
3898 return false;
3899 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3900 II->getArgOperand(1), Depth);
3901 case Intrinsic::sadd_sat:
3902 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3903 II->getArgOperand(1),
3904 /*NSW=*/true, /* NUW=*/false, Depth);
3905 // Vec reverse preserves zero/non-zero status from input vec.
3906 case Intrinsic::vector_reverse:
3907 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3908 Q, Depth);
3909 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3910 case Intrinsic::vector_reduce_or:
3911 case Intrinsic::vector_reduce_umax:
3912 case Intrinsic::vector_reduce_umin:
3913 case Intrinsic::vector_reduce_smax:
3914 case Intrinsic::vector_reduce_smin:
3915 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3916 case Intrinsic::umax:
3917 case Intrinsic::uadd_sat:
3918 // umax(X, (X != 0)) is non zero
3919 // X +usat (X != 0) is non zero
3920 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3921 return true;
3922
3923 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3924 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3925 case Intrinsic::smax: {
3926 // If either arg is strictly positive the result is non-zero. Otherwise
3927 // the result is non-zero if both ops are non-zero.
3928 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3929 const KnownBits &OpKnown) {
3930 if (!OpNonZero.has_value())
3931 OpNonZero = OpKnown.isNonZero() ||
3932 isKnownNonZero(Op, DemandedElts, Q, Depth);
3933 return *OpNonZero;
3934 };
3935 // Avoid re-computing isKnownNonZero.
3936 std::optional<bool> Op0NonZero, Op1NonZero;
3937 KnownBits Op1Known =
3938 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3939 if (Op1Known.isNonNegative() &&
3940 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3941 return true;
3942 KnownBits Op0Known =
3943 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3944 if (Op0Known.isNonNegative() &&
3945 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3946 return true;
3947 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3948 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3949 }
3950 case Intrinsic::smin: {
3951 // If either arg is negative the result is non-zero. Otherwise
3952 // the result is non-zero if both ops are non-zero.
3953 KnownBits Op1Known =
3954 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3955 if (Op1Known.isNegative())
3956 return true;
3957 KnownBits Op0Known =
3958 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3959 if (Op0Known.isNegative())
3960 return true;
3961
3962 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3963 return true;
3964 }
3965 [[fallthrough]];
3966 case Intrinsic::umin:
3967 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3968 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3969 case Intrinsic::cttz:
3970 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3971 .Zero[0];
3972 case Intrinsic::ctlz:
3973 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3974 .isNonNegative();
3975 case Intrinsic::fshr:
3976 case Intrinsic::fshl:
3977 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3978 if (II->getArgOperand(0) == II->getArgOperand(1))
3979 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3980 break;
3981 case Intrinsic::vscale:
3982 return true;
3983 case Intrinsic::experimental_get_vector_length:
3984 return isKnownNonZero(I->getOperand(0), Q, Depth);
3985 default:
3986 break;
3987 }
3988 break;
3989 }
3990
3991 return false;
3992 }
3993 }
3994
3996 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3997 return Known.One != 0;
3998}
3999
4000/// Return true if the given value is known to be non-zero when defined. For
4001/// vectors, return true if every demanded element is known to be non-zero when
4002/// defined. For pointers, if the context instruction and dominator tree are
4003/// specified, perform context-sensitive analysis and return true if the
4004/// pointer couldn't possibly be null at the specified instruction.
4005/// Supports values with integer or pointer type and vectors of integers.
4006bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
4007 const SimplifyQuery &Q, unsigned Depth) {
4008 Type *Ty = V->getType();
4009
4010#ifndef NDEBUG
4011 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4012
4013 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4014 assert(
4015 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4016 "DemandedElt width should equal the fixed vector number of elements");
4017 } else {
4018 assert(DemandedElts == APInt(1, 1) &&
4019 "DemandedElt width should be 1 for scalars");
4020 }
4021#endif
4022
4023 if (auto *C = dyn_cast<Constant>(V)) {
4024 if (C->isNullValue())
4025 return false;
4026 if (isa<ConstantInt>(C))
4027 // Must be non-zero due to null test above.
4028 return true;
4029
4030 // For constant vectors, check that all elements are poison or known
4031 // non-zero to determine that the whole vector is known non-zero.
4032 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
4033 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
4034 if (!DemandedElts[i])
4035 continue;
4036 Constant *Elt = C->getAggregateElement(i);
4037 if (!Elt || Elt->isNullValue())
4038 return false;
4039 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
4040 return false;
4041 }
4042 return true;
4043 }
4044
4045 // Constant ptrauth can be null, iff the base pointer can be.
4046 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
4047 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
4048
4049 // A global variable is non null unless extern weak or an absolute symbol
4050 // reference. An alias is also excluded, as it may resolve to a weak
4051 // undefined symbol and thus to the null address. Where null is a valid
4052 // address an allocation may start there, so nothing can be assumed; that
4053 // covers both null_pointer_is_valid and address spaces other than zero.
4054 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
4056 GV->getType()->getAddressSpace()) &&
4057 !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
4058 !isa<GlobalAlias>(GV))
4059 return true;
4060 }
4061
4062 // For constant expressions, fall through to the Operator code below.
4063 if (!isa<ConstantExpr>(V))
4064 return false;
4065 }
4066
4067 if (const auto *A = dyn_cast<Argument>(V))
4068 if (std::optional<ConstantRange> Range = A->getRange()) {
4069 const APInt ZeroValue(Range->getBitWidth(), 0);
4070 if (!Range->contains(ZeroValue))
4071 return true;
4072 }
4073
4075 return true;
4076
4077 // Some of the tests below are recursive, so bail out if we hit the limit.
4079 return false;
4080
4081 // Check for pointer simplifications.
4082
4083 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
4084 // A byval, inalloca may not be null in a non-default addres space. A
4085 // nonnull argument is assumed never 0.
4086 if (const Argument *A = dyn_cast<Argument>(V)) {
4087 if (((A->hasPassPointeeByValueCopyAttr() &&
4088 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
4089 A->hasNonNullAttr()))
4090 return true;
4091 }
4092 }
4093
4094 if (const auto *I = dyn_cast<Operator>(V))
4095 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
4096 return true;
4097
4098 if (!isa<Constant>(V) &&
4100 return true;
4101
4102 if (const Value *Stripped = stripNullTest(V))
4103 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
4104
4105 return false;
4106}
4107
4109 unsigned Depth) {
4110 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
4111 APInt DemandedElts =
4112 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
4113 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
4114}
4115
4116/// If the pair of operators are the same invertible function, return the
4117/// the operands of the function corresponding to each input. Otherwise,
4118/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
4119/// every input value to exactly one output value. This is equivalent to
4120/// saying that Op1 and Op2 are equal exactly when the specified pair of
4121/// operands are equal, (except that Op1 and Op2 may be poison more often.)
4122static std::optional<std::pair<Value*, Value*>>
4124 const Operator *Op2) {
4125 if (Op1->getOpcode() != Op2->getOpcode())
4126 return std::nullopt;
4127
4128 auto getOperands = [&](unsigned OpNum) -> auto {
4129 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
4130 };
4131
4132 switch (Op1->getOpcode()) {
4133 default:
4134 break;
4135 case Instruction::Or:
4136 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
4137 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
4138 break;
4139 [[fallthrough]];
4140 case Instruction::Xor:
4141 case Instruction::Add: {
4142 Value *Other;
4143 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
4144 return std::make_pair(Op1->getOperand(1), Other);
4145 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
4146 return std::make_pair(Op1->getOperand(0), Other);
4147 break;
4148 }
4149 case Instruction::Sub:
4150 if (Op1->getOperand(0) == Op2->getOperand(0))
4151 return getOperands(1);
4152 if (Op1->getOperand(1) == Op2->getOperand(1))
4153 return getOperands(0);
4154 break;
4155 case Instruction::Mul: {
4156 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
4157 // and N is the bitwdith. The nsw case is non-obvious, but proven by
4158 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
4159 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4160 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4161 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4162 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4163 break;
4164
4165 // Assume operand order has been canonicalized
4166 if (Op1->getOperand(1) == Op2->getOperand(1) &&
4167 isa<ConstantInt>(Op1->getOperand(1)) &&
4168 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
4169 return getOperands(0);
4170 break;
4171 }
4172 case Instruction::Shl: {
4173 // Same as multiplies, with the difference that we don't need to check
4174 // for a non-zero multiply. Shifts always multiply by non-zero.
4175 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4176 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4177 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4178 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4179 break;
4180
4181 if (Op1->getOperand(1) == Op2->getOperand(1))
4182 return getOperands(0);
4183 break;
4184 }
4185 case Instruction::AShr:
4186 case Instruction::LShr: {
4187 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4188 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4189 if (!PEO1->isExact() || !PEO2->isExact())
4190 break;
4191
4192 if (Op1->getOperand(1) == Op2->getOperand(1))
4193 return getOperands(0);
4194 break;
4195 }
4196 case Instruction::SExt:
4197 case Instruction::ZExt:
4198 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4199 return getOperands(0);
4200 break;
4201 case Instruction::PHI: {
4202 const PHINode *PN1 = cast<PHINode>(Op1);
4203 const PHINode *PN2 = cast<PHINode>(Op2);
4204
4205 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4206 // are a single invertible function of the start values? Note that repeated
4207 // application of an invertible function is also invertible
4208 BinaryOperator *BO1 = nullptr;
4209 Value *Start1 = nullptr, *Step1 = nullptr;
4210 BinaryOperator *BO2 = nullptr;
4211 Value *Start2 = nullptr, *Step2 = nullptr;
4212 if (PN1->getParent() != PN2->getParent() ||
4213 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4214 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4215 break;
4216
4218 cast<Operator>(BO2));
4219 if (!Values)
4220 break;
4221
4222 // We have to be careful of mutually defined recurrences here. Ex:
4223 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4224 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4225 // The invertibility of these is complicated, and not worth reasoning
4226 // about (yet?).
4227 if (Values->first != PN1 || Values->second != PN2)
4228 break;
4229
4230 return std::make_pair(Start1, Start2);
4231 }
4232 }
4233 return std::nullopt;
4234}
4235
4236/// Return true if V1 == (binop V2, X), where X is known non-zero.
4237/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4238/// implies V2 != V1.
4239static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4240 const APInt &DemandedElts,
4241 const SimplifyQuery &Q, unsigned Depth) {
4243 if (!BO)
4244 return false;
4245 switch (BO->getOpcode()) {
4246 default:
4247 break;
4248 case Instruction::Or:
4249 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4250 break;
4251 [[fallthrough]];
4252 case Instruction::Xor:
4253 case Instruction::Add:
4254 Value *Op = nullptr;
4255 if (V2 == BO->getOperand(0))
4256 Op = BO->getOperand(1);
4257 else if (V2 == BO->getOperand(1))
4258 Op = BO->getOperand(0);
4259 else
4260 return false;
4261 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4262 }
4263 return false;
4264}
4265
4266/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4267/// the multiplication is nuw or nsw.
4268static bool isNonEqualMul(const Value *V1, const Value *V2,
4269 const APInt &DemandedElts, const SimplifyQuery &Q,
4270 unsigned Depth) {
4271 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4272 const APInt *C;
4273 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4274 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4275 !C->isZero() && !C->isOne() &&
4276 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4277 }
4278 return false;
4279}
4280
4281/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4282/// the shift is nuw or nsw.
4283static bool isNonEqualShl(const Value *V1, const Value *V2,
4284 const APInt &DemandedElts, const SimplifyQuery &Q,
4285 unsigned Depth) {
4286 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4287 const APInt *C;
4288 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4289 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4290 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4291 }
4292 return false;
4293}
4294
4295static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4296 const APInt &DemandedElts, const SimplifyQuery &Q,
4297 unsigned Depth) {
4298 // Check two PHIs are in same block.
4299 if (PN1->getParent() != PN2->getParent())
4300 return false;
4301
4303 bool UsedFullRecursion = false;
4304 for (const BasicBlock *IncomBB : PN1->blocks()) {
4305 if (!VisitedBBs.insert(IncomBB).second)
4306 continue; // Don't reprocess blocks that we have dealt with already.
4307 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4308 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4309 const APInt *C1, *C2;
4310 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4311 continue;
4312
4313 // Only one pair of phi operands is allowed for full recursion.
4314 if (UsedFullRecursion)
4315 return false;
4316
4318 RecQ.CtxI = IncomBB->getTerminator();
4319 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4320 return false;
4321 UsedFullRecursion = true;
4322 }
4323 return true;
4324}
4325
4326static bool isNonEqualSelect(const Value *V1, const Value *V2,
4327 const APInt &DemandedElts, const SimplifyQuery &Q,
4328 unsigned Depth) {
4329 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4330 if (!SI1)
4331 return false;
4332
4333 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4334 const Value *Cond1 = SI1->getCondition();
4335 const Value *Cond2 = SI2->getCondition();
4336 if (Cond1 == Cond2)
4337 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4338 DemandedElts, Q, Depth + 1) &&
4339 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4340 DemandedElts, Q, Depth + 1);
4341 }
4342 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4343 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4344}
4345
4346// Check to see if A is both a GEP and is the incoming value for a PHI in the
4347// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4348// one of them being the recursive GEP A and the other a ptr at same base and at
4349// the same/higher offset than B we are only incrementing the pointer further in
4350// loop if offset of recursive GEP is greater than 0.
4352 const SimplifyQuery &Q) {
4353 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4354 return false;
4355
4356 auto *GEPA = dyn_cast<GEPOperator>(A);
4357 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4358 return false;
4359
4360 // Handle 2 incoming PHI values with one being a recursive GEP.
4361 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4362 if (!PN || PN->getNumIncomingValues() != 2)
4363 return false;
4364
4365 // Search for the recursive GEP as an incoming operand, and record that as
4366 // Step.
4367 Value *Start = nullptr;
4368 Value *Step = const_cast<Value *>(A);
4369 if (PN->getIncomingValue(0) == Step)
4370 Start = PN->getIncomingValue(1);
4371 else if (PN->getIncomingValue(1) == Step)
4372 Start = PN->getIncomingValue(0);
4373 else
4374 return false;
4375
4376 // Other incoming node base should match the B base.
4377 // StartOffset >= OffsetB && StepOffset > 0?
4378 // StartOffset <= OffsetB && StepOffset < 0?
4379 // Is non-equal if above are true.
4380 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4381 // optimisation to inbounds GEPs only.
4382 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4383 APInt StartOffset(IndexWidth, 0);
4384 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4385 APInt StepOffset(IndexWidth, 0);
4386 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4387
4388 // Check if Base Pointer of Step matches the PHI.
4389 if (Step != PN)
4390 return false;
4391 APInt OffsetB(IndexWidth, 0);
4392 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4393 return Start == B &&
4394 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4395 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4396}
4397
4398static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4399 const SimplifyQuery &Q, unsigned Depth) {
4400 if (!Q.CtxI)
4401 return false;
4402
4403 // Try to infer NonEqual based on information from dominating conditions.
4404 if (Q.DC && Q.DT) {
4405 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4406 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4407 Value *Cond = BI->getCondition();
4408 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4409 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4411 /*LHSIsTrue=*/true, Depth)
4412 .value_or(false))
4413 return true;
4414
4415 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4416 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4418 /*LHSIsTrue=*/false, Depth)
4419 .value_or(false))
4420 return true;
4421 }
4422
4423 return false;
4424 };
4425
4426 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4427 IsKnownNonEqualFromDominatingCondition(V2))
4428 return true;
4429 }
4430
4431 if (!Q.AC)
4432 return false;
4433
4434 // Try to infer NonEqual based on information from assumptions.
4435 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4436 if (!AssumeVH)
4437 continue;
4438 CallInst *I = cast<CallInst>(AssumeVH);
4439
4440 assert(I->getFunction() == Q.CtxI->getFunction() &&
4441 "Got assumption for the wrong function!");
4442 assert(I->getIntrinsicID() == Intrinsic::assume &&
4443 "must be an assume intrinsic");
4444
4445 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4446 /*LHSIsTrue=*/true, Depth)
4447 .value_or(false) &&
4449 return true;
4450 }
4451
4452 return false;
4453}
4454
4455static bool isNonEqualURem(const Value *X, const Value *Rem,
4456 const SimplifyQuery &Q) {
4457 const Value *Y;
4458 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4459 return false;
4460
4461 // For a defined urem, X != X urem Y exactly when X u>= Y.
4462 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4464 return true;
4465
4466 std::optional<bool> Implied =
4468 return Implied && *Implied;
4469}
4470
4471/// Return true if it is known that V1 != V2.
4472static bool isKnownNonEqual(const Value *V1, const Value *V2,
4473 const APInt &DemandedElts, const SimplifyQuery &Q,
4474 unsigned Depth) {
4475 if (V1 == V2)
4476 return false;
4477 if (V1->getType() != V2->getType())
4478 // We can't look through casts yet.
4479 return false;
4480
4482 return false;
4483
4484 // See if we can recurse through (exactly one of) our operands. This
4485 // requires our operation be 1-to-1 and map every input value to exactly
4486 // one output value. Such an operation is invertible.
4487 auto *O1 = dyn_cast<Operator>(V1);
4488 auto *O2 = dyn_cast<Operator>(V2);
4489 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4490 if (auto Values = getInvertibleOperands(O1, O2))
4491 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4492 Depth + 1);
4493
4494 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4495 const PHINode *PN2 = cast<PHINode>(V2);
4496 // FIXME: This is missing a generalization to handle the case where one is
4497 // a PHI and another one isn't.
4498 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4499 return true;
4500 };
4501 }
4502
4503 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4504 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4505 return true;
4506
4507 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4508 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4509 return true;
4510
4511 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4512 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4513 return true;
4514
4515 if (V1->getType()->isIntOrIntVectorTy()) {
4516 // Are any known bits in V1 contradictory to known bits in V2? If V1
4517 // has a known zero where V2 has a known one, they must not be equal.
4518 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4519 if (!Known1.isUnknown()) {
4520 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4521 if (Known1.Zero.intersects(Known2.One) ||
4522 Known2.Zero.intersects(Known1.One))
4523 return true;
4524 }
4525 }
4526
4527 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4528 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4529 return true;
4530
4533 return true;
4534
4535 Value *A, *B;
4536 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4537 // Check PtrToInt type matches the pointer size.
4538 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4540 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4541
4542 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4543 return true;
4544
4545 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4546 return true;
4547
4548 return false;
4549}
4550
4551/// For vector constants, loop over the elements and find the constant with the
4552/// minimum number of sign bits. Return 0 if the value is not a vector constant
4553/// or if any element was not analyzed; otherwise, return the count for the
4554/// element with the minimum number of sign bits.
4556 const APInt &DemandedElts,
4557 unsigned TyBits) {
4558 const auto *CV = dyn_cast<Constant>(V);
4559 if (!CV || !isa<FixedVectorType>(CV->getType()))
4560 return 0;
4561
4562 unsigned MinSignBits = TyBits;
4563 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4564 for (unsigned i = 0; i != NumElts; ++i) {
4565 if (!DemandedElts[i])
4566 continue;
4567 // If we find a non-ConstantInt, bail out.
4568 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4569 if (!Elt)
4570 return 0;
4571
4572 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4573 }
4574
4575 return MinSignBits;
4576}
4577
4578static unsigned computeNumSignBitsImpl(const Value *V,
4579 const APInt &DemandedElts,
4580 const SimplifyQuery &Q, unsigned Depth);
4581
4582static unsigned computeNumSignBits(const Value *V, const APInt &DemandedElts,
4583 const SimplifyQuery &Q, unsigned Depth) {
4584 unsigned Result = computeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4585 assert(Result > 0 && "At least one sign bit needs to be present!");
4586 return Result;
4587}
4588
4589/// Return the number of times the sign bit of the register is replicated into
4590/// the other bits. We know that at least 1 bit is always equal to the sign bit
4591/// (itself), but other cases can give us information. For example, immediately
4592/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4593/// other, so we return 3. For vectors, return the number of sign bits for the
4594/// vector element with the minimum number of known sign bits of the demanded
4595/// elements in the vector specified by DemandedElts.
4596static unsigned computeNumSignBitsImpl(const Value *V,
4597 const APInt &DemandedElts,
4598 const SimplifyQuery &Q, unsigned Depth) {
4599 Type *Ty = V->getType();
4600#ifndef NDEBUG
4601 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4602
4603 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4604 assert(
4605 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4606 "DemandedElt width should equal the fixed vector number of elements");
4607 } else {
4608 assert(DemandedElts == APInt(1, 1) &&
4609 "DemandedElt width should be 1 for scalars");
4610 }
4611#endif
4612
4613 // We return the minimum number of sign bits that are guaranteed to be present
4614 // in V, so for undef we have to conservatively return 1. We don't have the
4615 // same behavior for poison though -- that's a FIXME today.
4616
4617 Type *ScalarTy = Ty->getScalarType();
4618 unsigned TyBits = ScalarTy->isPointerTy() ?
4619 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4620 Q.DL.getTypeSizeInBits(ScalarTy);
4621
4622 unsigned Tmp, Tmp2;
4623 unsigned FirstAnswer = 1;
4624
4625 // Note that ConstantInt is handled by the general computeKnownBits case
4626 // below.
4627
4629 return 1;
4630
4631 if (auto *U = dyn_cast<Operator>(V)) {
4632 switch (Operator::getOpcode(V)) {
4633 default: break;
4634 case Instruction::BitCast: {
4635 Value *Src = U->getOperand(0);
4636 Type *SrcTy = Src->getType();
4637
4638 // Skip if the source type is not an integer or integer vector type
4639 // This ensures we only process integer-like types
4640 if (!SrcTy->isIntOrIntVectorTy())
4641 break;
4642
4643 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4644
4645 // Bitcast 'large element' scalar/vector to 'small element' vector.
4646 if ((SrcBits % TyBits) != 0)
4647 break;
4648
4649 // Only proceed if the destination type is a fixed-size vector
4650 if (isa<FixedVectorType>(Ty)) {
4651 // Fast case - sign splat can be simply split across the small elements.
4652 // This works for both vector and scalar sources
4653 unsigned Scale = SrcBits / TyBits;
4654 APInt SrcDemandedElts = APIntOps::ScaleBitMask(
4655 DemandedElts, DemandedElts.getBitWidth() / Scale);
4656 Tmp = computeNumSignBits(Src, SrcDemandedElts, Q, Depth + 1);
4657 if (Tmp == SrcBits)
4658 return TyBits;
4659 }
4660 break;
4661 }
4662 case Instruction::SExt:
4663 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4664 return computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4665 Tmp;
4666
4667 case Instruction::SDiv: {
4668 const APInt *Denominator;
4669 // sdiv X, C -> adds log(C) sign bits.
4670 if (match(U->getOperand(1), m_APInt(Denominator))) {
4671
4672 // Ignore non-positive denominator.
4673 if (!Denominator->isStrictlyPositive())
4674 break;
4675
4676 // Calculate the incoming numerator bits.
4677 unsigned NumBits =
4678 computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4679
4680 // Add floor(log(C)) bits to the numerator bits.
4681 return std::min(TyBits, NumBits + Denominator->logBase2());
4682 }
4683 break;
4684 }
4685
4686 case Instruction::SRem: {
4687 Tmp = computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4688
4689 const APInt *Denominator;
4690 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4691 // positive constant. This let us put a lower bound on the number of sign
4692 // bits.
4693 if (match(U->getOperand(1), m_APInt(Denominator))) {
4694
4695 // Ignore non-positive denominator.
4696 if (Denominator->isStrictlyPositive()) {
4697 // Calculate the leading sign bit constraints by examining the
4698 // denominator. Given that the denominator is positive, there are two
4699 // cases:
4700 //
4701 // 1. The numerator is positive. The result range is [0,C) and
4702 // [0,C) u< (1 << ceilLogBase2(C)).
4703 //
4704 // 2. The numerator is negative. Then the result range is (-C,0] and
4705 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4706 //
4707 // Thus a lower bound on the number of sign bits is `TyBits -
4708 // ceilLogBase2(C)`.
4709
4710 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4711 Tmp = std::max(Tmp, ResBits);
4712 }
4713 }
4714 return Tmp;
4715 }
4716
4717 case Instruction::AShr: {
4718 Tmp = computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4719 // ashr X, C -> adds C sign bits. Vectors too.
4720 const APInt *ShAmt;
4721 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4722 if (ShAmt->uge(TyBits))
4723 break; // Bad shift.
4724 unsigned ShAmtLimited = ShAmt->getZExtValue();
4725 Tmp += ShAmtLimited;
4726 if (Tmp > TyBits) Tmp = TyBits;
4727 }
4728 return Tmp;
4729 }
4730 case Instruction::Shl: {
4731 const APInt *ShAmt;
4732 Value *X = nullptr;
4733 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4734 // shl destroys sign bits.
4735 if (ShAmt->uge(TyBits))
4736 break; // Bad shift.
4737 // We can look through a zext (more or less treating it as a sext) if
4738 // all extended bits are shifted out.
4739 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4740 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4741 Tmp = computeNumSignBits(X, DemandedElts, Q, Depth + 1);
4742 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4743 } else
4744 Tmp =
4745 computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4746 if (ShAmt->uge(Tmp))
4747 break; // Shifted all sign bits out.
4748 Tmp2 = ShAmt->getZExtValue();
4749 return Tmp - Tmp2;
4750 }
4751 break;
4752 }
4753 case Instruction::And:
4754 case Instruction::Or:
4755 case Instruction::Xor: // NOT is handled here.
4756 // Logical binary ops preserve the number of sign bits at the worst.
4757 Tmp = computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4758 if (Tmp != 1) {
4759 Tmp2 = computeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4760 FirstAnswer = std::min(Tmp, Tmp2);
4761 // We computed what we know about the sign bits as our first
4762 // answer. Now proceed to the generic code that uses
4763 // computeKnownBits, and pick whichever answer is better.
4764 }
4765 break;
4766
4767 case Instruction::Select: {
4768 // If we have a clamp pattern, we know that the number of sign bits will
4769 // be the minimum of the clamp min/max range.
4770 const Value *X;
4771 const APInt *CLow, *CHigh;
4772 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4773 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4774
4775 Tmp = computeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4776 if (Tmp == 1)
4777 break;
4778 Tmp2 = computeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4779 return std::min(Tmp, Tmp2);
4780 }
4781
4782 case Instruction::Add:
4783 // Add can have at most one carry bit. Thus we know that the output
4784 // is, at worst, one more bit than the inputs.
4785 Tmp = computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4786 if (Tmp == 1) break;
4787
4788 // Special case decrementing a value (ADD X, -1):
4789 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4790 if (CRHS->isAllOnesValue()) {
4791 KnownBits Known(TyBits);
4792 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4793
4794 // If the input is known to be 0 or 1, the output is 0/-1, which is
4795 // all sign bits set.
4796 if ((Known.Zero | 1).isAllOnes())
4797 return TyBits;
4798
4799 // If we are subtracting one from a positive number, there is no carry
4800 // out of the result.
4801 if (Known.isNonNegative())
4802 return Tmp;
4803 }
4804
4805 Tmp2 = computeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4806 if (Tmp2 == 1)
4807 break;
4808 return std::min(Tmp, Tmp2) - 1;
4809
4810 case Instruction::Sub:
4811 Tmp2 = computeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4812 if (Tmp2 == 1)
4813 break;
4814
4815 // Handle NEG.
4816 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4817 if (CLHS->isNullValue()) {
4818 KnownBits Known(TyBits);
4819 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4820 // If the input is known to be 0 or 1, the output is 0/-1, which is
4821 // all sign bits set.
4822 if ((Known.Zero | 1).isAllOnes())
4823 return TyBits;
4824
4825 // If the input is known to be positive (the sign bit is known clear),
4826 // the output of the NEG has the same number of sign bits as the
4827 // input.
4828 if (Known.isNonNegative())
4829 return Tmp2;
4830
4831 // Otherwise, we treat this like a SUB.
4832 }
4833
4834 // Sub can have at most one carry bit. Thus we know that the output
4835 // is, at worst, one more bit than the inputs.
4836 Tmp = computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4837 if (Tmp == 1)
4838 break;
4839 return std::min(Tmp, Tmp2) - 1;
4840
4841 case Instruction::Mul: {
4842 // The output of the Mul can be at most twice the valid bits in the
4843 // inputs.
4844 unsigned SignBitsOp0 =
4845 computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4846 if (SignBitsOp0 == 1)
4847 break;
4848 unsigned SignBitsOp1 =
4849 computeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4850 if (SignBitsOp1 == 1)
4851 break;
4852 unsigned OutValidBits =
4853 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4854 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4855 }
4856
4857 case Instruction::PHI: {
4858 const PHINode *PN = cast<PHINode>(U);
4859 unsigned NumIncomingValues = PN->getNumIncomingValues();
4860 // Don't analyze large in-degree PHIs.
4861 if (NumIncomingValues > 4) break;
4862 // Unreachable blocks may have zero-operand PHI nodes.
4863 if (NumIncomingValues == 0) break;
4864
4865 // Take the minimum of all incoming values. This can't infinitely loop
4866 // because of our depth threshold.
4868 Tmp = TyBits;
4869 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4870 if (Tmp == 1) return Tmp;
4871 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4872 Tmp = std::min(Tmp, computeNumSignBits(PN->getIncomingValue(i),
4873 DemandedElts, RecQ, Depth + 1));
4874 }
4875 return Tmp;
4876 }
4877
4878 case Instruction::Trunc: {
4879 // If the input contained enough sign bits that some remain after the
4880 // truncation, then we can make use of that. Otherwise we don't know
4881 // anything.
4882 Tmp = computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4883 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4884 if (Tmp > (OperandTyBits - TyBits))
4885 return Tmp - (OperandTyBits - TyBits);
4886
4887 return 1;
4888 }
4889
4890 case Instruction::ExtractElement: {
4891 const Value *Vec = U->getOperand(0);
4892 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
4893 if (!VecTy)
4894 return computeNumSignBits(Vec, Q, Depth + 1);
4895
4896 unsigned NumElts = VecTy->getNumElements();
4897 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
4898 if (auto *CIdx = dyn_cast<ConstantInt>(U->getOperand(1)))
4899 if (CIdx->getValue().ult(NumElts))
4900 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
4901 return computeNumSignBits(Vec, DemandedVecElts, Q, Depth + 1);
4902 }
4903
4904 case Instruction::ShuffleVector: {
4905 // Collect the minimum number of sign bits that are shared by every vector
4906 // element referenced by the shuffle.
4907 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4908 if (!Shuf) {
4909 // FIXME: Add support for shufflevector constant expressions.
4910 return 1;
4911 }
4912 APInt DemandedLHS, DemandedRHS;
4913 // For undef elements, we don't know anything about the common state of
4914 // the shuffle result.
4915 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4916 return 1;
4917 Tmp = std::numeric_limits<unsigned>::max();
4918 if (!!DemandedLHS) {
4919 const Value *LHS = Shuf->getOperand(0);
4920 Tmp = computeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4921 }
4922 // If we don't know anything, early out and try computeKnownBits
4923 // fall-back.
4924 if (Tmp == 1)
4925 break;
4926 if (!!DemandedRHS) {
4927 const Value *RHS = Shuf->getOperand(1);
4928 Tmp2 = computeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4929 Tmp = std::min(Tmp, Tmp2);
4930 }
4931 // If we don't know anything, early out and try computeKnownBits
4932 // fall-back.
4933 if (Tmp == 1)
4934 break;
4935 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4936 return Tmp;
4937 }
4938 case Instruction::Call: {
4939 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4940 switch (II->getIntrinsicID()) {
4941 default:
4942 break;
4943 case Intrinsic::abs:
4944 Tmp =
4945 computeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4946 if (Tmp == 1)
4947 break;
4948
4949 // Absolute value reduces number of sign bits by at most 1.
4950 return Tmp - 1;
4951 case Intrinsic::smin:
4952 case Intrinsic::smax: {
4953 const APInt *CLow, *CHigh;
4954 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4955 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4956 }
4957 }
4958 }
4959 }
4960 }
4961 }
4962
4963 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4964 // use this information.
4965
4966 // If we can examine all elements of a vector constant successfully, we're
4967 // done (we can't do any better than that). If not, keep trying.
4968 if (unsigned VecSignBits =
4969 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4970 return VecSignBits;
4971
4972 KnownBits Known(TyBits);
4973 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4974
4975 // If we know that the sign bit is either zero or one, determine the number of
4976 // identical bits in the top of the input value.
4977 return std::max(FirstAnswer, Known.countMinSignBits());
4978}
4979
4981 const TargetLibraryInfo *TLI) {
4982 const Function *F = CB.getCalledFunction();
4983 if (!F)
4985
4986 if (F->isIntrinsic())
4987 return F->getIntrinsicID();
4988
4989 // We are going to infer semantics of a library function based on mapping it
4990 // to an LLVM intrinsic. Check that the library function is available from
4991 // this callbase and in this environment.
4992 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4994
4995 LibFunc Func = TLI->getLibFunc(CB);
4996 if (Func == NotLibFunc)
4998
4999 switch (Func) {
5000 default:
5001 break;
5002 case LibFunc_sin:
5003 case LibFunc_sinf:
5004 case LibFunc_sinl:
5005 return Intrinsic::sin;
5006 case LibFunc_cos:
5007 case LibFunc_cosf:
5008 case LibFunc_cosl:
5009 return Intrinsic::cos;
5010 case LibFunc_tan:
5011 case LibFunc_tanf:
5012 case LibFunc_tanl:
5013 return Intrinsic::tan;
5014 case LibFunc_asin:
5015 case LibFunc_asinf:
5016 case LibFunc_asinl:
5017 return Intrinsic::asin;
5018 case LibFunc_acos:
5019 case LibFunc_acosf:
5020 case LibFunc_acosl:
5021 return Intrinsic::acos;
5022 case LibFunc_atan:
5023 case LibFunc_atanf:
5024 case LibFunc_atanl:
5025 return Intrinsic::atan;
5026 case LibFunc_atan2:
5027 case LibFunc_atan2f:
5028 case LibFunc_atan2l:
5029 return Intrinsic::atan2;
5030 case LibFunc_sinh:
5031 case LibFunc_sinhf:
5032 case LibFunc_sinhl:
5033 return Intrinsic::sinh;
5034 case LibFunc_cosh:
5035 case LibFunc_coshf:
5036 case LibFunc_coshl:
5037 return Intrinsic::cosh;
5038 case LibFunc_tanh:
5039 case LibFunc_tanhf:
5040 case LibFunc_tanhl:
5041 return Intrinsic::tanh;
5042 case LibFunc_exp:
5043 case LibFunc_expf:
5044 case LibFunc_expl:
5045 return Intrinsic::exp;
5046 case LibFunc_exp2:
5047 case LibFunc_exp2f:
5048 case LibFunc_exp2l:
5049 return Intrinsic::exp2;
5050 case LibFunc_exp10:
5051 case LibFunc_exp10f:
5052 case LibFunc_exp10l:
5053 return Intrinsic::exp10;
5054 case LibFunc_log:
5055 case LibFunc_logf:
5056 case LibFunc_logl:
5057 return Intrinsic::log;
5058 case LibFunc_log10:
5059 case LibFunc_log10f:
5060 case LibFunc_log10l:
5061 return Intrinsic::log10;
5062 case LibFunc_log2:
5063 case LibFunc_log2f:
5064 case LibFunc_log2l:
5065 return Intrinsic::log2;
5066 case LibFunc_fabs:
5067 case LibFunc_fabsf:
5068 case LibFunc_fabsl:
5069 return Intrinsic::fabs;
5070 case LibFunc_fmin:
5071 case LibFunc_fminf:
5072 case LibFunc_fminl:
5073 return Intrinsic::minnum;
5074 case LibFunc_fmax:
5075 case LibFunc_fmaxf:
5076 case LibFunc_fmaxl:
5077 return Intrinsic::maxnum;
5078 case LibFunc_copysign:
5079 case LibFunc_copysignf:
5080 case LibFunc_copysignl:
5081 return Intrinsic::copysign;
5082 case LibFunc_floor:
5083 case LibFunc_floorf:
5084 case LibFunc_floorl:
5085 return Intrinsic::floor;
5086 case LibFunc_ceil:
5087 case LibFunc_ceilf:
5088 case LibFunc_ceill:
5089 return Intrinsic::ceil;
5090 case LibFunc_trunc:
5091 case LibFunc_truncf:
5092 case LibFunc_truncl:
5093 return Intrinsic::trunc;
5094 case LibFunc_rint:
5095 case LibFunc_rintf:
5096 case LibFunc_rintl:
5097 return Intrinsic::rint;
5098 case LibFunc_nearbyint:
5099 case LibFunc_nearbyintf:
5100 case LibFunc_nearbyintl:
5101 return Intrinsic::nearbyint;
5102 case LibFunc_round:
5103 case LibFunc_roundf:
5104 case LibFunc_roundl:
5105 return Intrinsic::round;
5106 case LibFunc_roundeven:
5107 case LibFunc_roundevenf:
5108 case LibFunc_roundevenl:
5109 return Intrinsic::roundeven;
5110 case LibFunc_pow:
5111 case LibFunc_powf:
5112 case LibFunc_powl:
5113 return Intrinsic::pow;
5114 case LibFunc_sqrt:
5115 case LibFunc_sqrtf:
5116 case LibFunc_sqrtl:
5117 return Intrinsic::sqrt;
5118 }
5119
5121}
5122
5123/// Given an exploded icmp instruction, return true if the comparison only
5124/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
5125/// the result of the comparison is true when the input value is signed.
5127 bool &TrueIfSigned) {
5128 switch (Pred) {
5129 case ICmpInst::ICMP_SLT: // True if LHS s< 0
5130 TrueIfSigned = true;
5131 return RHS.isZero();
5132 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
5133 TrueIfSigned = true;
5134 return RHS.isAllOnes();
5135 case ICmpInst::ICMP_SGT: // True if LHS s> -1
5136 TrueIfSigned = false;
5137 return RHS.isAllOnes();
5138 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
5139 TrueIfSigned = false;
5140 return RHS.isZero();
5141 case ICmpInst::ICMP_UGT:
5142 // True if LHS u> RHS and RHS == sign-bit-mask - 1
5143 TrueIfSigned = true;
5144 return RHS.isMaxSignedValue();
5145 case ICmpInst::ICMP_UGE:
5146 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5147 TrueIfSigned = true;
5148 return RHS.isMinSignedValue();
5149 case ICmpInst::ICMP_ULT:
5150 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5151 TrueIfSigned = false;
5152 return RHS.isMinSignedValue();
5153 case ICmpInst::ICMP_ULE:
5154 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
5155 TrueIfSigned = false;
5156 return RHS.isMaxSignedValue();
5157 default:
5158 return false;
5159 }
5160}
5161
5162/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5163/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5164/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5165/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5166/// exponent range is [-149, -2], but the 0 edge case is above this range).
5167static std::tuple<int, int, int>
5169 if (!Q.CtxI || !Q.DC || !Q.DT)
5171
5172 // Intersect the bounds implied by every dominating condition, keeping the
5173 // tightest maximum. A value may participate in multiple compares
5174 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5175 int MaxExp = APFloat::IEK_Inf;
5176 int MaxExpNonZero = APFloat::IEK_Inf;
5177
5178 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5180 const APFloat *LimitC;
5181 if (!match(BI->getCondition(),
5182 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5183 continue;
5184
5187 continue;
5188
5189 // If fabs(x) <= K, implies the exponent min exp range.
5190 // if fabs(x) >= K, swap the successor
5191 bool IsLessEqual =
5195
5196 bool KnownStrictlyLess =
5199
5200 BasicBlockEdge Edge1(BI->getParent(),
5201 BI->getSuccessor(IsLessEqual ? 0 : 1));
5202 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5203 // frexp returns an exponent one greater than ilogb.
5204 int Exp = ilogb(*LimitC) + 1;
5205
5206 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5207 // exponent drops by one when K is exact power of two.
5208 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5209 --Exp;
5210
5211 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5212 // may exclude.
5213
5214 // TODO: Figure out lower bound to detect no-underflow.
5215 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5216 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5217 }
5218 }
5219
5220 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5221}
5222
5224
5225 // All byte-wide stores are splatable, even of arbitrary variables.
5226 if (V->getType()->isIntegerTy(8))
5227 return V;
5228
5229 LLVMContext &Ctx = V->getContext();
5230
5231 // Undef don't care.
5232 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
5233 if (isa<UndefValue>(V))
5234 return UndefInt8;
5235
5236 // Return poison for zero-sized type.
5237 if (DL.getTypeStoreSize(V->getType()).isZero())
5238 return PoisonValue::get(Type::getInt8Ty(Ctx));
5239
5241 if (!C) {
5242 // Conceptually, we could handle things like:
5243 // %a = zext i8 %X to i16
5244 // %b = shl i16 %a, 8
5245 // %c = or i16 %a, %b
5246 // but until there is an example that actually needs this, it doesn't seem
5247 // worth worrying about.
5248 return nullptr;
5249 }
5250
5251 // Handle 'null' ConstantArrayZero etc.
5252 if (C->isNullValue())
5254
5255 // Constant floating-point values can be handled as integer values if the
5256 // corresponding integer value is "byteable". An important case is 0.0.
5257 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
5258 Type *ScalarTy = CFP->getType()->getScalarType();
5259 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
5260 return isBytewiseValue(
5261 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
5262
5263 // Don't handle long double formats, which have strange constraints.
5264 return nullptr;
5265 }
5266
5267 // We can handle constant integers that are multiple of 8 bits.
5268 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
5269 if (CI->getBitWidth() % 8 == 0) {
5270 if (!CI->getValue().isSplat(8))
5271 return nullptr;
5272 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
5273 }
5274 }
5275
5276 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
5277 if (CE->getOpcode() == Instruction::IntToPtr) {
5278 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
5279 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
5281 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
5282 return isBytewiseValue(Op, DL);
5283 }
5284 }
5285 }
5286
5287 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
5288 if (LHS == RHS)
5289 return LHS;
5290 if (!LHS || !RHS)
5291 return nullptr;
5292 if (LHS == UndefInt8)
5293 return RHS;
5294 if (RHS == UndefInt8)
5295 return LHS;
5296 return nullptr;
5297 };
5298
5300 Value *Val = UndefInt8;
5301 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
5302 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
5303 return nullptr;
5304 return Val;
5305 }
5306
5308 Value *Val = UndefInt8;
5309 for (Value *Op : C->operands())
5310 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
5311 return nullptr;
5312 return Val;
5313 }
5314
5315 // Don't try to handle the handful of other constants.
5316 return nullptr;
5317}
5318
5319// This is the recursive version of BuildSubAggregate. It takes a few different
5320// arguments. Idxs is the index within the nested struct From that we are
5321// looking at now (which is of type IndexedType). IdxSkip is the number of
5322// indices from Idxs that should be left out when inserting into the resulting
5323// struct. To is the result struct built so far, new insertvalue instructions
5324// build on that.
5325static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
5327 unsigned IdxSkip,
5328 BasicBlock::iterator InsertBefore) {
5329 StructType *STy = dyn_cast<StructType>(IndexedType);
5330 if (STy) {
5331 // Save the original To argument so we can modify it
5332 Value *OrigTo = To;
5333 // General case, the type indexed by Idxs is a struct
5334 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
5335 // Process each struct element recursively
5336 Idxs.push_back(i);
5337 Value *PrevTo = To;
5338 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
5339 InsertBefore);
5340 Idxs.pop_back();
5341 if (!To) {
5342 // Couldn't find any inserted value for this index? Cleanup
5343 while (PrevTo != OrigTo) {
5345 PrevTo = Del->getAggregateOperand();
5346 Del->eraseFromParent();
5347 }
5348 // Stop processing elements
5349 break;
5350 }
5351 }
5352 // If we successfully found a value for each of our subaggregates
5353 if (To)
5354 return To;
5355 }
5356 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
5357 // the struct's elements had a value that was inserted directly. In the latter
5358 // case, perhaps we can't determine each of the subelements individually, but
5359 // we might be able to find the complete struct somewhere.
5360
5361 // Find the value that is at that particular spot
5362 Value *V = FindInsertedValue(From, Idxs);
5363
5364 if (!V)
5365 return nullptr;
5366
5367 // Insert the value in the new (sub) aggregate
5368 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
5369 InsertBefore);
5370}
5371
5372// This helper takes a nested struct and extracts a part of it (which is again a
5373// struct) into a new value. For example, given the struct:
5374// { a, { b, { c, d }, e } }
5375// and the indices "1, 1" this returns
5376// { c, d }.
5377//
5378// It does this by inserting an insertvalue for each element in the resulting
5379// struct, as opposed to just inserting a single struct. This will only work if
5380// each of the elements of the substruct are known (ie, inserted into From by an
5381// insertvalue instruction somewhere).
5382//
5383// All inserted insertvalue instructions are inserted before InsertBefore
5385 BasicBlock::iterator InsertBefore) {
5386 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
5387 idx_range);
5388 Value *To = PoisonValue::get(IndexedType);
5389 SmallVector<unsigned, 10> Idxs(idx_range);
5390 unsigned IdxSkip = Idxs.size();
5391
5392 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
5393}
5394
5395/// Given an aggregate and a sequence of indices, see if the scalar value
5396/// indexed is already around as a register, for example if it was inserted
5397/// directly into the aggregate.
5398///
5399/// If InsertBefore is not null, this function will duplicate (modified)
5400/// insertvalues when a part of a nested struct is extracted.
5401Value *
5403 std::optional<BasicBlock::iterator> InsertBefore) {
5404 // Nothing to index? Just return V then (this is useful at the end of our
5405 // recursion).
5406 if (idx_range.empty())
5407 return V;
5408 // We have indices, so V should have an indexable type.
5409 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
5410 "Not looking at a struct or array?");
5411 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
5412 "Invalid indices for type?");
5413
5414 if (Constant *C = dyn_cast<Constant>(V)) {
5415 C = C->getAggregateElement(idx_range[0]);
5416 if (!C) return nullptr;
5417 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
5418 }
5419
5421 // Loop the indices for the insertvalue instruction in parallel with the
5422 // requested indices
5423 const unsigned *req_idx = idx_range.begin();
5424 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
5425 i != e; ++i, ++req_idx) {
5426 if (req_idx == idx_range.end()) {
5427 // We can't handle this without inserting insertvalues
5428 if (!InsertBefore)
5429 return nullptr;
5430
5431 // The requested index identifies a part of a nested aggregate. Handle
5432 // this specially. For example,
5433 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
5434 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
5435 // %C = extractvalue {i32, { i32, i32 } } %B, 1
5436 // This can be changed into
5437 // %A = insertvalue {i32, i32 } undef, i32 10, 0
5438 // %C = insertvalue {i32, i32 } %A, i32 11, 1
5439 // which allows the unused 0,0 element from the nested struct to be
5440 // removed.
5441 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
5442 *InsertBefore);
5443 }
5444
5445 // This insert value inserts something else than what we are looking for.
5446 // See if the (aggregate) value inserted into has the value we are
5447 // looking for, then.
5448 if (*req_idx != *i)
5449 return FindInsertedValue(I->getAggregateOperand(), idx_range,
5450 InsertBefore);
5451 }
5452 // If we end up here, the indices of the insertvalue match with those
5453 // requested (though possibly only partially). Now we recursively look at
5454 // the inserted value, passing any remaining indices.
5455 return FindInsertedValue(I->getInsertedValueOperand(),
5456 ArrayRef(req_idx, idx_range.end()), InsertBefore);
5457 }
5458
5460 // If we're extracting a value from an aggregate that was extracted from
5461 // something else, we can extract from that something else directly instead.
5462 // However, we will need to chain I's indices with the requested indices.
5463
5464 // Calculate the number of indices required
5465 unsigned size = I->getNumIndices() + idx_range.size();
5466 // Allocate some space to put the new indices in
5468 Idxs.reserve(size);
5469 // Add indices from the extract value instruction
5470 Idxs.append(I->idx_begin(), I->idx_end());
5471
5472 // Add requested indices
5473 Idxs.append(idx_range.begin(), idx_range.end());
5474
5475 assert(Idxs.size() == size
5476 && "Number of indices added not correct?");
5477
5478 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
5479 }
5480 // Otherwise, we don't know (such as, extracting from a function return value
5481 // or load instruction)
5482 return nullptr;
5483}
5484
5485// If V refers to an initialized global constant, set Slice either to
5486// its initializer if the size of its elements equals ElementSize, or,
5487// for ElementSize == 8, to its representation as an array of unsiged
5488// char. Return true on success.
5489// Offset is in the unit "nr of ElementSize sized elements".
5492 unsigned ElementSize, uint64_t Offset) {
5493 assert(V && "V should not be null.");
5494 assert((ElementSize % 8) == 0 &&
5495 "ElementSize expected to be a multiple of the size of a byte.");
5496 unsigned ElementSizeInBytes = ElementSize / 8;
5497
5498 // Drill down into the pointer expression V, ignoring any intervening
5499 // casts, and determine the identity of the object it references along
5500 // with the cumulative byte offset into it.
5501 const GlobalVariable *GV =
5503 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
5504 // Fail if V is not based on constant global object.
5505 return false;
5506
5507 const DataLayout &DL = GV->getDataLayout();
5508 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
5509
5511 /*AllowNonInbounds*/ true))
5512 // Fail if a constant offset could not be determined.
5513 return false;
5514
5515 uint64_t StartIdx = Off.getLimitedValue();
5516 if (StartIdx == UINT64_MAX)
5517 // Fail if the constant offset is excessive.
5518 return false;
5519
5520 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
5521 // elements. Simply bail out if that isn't possible.
5522 if ((StartIdx % ElementSizeInBytes) != 0)
5523 return false;
5524
5525 Offset += StartIdx / ElementSizeInBytes;
5526 ConstantDataArray *Array = nullptr;
5527 ArrayType *ArrayTy = nullptr;
5528
5529 if (GV->getInitializer()->isNullValue()) {
5530 Type *GVTy = GV->getValueType();
5531 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
5532 uint64_t Length = SizeInBytes / ElementSizeInBytes;
5533
5534 Slice.Array = nullptr;
5535 Slice.Offset = 0;
5536 // Return an empty Slice for undersized constants to let callers
5537 // transform even undefined library calls into simpler, well-defined
5538 // expressions. This is preferable to making the calls although it
5539 // prevents sanitizers from detecting such calls.
5540 Slice.Length = Length < Offset ? 0 : Length - Offset;
5541 return true;
5542 }
5543
5544 auto *Init = const_cast<Constant *>(GV->getInitializer());
5545 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
5546 Type *InitElTy = ArrayInit->getElementType();
5547 if (InitElTy->isIntegerTy(ElementSize)) {
5548 // If Init is an initializer for an array of the expected type
5549 // and size, use it as is.
5550 Array = ArrayInit;
5551 ArrayTy = ArrayInit->getType();
5552 }
5553 }
5554
5555 if (!Array) {
5556 if (ElementSize != 8)
5557 // TODO: Handle conversions to larger integral types.
5558 return false;
5559
5560 // Otherwise extract the portion of the initializer starting
5561 // at Offset as an array of bytes, and reset Offset.
5563 if (!Init)
5564 return false;
5565
5566 Offset = 0;
5568 ArrayTy = dyn_cast<ArrayType>(Init->getType());
5569 }
5570
5571 uint64_t NumElts = ArrayTy->getArrayNumElements();
5572 if (Offset > NumElts)
5573 return false;
5574
5575 Slice.Array = Array;
5576 Slice.Offset = Offset;
5577 Slice.Length = NumElts - Offset;
5578 return true;
5579}
5580
5581/// Extract bytes from the initializer of the constant array V, which need
5582/// not be a nul-terminated string. On success, store the bytes in Str and
5583/// return true. When TrimAtNul is set, Str will contain only the bytes up
5584/// to but not including the first nul. Return false on failure.
5586 bool TrimAtNul) {
5588 if (!getConstantDataArrayInfo(V, Slice, 8))
5589 return false;
5590
5591 if (Slice.Array == nullptr) {
5592 if (TrimAtNul) {
5593 // Return a nul-terminated string even for an empty Slice. This is
5594 // safe because all existing SimplifyLibcalls callers require string
5595 // arguments and the behavior of the functions they fold is undefined
5596 // otherwise. Folding the calls this way is preferable to making
5597 // the undefined library calls, even though it prevents sanitizers
5598 // from reporting such calls.
5599 Str = StringRef();
5600 return true;
5601 }
5602 if (Slice.Length == 1) {
5603 Str = StringRef("", 1);
5604 return true;
5605 }
5606 // We cannot instantiate a StringRef as we do not have an appropriate string
5607 // of 0s at hand.
5608 return false;
5609 }
5610
5611 // Start out with the entire array in the StringRef.
5612 Str = Slice.Array->getAsString();
5613 // Skip over 'offset' bytes.
5614 Str = Str.substr(Slice.Offset);
5615
5616 if (TrimAtNul) {
5617 // Trim off the \0 and anything after it. If the array is not nul
5618 // terminated, we just return the whole end of string. The client may know
5619 // some other way that the string is length-bound.
5620 Str = Str.substr(0, Str.find('\0'));
5621 }
5622 return true;
5623}
5624
5625// These next two are very similar to the above, but also look through PHI
5626// nodes.
5627// TODO: See if we can integrate these two together.
5628
5629/// If we can compute the length of the string pointed to by
5630/// the specified pointer, return 'len+1'. If we can't, return 0.
5633 unsigned CharSize) {
5634 // Look through noop bitcast instructions.
5635 V = V->stripPointerCasts();
5636
5637 // If this is a PHI node, there are two cases: either we have already seen it
5638 // or we haven't.
5639 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
5640 if (!PHIs.insert(PN).second)
5641 return ~0ULL; // already in the set.
5642
5643 // If it was new, see if all the input strings are the same length.
5644 uint64_t LenSoFar = ~0ULL;
5645 for (Value *IncValue : PN->incoming_values()) {
5646 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
5647 if (Len == 0) return 0; // Unknown length -> unknown.
5648
5649 if (Len == ~0ULL) continue;
5650
5651 if (Len != LenSoFar && LenSoFar != ~0ULL)
5652 return 0; // Disagree -> unknown.
5653 LenSoFar = Len;
5654 }
5655
5656 // Success, all agree.
5657 return LenSoFar;
5658 }
5659
5660 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
5661 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
5662 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
5663 if (Len1 == 0) return 0;
5664 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
5665 if (Len2 == 0) return 0;
5666 if (Len1 == ~0ULL) return Len2;
5667 if (Len2 == ~0ULL) return Len1;
5668 if (Len1 != Len2) return 0;
5669 return Len1;
5670 }
5671
5672 // Otherwise, see if we can read the string.
5674 if (!getConstantDataArrayInfo(V, Slice, CharSize))
5675 return 0;
5676
5677 if (Slice.Array == nullptr)
5678 // Zeroinitializer (including an empty one).
5679 return 1;
5680
5681 // Search for the first nul character. Return a conservative result even
5682 // when there is no nul. This is safe since otherwise the string function
5683 // being folded such as strlen is undefined, and can be preferable to
5684 // making the undefined library call.
5685 unsigned NullIndex = 0;
5686 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
5687 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
5688 break;
5689 }
5690
5691 return NullIndex + 1;
5692}
5693
5694/// If we can compute the length of the string pointed to by
5695/// the specified pointer, return 'len+1'. If we can't, return 0.
5696uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
5697 if (!V->getType()->isPointerTy())
5698 return 0;
5699
5701 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
5702 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
5703 // an empty string as a length.
5704 return Len == ~0ULL ? 1 : Len;
5705}
5706
5707const Value *
5709 bool MustPreserveOffset,
5710 bool MustPreserveProvenance) {
5711 assert(Call &&
5712 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
5713 if (const Value *RV = Call->getReturnedArgOperand())
5714 return RV;
5715 // This can be used only as a aliasing property.
5717 Call, MustPreserveOffset, MustPreserveProvenance))
5718 return Call->getArgOperand(0);
5719 return nullptr;
5720}
5721
5723 const CallBase *Call, bool MustPreserveOffset,
5724 bool MustPreserveProvenance) {
5725 switch (Call->getIntrinsicID()) {
5726 case Intrinsic::launder_invariant_group:
5727 case Intrinsic::aarch64_irg:
5728 case Intrinsic::aarch64_tagp:
5729 // The amdgcn_make_buffer_rsrc function does not alter the address of the
5730 // input pointer (and thus preserves the byte offset, which is the property
5731 // the MustPreserveOffset flag selects). However, it will not necessarily
5732 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
5733 // descriptor", which has "all loads return 0, all stores are dropped"
5734 // semantics. Given the context of this intrinsic list, no one should be
5735 // relying on such a strict bit-exact null mapping (and, at time of
5736 // writing, they are not), but we document this fact out of an abundance
5737 // of caution.
5738 case Intrinsic::amdgcn_make_buffer_rsrc:
5739 return !MustPreserveProvenance;
5740 case Intrinsic::ptrmask:
5741 return !MustPreserveOffset;
5742 case Intrinsic::threadlocal_address:
5743 // The underlying variable changes with thread ID. The Thread ID may change
5744 // at coroutine suspend points.
5745 return !Call->getParent()->getParent()->isPresplitCoroutine();
5746 default:
5747 return false;
5748 }
5749}
5750
5751/// \p PN defines a loop-variant pointer to an object. Check if the
5752/// previous iteration of the loop was referring to the same object as \p PN.
5754 const LoopInfo *LI) {
5755 // Find the loop-defined value.
5756 Loop *L = LI->getLoopFor(PN->getParent());
5757 if (PN->getNumIncomingValues() != 2)
5758 return true;
5759
5760 // Find the value from previous iteration.
5761 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
5762 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
5763 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
5764 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
5765 return true;
5766
5767 // If a new pointer is loaded in the loop, the pointer references a different
5768 // object in every iteration. E.g.:
5769 // for (i)
5770 // int *p = a[i];
5771 // ...
5772 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
5773 if (!L->isLoopInvariant(Load->getPointerOperand()))
5774 return false;
5775 return true;
5776}
5777
5778const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
5779 bool MustPreserveProvenance) {
5780 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
5781 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
5782 const Value *PtrOp = GEP->getPointerOperand();
5783 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
5784 return V;
5785 V = PtrOp;
5786 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
5787 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
5788 Value *NewV = cast<Operator>(V)->getOperand(0);
5789 if (!NewV->getType()->isPointerTy())
5790 return V;
5791 V = NewV;
5792 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
5793 if (GA->isInterposable())
5794 return V;
5795 V = GA->getAliasee();
5796 } else {
5797 if (auto *PHI = dyn_cast<PHINode>(V)) {
5798 // Look through single-arg phi nodes created by LCSSA.
5799 if (PHI->getNumIncomingValues() == 1) {
5800 V = PHI->getIncomingValue(0);
5801 continue;
5802 }
5803 } else if (auto *Call = dyn_cast<CallBase>(V)) {
5804 // CaptureTracking can know about special capturing properties of some
5805 // intrinsics like launder.invariant.group, that can't be expressed with
5806 // the attributes, but have properties like returning aliasing pointer.
5807 // Because some analysis may assume that nocaptured pointer is not
5808 // returned from some special intrinsic (because function would have to
5809 // be marked with returns attribute), it is crucial to use this function
5810 // because it should be in sync with CaptureTracking. Not using it may
5811 // cause weird miscompilations where 2 aliasing pointers are assumed to
5812 // noalias.
5814 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
5815 V = RP;
5816 continue;
5817 }
5818 }
5819
5820 return V;
5821 }
5822 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
5823 }
5824 return V;
5825}
5826
5829 const LoopInfo *LI, unsigned MaxLookup) {
5832 Worklist.push_back(V);
5833 do {
5834 const Value *P = Worklist.pop_back_val();
5835 P = getUnderlyingObject(P, MaxLookup);
5836
5837 if (!Visited.insert(P).second)
5838 continue;
5839
5840 if (auto *SI = dyn_cast<SelectInst>(P)) {
5841 Worklist.push_back(SI->getTrueValue());
5842 Worklist.push_back(SI->getFalseValue());
5843 continue;
5844 }
5845
5846 if (auto *PN = dyn_cast<PHINode>(P)) {
5847 // If this PHI changes the underlying object in every iteration of the
5848 // loop, don't look through it. Consider:
5849 // int **A;
5850 // for (i) {
5851 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
5852 // Curr = A[i];
5853 // *Prev, *Curr;
5854 //
5855 // Prev is tracking Curr one iteration behind so they refer to different
5856 // underlying objects.
5857 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
5859 append_range(Worklist, PN->incoming_values());
5860 else
5861 Objects.push_back(P);
5862 continue;
5863 }
5864
5865 Objects.push_back(P);
5866 } while (!Worklist.empty());
5867}
5868
5870 bool MustPreserveProvenance) {
5871 const unsigned MaxVisited = 8;
5872
5875 Worklist.push_back(V);
5876 const Value *Object = nullptr;
5877 // Used as fallback if we can't find a common underlying object through
5878 // recursion.
5879 bool First = true;
5880 const Value *FirstObject =
5881 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
5882 do {
5883 const Value *P = Worklist.pop_back_val();
5884 P = First ? FirstObject
5886 MustPreserveProvenance);
5887 First = false;
5888
5889 if (!Visited.insert(P).second)
5890 continue;
5891
5892 if (Visited.size() == MaxVisited)
5893 return FirstObject;
5894
5895 if (auto *SI = dyn_cast<SelectInst>(P)) {
5896 Worklist.push_back(SI->getTrueValue());
5897 Worklist.push_back(SI->getFalseValue());
5898 continue;
5899 }
5900
5901 if (auto *PN = dyn_cast<PHINode>(P)) {
5902 append_range(Worklist, PN->incoming_values());
5903 continue;
5904 }
5905
5906 if (!Object)
5907 Object = P;
5908 else if (Object != P)
5909 return FirstObject;
5910 } while (!Worklist.empty());
5911
5912 return Object ? Object : FirstObject;
5913}
5914
5915/// This is the function that does the work of looking through basic
5916/// ptrtoint+arithmetic+inttoptr sequences.
5918 do {
5919 if (const Operator *U = dyn_cast<Operator>(V)) {
5920 // If we find a ptrtoint, we can transfer control back to the
5921 // regular getUnderlyingObjectFromInt.
5922 if (U->getOpcode() == Instruction::PtrToInt)
5923 return U->getOperand(0);
5924 // If we find an add of a constant, a multiplied value, or a phi, it's
5925 // likely that the other operand will lead us to the base
5926 // object. We don't have to worry about the case where the
5927 // object address is somehow being computed by the multiply,
5928 // because our callers only care when the result is an
5929 // identifiable object.
5930 if (U->getOpcode() != Instruction::Add ||
5931 (!isa<ConstantInt>(U->getOperand(1)) &&
5932 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
5933 !isa<PHINode>(U->getOperand(1))))
5934 return V;
5935 V = U->getOperand(0);
5936 } else {
5937 return V;
5938 }
5939 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
5940 } while (true);
5941}
5942
5943/// This is a wrapper around getUnderlyingObjects and adds support for basic
5944/// ptrtoint+arithmetic+inttoptr sequences.
5945/// It returns false if unidentified object is found in getUnderlyingObjects.
5947 SmallVectorImpl<Value *> &Objects) {
5949 SmallVector<const Value *, 4> Working(1, V);
5950 bool AllObjectsIdentified = true;
5951 do {
5952 V = Working.pop_back_val();
5953
5955 getUnderlyingObjects(V, Objs);
5956
5957 for (const Value *V : Objs) {
5958 if (!Visited.insert(V).second)
5959 continue;
5960 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
5961 const Value *O =
5962 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
5963 if (O->getType()->isPointerTy()) {
5964 Working.push_back(O);
5965 continue;
5966 }
5967 }
5968 AllObjectsIdentified &= isIdentifiedObject(V);
5969 Objects.push_back(const_cast<Value *>(V));
5970 }
5971 } while (!Working.empty());
5972 return AllObjectsIdentified;
5973}
5974
5976 AllocaInst *Result = nullptr;
5978 SmallVector<Value *, 4> Worklist;
5979
5980 auto AddWork = [&](Value *V) {
5981 if (Visited.insert(V).second)
5982 Worklist.push_back(V);
5983 };
5984
5985 AddWork(V);
5986 do {
5987 V = Worklist.pop_back_val();
5988 assert(Visited.count(V));
5989
5990 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
5991 if (Result && Result != AI)
5992 return nullptr;
5993 Result = AI;
5994 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
5995 AddWork(CI->getOperand(0));
5996 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
5997 for (Value *IncValue : PN->incoming_values())
5998 AddWork(IncValue);
5999 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
6000 AddWork(SI->getTrueValue());
6001 AddWork(SI->getFalseValue());
6003 if (OffsetZero && !GEP->hasAllZeroIndices())
6004 return nullptr;
6005 AddWork(GEP->getPointerOperand());
6006 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
6007 Value *Returned = CB->getReturnedArgOperand();
6008 if (Returned)
6009 AddWork(Returned);
6010 else
6011 return nullptr;
6012 } else {
6013 return nullptr;
6014 }
6015 } while (!Worklist.empty());
6016
6017 return Result;
6018}
6019
6021 if (auto *II = dyn_cast<IntrinsicInst>(I))
6022 return isTriviallyVectorizable(II->getIntrinsicID());
6023 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
6024 return (!Shuffle || Shuffle->isSelect()) &&
6026}
6027
6029 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
6030 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
6031 bool IgnoreUBImplyingAttrs) {
6032 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
6033 AC, DT, TLI, UseVariableInfo,
6034 IgnoreUBImplyingAttrs);
6035}
6036
6038 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
6039 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
6040 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
6041#ifndef NDEBUG
6042 if (Inst->getOpcode() != Opcode) {
6043 // Check that the operands are actually compatible with the Opcode override.
6044 auto hasEqualReturnAndLeadingOperandTypes =
6045 [](const Instruction *Inst, unsigned NumLeadingOperands) {
6046 if (Inst->getNumOperands() < NumLeadingOperands)
6047 return false;
6048 const Type *ExpectedType = Inst->getType();
6049 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
6050 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
6051 return false;
6052 return true;
6053 };
6055 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
6056 assert(!Instruction::isUnaryOp(Opcode) ||
6057 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
6058 }
6059#endif
6060
6061 switch (Opcode) {
6062 default:
6063 return true;
6064 case Instruction::UDiv:
6065 case Instruction::URem: {
6066 // x / y is undefined if y == 0.
6067 const APInt *V;
6068 if (match(Inst->getOperand(1), m_APInt(V)))
6069 return *V != 0;
6070 return false;
6071 }
6072 case Instruction::SDiv:
6073 case Instruction::SRem: {
6074 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
6075 const APInt *Numerator, *Denominator;
6076 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
6077 return false;
6078 // We cannot hoist this division if the denominator is 0.
6079 if (*Denominator == 0)
6080 return false;
6081 // It's safe to hoist if the denominator is not 0 or -1.
6082 if (!Denominator->isAllOnes())
6083 return true;
6084 // At this point we know that the denominator is -1. It is safe to hoist as
6085 // long we know that the numerator is not INT_MIN.
6086 if (match(Inst->getOperand(0), m_APInt(Numerator)))
6087 return !Numerator->isMinSignedValue();
6088 // The numerator *might* be MinSignedValue.
6089 return false;
6090 }
6091 case Instruction::Load: {
6092 if (!UseVariableInfo)
6093 return false;
6094
6095 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
6096 if (!LI)
6097 return false;
6098 if (mustSuppressSpeculation(*LI))
6099 return false;
6100 const DataLayout &DL = LI->getDataLayout();
6102 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
6103 SimplifyQuery(DL, TLI, DT, AC, CtxI));
6104 }
6105 case Instruction::Call: {
6106 auto *CI = dyn_cast<const CallInst>(Inst);
6107 if (!CI)
6108 return false;
6109 const Function *Callee = CI->getCalledFunction();
6110
6111 // The called function could have undefined behavior or side-effects, even
6112 // if marked readnone nounwind.
6113 if (!Callee || !Callee->isSpeculatable())
6114 return false;
6115 // Since the operands may be changed after hoisting, undefined behavior may
6116 // be triggered by some UB-implying attributes.
6117 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
6118 }
6119 case Instruction::VAArg:
6120 case Instruction::Alloca:
6121 case Instruction::Invoke:
6122 case Instruction::CallBr:
6123 case Instruction::PHI:
6124 case Instruction::Store:
6125 case Instruction::Ret:
6126 case Instruction::UncondBr:
6127 case Instruction::CondBr:
6128 case Instruction::IndirectBr:
6129 case Instruction::Switch:
6130 case Instruction::Unreachable:
6131 case Instruction::Fence:
6132 case Instruction::AtomicRMW:
6133 case Instruction::AtomicCmpXchg:
6134 case Instruction::LandingPad:
6135 case Instruction::Resume:
6136 case Instruction::CatchSwitch:
6137 case Instruction::CatchPad:
6138 case Instruction::CatchRet:
6139 case Instruction::CleanupPad:
6140 case Instruction::CleanupRet:
6141 return false; // Misc instructions which have effects
6142 }
6143}
6144
6146 if (I.mayReadOrWriteMemory())
6147 // Memory dependency possible
6148 return true;
6150 // Can't move above a maythrow call or infinite loop. Or if an
6151 // inalloca alloca, above a stacksave call.
6152 return true;
6154 // 1) Can't reorder two inf-loop calls, even if readonly
6155 // 2) Also can't reorder an inf-loop call below a instruction which isn't
6156 // safe to speculative execute. (Inverse of above)
6157 return true;
6158 return false;
6159}
6160
6161/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
6175
6176/// Combine constant ranges from computeConstantRange() and computeKnownBits().
6179 bool ForSigned,
6180 const SimplifyQuery &SQ) {
6181 ConstantRange CR1 =
6182 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
6183 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
6186 return CR1.intersectWith(CR2, RangeType);
6187}
6188
6190 const Value *RHS,
6191 const SimplifyQuery &SQ,
6192 bool IsNSW) {
6193 ConstantRange LHSRange =
6194 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
6195 ConstantRange RHSRange =
6196 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
6197
6198 // mul nsw of two non-negative numbers is also nuw.
6199 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
6201
6202 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
6203}
6204
6206 const Value *RHS,
6207 const SimplifyQuery &SQ) {
6208 // Multiplying n * m significant bits yields a result of n + m significant
6209 // bits. If the total number of significant bits does not exceed the
6210 // result bit width (minus 1), there is no overflow.
6211 // This means if we have enough leading sign bits in the operands
6212 // we can guarantee that the result does not overflow.
6213 // Ref: "Hacker's Delight" by Henry Warren
6214 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
6215
6216 // Note that underestimating the number of sign bits gives a more
6217 // conservative answer.
6218 unsigned SignBits = computeNumSignBits(LHS, SQ) + computeNumSignBits(RHS, SQ);
6219
6220 // First handle the easy case: if we have enough sign bits there's
6221 // definitely no overflow.
6222 if (SignBits > BitWidth + 1)
6224
6225 // There are two ambiguous cases where there can be no overflow:
6226 // SignBits == BitWidth + 1 and
6227 // SignBits == BitWidth
6228 // The second case is difficult to check, therefore we only handle the
6229 // first case.
6230 if (SignBits == BitWidth + 1) {
6231 // It overflows only when both arguments are negative and the true
6232 // product is exactly the minimum negative number.
6233 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
6234 // For simplicity we just check if at least one side is not negative.
6235 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
6236 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
6237 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
6239 }
6241}
6242
6245 const WithCache<const Value *> &RHS,
6246 const SimplifyQuery &SQ) {
6247 ConstantRange LHSRange =
6248 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
6249 ConstantRange RHSRange =
6250 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
6251 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
6252}
6253
6254static OverflowResult
6257 const AddOperator *Add, const SimplifyQuery &SQ) {
6258 if (Add && Add->hasNoSignedWrap()) {
6260 }
6261
6262 // If LHS and RHS each have at least two sign bits, the addition will look
6263 // like
6264 //
6265 // XX..... +
6266 // YY.....
6267 //
6268 // If the carry into the most significant position is 0, X and Y can't both
6269 // be 1 and therefore the carry out of the addition is also 0.
6270 //
6271 // If the carry into the most significant position is 1, X and Y can't both
6272 // be 0 and therefore the carry out of the addition is also 1.
6273 //
6274 // Since the carry into the most significant position is always equal to
6275 // the carry out of the addition, there is no signed overflow.
6276 if (computeNumSignBits(LHS, SQ) > 1 && computeNumSignBits(RHS, SQ) > 1)
6278
6279 ConstantRange LHSRange =
6280 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
6281 ConstantRange RHSRange =
6282 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
6283 OverflowResult OR =
6284 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
6286 return OR;
6287
6288 // The remaining code needs Add to be available. Early returns if not so.
6289 if (!Add)
6291
6292 // If the sign of Add is the same as at least one of the operands, this add
6293 // CANNOT overflow. If this can be determined from the known bits of the
6294 // operands the above signedAddMayOverflow() check will have already done so.
6295 // The only other way to improve on the known bits is from an assumption, so
6296 // call computeKnownBitsFromContext() directly.
6297 bool LHSOrRHSKnownNonNegative =
6298 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
6299 bool LHSOrRHSKnownNegative =
6300 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
6301 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
6302 KnownBits AddKnown(LHSRange.getBitWidth());
6303 computeKnownBitsFromContext(Add, AddKnown, SQ);
6304 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
6305 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
6307 }
6308
6310}
6311
6313 const Value *RHS,
6314 const SimplifyQuery &SQ) {
6315 // X - (X % ?)
6316 // The remainder of a value can't have greater magnitude than itself,
6317 // so the subtraction can't overflow.
6318
6319 // X - (X -nuw ?)
6320 // In the minimal case, this would simplify to "?", so there's no subtract
6321 // at all. But if this analysis is used to peek through casts, for example,
6322 // then determining no-overflow may allow other transforms.
6323
6324 // TODO: There are other patterns like this.
6325 // See simplifyICmpWithBinOpOnLHS() for candidates.
6326 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
6327 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
6328 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
6330
6331 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
6332 SQ.DL)) {
6333 if (*C)
6336 }
6337
6338 ConstantRange LHSRange =
6339 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
6340 ConstantRange RHSRange =
6341 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
6342 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
6343}
6344
6346 const Value *RHS,
6347 const SimplifyQuery &SQ) {
6348 // X - (X % ?)
6349 // The remainder of a value can't have greater magnitude than itself,
6350 // so the subtraction can't overflow.
6351
6352 // X - (X -nsw ?)
6353 // In the minimal case, this would simplify to "?", so there's no subtract
6354 // at all. But if this analysis is used to peek through casts, for example,
6355 // then determining no-overflow may allow other transforms.
6356 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
6357 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
6358 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
6360
6361 // If LHS and RHS each have at least two sign bits, the subtraction
6362 // cannot overflow.
6363 if (computeNumSignBits(LHS, SQ) > 1 && computeNumSignBits(RHS, SQ) > 1)
6365
6366 ConstantRange LHSRange =
6367 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
6368 ConstantRange RHSRange =
6369 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
6370 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
6371}
6372
6374 const DominatorTree &DT) {
6375 SmallVector<const CondBrInst *, 2> GuardingBranches;
6377
6378 for (const User *U : WO->users()) {
6379 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
6380 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
6381
6382 if (EVI->getIndices()[0] == 0)
6383 Results.push_back(EVI);
6384 else {
6385 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
6386
6387 for (const auto *U : EVI->users())
6388 if (const auto *B = dyn_cast<CondBrInst>(U))
6389 GuardingBranches.push_back(B);
6390 }
6391 } else {
6392 // We are using the aggregate directly in a way we don't want to analyze
6393 // here (storing it to a global, say).
6394 return false;
6395 }
6396 }
6397
6398 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
6399 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
6400
6401 // Check if all users of the add are provably no-wrap.
6402 for (const auto *Result : Results) {
6403 // If the extractvalue itself is not executed on overflow, the we don't
6404 // need to check each use separately, since domination is transitive.
6405 if (DT.dominates(NoWrapEdge, Result->getParent()))
6406 continue;
6407
6408 for (const auto &RU : Result->uses())
6409 if (!DT.dominates(NoWrapEdge, RU))
6410 return false;
6411 }
6412
6413 return true;
6414 };
6415
6416 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
6417}
6418
6419/// Shifts return poison if shiftwidth is larger than the bitwidth.
6420static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
6421 auto *C = dyn_cast<Constant>(ShiftAmount);
6422 if (!C)
6423 return false;
6424
6425 // Shifts return poison if shiftwidth is larger than the bitwidth.
6427 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
6428 unsigned NumElts = FVTy->getNumElements();
6429 for (unsigned i = 0; i < NumElts; ++i)
6430 ShiftAmounts.push_back(C->getAggregateElement(i));
6431 } else if (isa<ScalableVectorType>(C->getType()))
6432 return false; // Can't tell, just return false to be safe
6433 else
6434 ShiftAmounts.push_back(C);
6435
6436 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
6437 auto *CI = dyn_cast_or_null<ConstantInt>(C);
6438 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
6439 });
6440
6441 return Safe;
6442}
6443
6445 bool ConsiderFlagsAndMetadata) {
6446 const auto *CB = dyn_cast<CallBase>(Op);
6447 bool CBHasNoUndef = CB && CB->hasRetAttr(Attribute::NoUndef);
6448 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
6449 Op->hasPoisonGeneratingAnnotations() && !CBHasNoUndef)
6450 return true;
6451
6452 unsigned Opcode = Op->getOpcode();
6453
6454 // Check whether opcode is a poison/undef-generating operation
6455 switch (Opcode) {
6456 case Instruction::Shl:
6457 case Instruction::AShr:
6458 case Instruction::LShr:
6459 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
6460 case Instruction::FPToSI:
6461 case Instruction::FPToUI:
6462 // fptosi/ui yields poison if the resulting value does not fit in the
6463 // destination type.
6464 return true;
6465 case Instruction::Call:
6466 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
6467 switch (II->getIntrinsicID()) {
6468 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
6469 case Intrinsic::ctlz:
6470 case Intrinsic::cttz:
6471 case Intrinsic::abs:
6472 // We're not considering flags so it is safe to just return false.
6473 return false;
6474 case Intrinsic::sshl_sat:
6475 case Intrinsic::ushl_sat:
6476 if (!includesPoison(Kind) ||
6477 shiftAmountKnownInRange(II->getArgOperand(1)))
6478 return false;
6479 break;
6480 }
6481 }
6482 [[fallthrough]];
6483 case Instruction::CallBr:
6484 case Instruction::Invoke: {
6485 return !CBHasNoUndef && !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
6486 }
6487 case Instruction::InsertElement:
6488 case Instruction::ExtractElement: {
6489 // If index exceeds the length of the vector, it returns poison
6490 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
6491 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
6492 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
6493 if (includesPoison(Kind))
6494 return !Idx ||
6495 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
6496 return false;
6497 }
6498 case Instruction::ShuffleVector: {
6500 ? cast<ConstantExpr>(Op)->getShuffleMask()
6501 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
6502 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
6503 }
6504 case Instruction::FNeg:
6505 case Instruction::PHI:
6506 case Instruction::Select:
6507 case Instruction::ExtractValue:
6508 case Instruction::InsertValue:
6509 case Instruction::Freeze:
6510 case Instruction::ICmp:
6511 case Instruction::FCmp:
6512 case Instruction::GetElementPtr:
6513 return false;
6514 case Instruction::AddrSpaceCast:
6515 return true;
6516 default: {
6517 const auto *CE = dyn_cast<ConstantExpr>(Op);
6518 if (isa<CastInst>(Op) || (CE && CE->isCast()))
6519 return false;
6520 else if (Instruction::isBinaryOp(Opcode))
6521 return false;
6522 // Be conservative and return true.
6523 return true;
6524 }
6525 }
6526}
6527
6529 bool ConsiderFlagsAndMetadata) {
6530 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
6531 ConsiderFlagsAndMetadata);
6532}
6533
6534bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
6535 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
6536 ConsiderFlagsAndMetadata);
6537}
6538
6539static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
6540 unsigned Depth) {
6541 if (ValAssumedPoison == V)
6542 return true;
6543
6544 const unsigned MaxDepth = 2;
6545 if (Depth >= MaxDepth)
6546 return false;
6547
6548 if (const auto *I = dyn_cast<Instruction>(V)) {
6549 if (any_of(I->operands(), [=](const Use &Op) {
6550 return propagatesPoison(Op) &&
6551 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
6552 }))
6553 return true;
6554
6555 // V = extractvalue V0, idx
6556 // V2 = extractvalue V0, idx2
6557 // V0's elements are all poison or not. (e.g., add_with_overflow)
6558 const WithOverflowInst *II;
6560 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
6561 llvm::is_contained(II->args(), ValAssumedPoison)))
6562 return true;
6563 }
6564 return false;
6565}
6566
6567static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
6568 unsigned Depth) {
6569 if (isGuaranteedNotToBePoison(ValAssumedPoison))
6570 return true;
6571
6572 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
6573 return true;
6574
6575 const unsigned MaxDepth = 2;
6576 if (Depth >= MaxDepth)
6577 return false;
6578
6579 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
6580 if (I && !canCreatePoison(cast<Operator>(I))) {
6581 return all_of(I->operands(), [=](const Value *Op) {
6582 return impliesPoison(Op, V, Depth + 1);
6583 });
6584 }
6585 return false;
6586}
6587
6588bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
6589 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
6590}
6591
6592static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
6593
6595 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
6596 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
6598 return false;
6599
6601 return false;
6602
6603 if (const auto *A = dyn_cast<Argument>(V)) {
6604 if (A->hasAttribute(Attribute::NoUndef) ||
6605 A->hasAttribute(Attribute::Dereferenceable) ||
6606 A->hasAttribute(Attribute::DereferenceableOrNull))
6607 return true;
6608 }
6609
6610 if (auto *C = dyn_cast<Constant>(V)) {
6611 if (isa<PoisonValue>(C))
6612 return !includesPoison(Kind);
6613
6614 if (isa<UndefValue>(C))
6615 return !includesUndef(Kind);
6616
6619 return true;
6620
6621 // Limit constexpr GEPs to just two operands for simplicity, since when the
6622 // GEP has a inbounds/nuw flags we need to ensure that every addition to the
6623 // underlying object will stay inbound and not wrap.
6624 const Value *BaseObj;
6625 const APInt *BaseOff;
6626 if (C && CtxI &&
6627 match(C, m_PtrAdd(CtxI->getDataLayout(), m_Value(BaseObj),
6628 m_APInt(BaseOff)))) {
6629 const GlobalVariable *GV = dyn_cast<GlobalVariable>(BaseObj);
6630 // Exclude global variables with absolute symbol refs or external weak
6631 // linkage because these could be null.
6632 if (GV && !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
6633 BaseOff->sge(0) &&
6634 BaseOff->slt(GV->getGlobalSize(CtxI->getDataLayout()))) {
6635 return true;
6636 }
6637 }
6638
6639 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
6640 if (isa<ConstantExpr>(C)) {
6641 // Scalable vectors can use a ConstantExpr to build a splat.
6642 if (Constant *SplatC = C->getSplatValue())
6643 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
6644 return true;
6645 } else if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
6646 return all_of(CA->operands(), [&](const Use &Op) {
6647 return isGuaranteedNotToBeUndefOrPoison(Op.get(), AC, CtxI, DT,
6648 Depth + 1, Kind);
6649 });
6650 }
6651 }
6652 }
6653
6654 // Strip cast operations from a pointer value.
6655 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
6656 // inbounds with zero offset. To guarantee that the result isn't poison, the
6657 // stripped pointer is checked as it has to be pointing into an allocated
6658 // object or be null `null` to ensure `inbounds` getelement pointers with a
6659 // zero offset could not produce poison.
6660 // It can strip off addrspacecast that do not change bit representation as
6661 // well. We believe that such addrspacecast is equivalent to no-op.
6662 auto *StrippedV = V->stripPointerCastsSameRepresentation();
6663 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
6664 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
6665 return true;
6666
6667 auto OpCheck = [&](const Value *V) {
6668 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
6669 };
6670
6671 if (auto *Opr = dyn_cast<Operator>(V)) {
6672 // If the value is a freeze instruction, then it can never
6673 // be undef or poison.
6674 if (isa<FreezeInst>(V))
6675 return true;
6676
6677 if (const auto *CB = dyn_cast<CallBase>(V)) {
6678 if (CB->hasRetAttr(Attribute::NoUndef) ||
6679 CB->hasRetAttr(Attribute::Dereferenceable) ||
6680 CB->hasRetAttr(Attribute::DereferenceableOrNull))
6681 return true;
6682 }
6683
6684 if (!::canCreateUndefOrPoison(Opr, Kind,
6685 /*ConsiderFlagsAndMetadata=*/true)) {
6686 if (const auto *PN = dyn_cast<PHINode>(V)) {
6687 unsigned Num = PN->getNumIncomingValues();
6688 bool IsWellDefined = true;
6689 for (unsigned i = 0; i < Num; ++i) {
6690 if (PN == PN->getIncomingValue(i))
6691 continue;
6692 auto *TI = PN->getIncomingBlock(i)->getTerminator();
6693 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
6694 DT, Depth + 1, Kind)) {
6695 IsWellDefined = false;
6696 break;
6697 }
6698 }
6699 if (IsWellDefined)
6700 return true;
6701 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
6702 : nullptr) {
6703 // For splats we only need to check the value being splatted.
6704 if (OpCheck(Splat))
6705 return true;
6706 } else if (all_of(Opr->operands(), OpCheck))
6707 return true;
6708 }
6709 }
6710
6711 if (auto *I = dyn_cast<LoadInst>(V))
6712 if (I->hasMetadata(LLVMContext::MD_noundef) ||
6713 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
6714 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
6715 return true;
6716
6718 return true;
6719
6720 // CtxI may be null or a cloned instruction.
6721 if (!CtxI || !CtxI->getParent() || !DT)
6722 return false;
6723
6724 auto *DNode = DT->getNode(CtxI->getParent());
6725 if (!DNode)
6726 // Unreachable block
6727 return false;
6728
6729 // If V is used as a branch condition before reaching CtxI, V cannot be
6730 // undef or poison.
6731 // br V, BB1, BB2
6732 // BB1:
6733 // CtxI ; V cannot be undef or poison here
6734 auto *Dominator = DNode->getIDom();
6735 // This check is purely for compile time reasons: we can skip the IDom walk
6736 // if what we are checking for includes undef and the value is not an integer.
6737 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
6738 while (Dominator) {
6739 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
6740
6741 Value *Cond = nullptr;
6742 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
6743 Cond = BI->getCondition();
6744 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
6745 Cond = SI->getCondition();
6746 }
6747
6748 if (Cond) {
6749 if (Cond == V)
6750 return true;
6751 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
6752 // For poison, we can analyze further
6753 auto *Opr = cast<Operator>(Cond);
6754 if (any_of(Opr->operands(), [V](const Use &U) {
6755 return V == U && propagatesPoison(U);
6756 }))
6757 return true;
6758 }
6759 }
6760
6761 Dominator = Dominator->getIDom();
6762 }
6763
6764 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
6765 return true;
6766
6767 return false;
6768}
6769
6771 const Instruction *CtxI,
6772 const DominatorTree *DT,
6773 unsigned Depth) {
6774 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
6776}
6777
6779 const Instruction *CtxI,
6780 const DominatorTree *DT, unsigned Depth) {
6781 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
6783}
6784
6786 const Instruction *CtxI,
6787 const DominatorTree *DT, unsigned Depth) {
6788 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
6790}
6791
6792/// Return true if undefined behavior would provably be executed on the path to
6793/// OnPathTo if Root produced a posion result. Note that this doesn't say
6794/// anything about whether OnPathTo is actually executed or whether Root is
6795/// actually poison. This can be used to assess whether a new use of Root can
6796/// be added at a location which is control equivalent with OnPathTo (such as
6797/// immediately before it) without introducing UB which didn't previously
6798/// exist. Note that a false result conveys no information.
6800 Instruction *OnPathTo,
6801 DominatorTree *DT) {
6802 // Basic approach is to assume Root is poison, propagate poison forward
6803 // through all users we can easily track, and then check whether any of those
6804 // users are provable UB and must execute before out exiting block might
6805 // exit.
6806
6807 // The set of all recursive users we've visited (which are assumed to all be
6808 // poison because of said visit)
6811 Worklist.push_back(Root);
6812 while (!Worklist.empty()) {
6813 const Instruction *I = Worklist.pop_back_val();
6814
6815 // If we know this must trigger UB on a path leading our target.
6816 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
6817 return true;
6818
6819 // If we can't analyze propagation through this instruction, just skip it
6820 // and transitive users. Safe as false is a conservative result.
6821 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
6822 return KnownPoison.contains(U) && propagatesPoison(U);
6823 }))
6824 continue;
6825
6826 if (KnownPoison.insert(I).second)
6827 for (const Instruction *User : I->users())
6828 Worklist.push_back(User);
6829 }
6830
6831 // Might be non-UB, or might have a path we couldn't prove must execute on
6832 // way to exiting bb.
6833 return false;
6834}
6835
6837 const SimplifyQuery &SQ) {
6838 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
6839 Add, SQ);
6840}
6841
6844 const WithCache<const Value *> &RHS,
6845 const SimplifyQuery &SQ) {
6846 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
6847}
6848
6850 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
6851 // of time because it's possible for another thread to interfere with it for an
6852 // arbitrary length of time, but programs aren't allowed to rely on that.
6853
6854 // If there is no successor, then execution can't transfer to it.
6855 if (isa<ReturnInst>(I))
6856 return false;
6858 return false;
6859
6860 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
6861 // Instruction::willReturn.
6862 //
6863 // FIXME: Move this check into Instruction::willReturn.
6864 if (isa<CatchPadInst>(I)) {
6865 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
6866 default:
6867 // A catchpad may invoke exception object constructors and such, which
6868 // in some languages can be arbitrary code, so be conservative by default.
6869 return false;
6871 // For CoreCLR, it just involves a type test.
6872 return true;
6873 }
6874 }
6875
6876 // An instruction that returns without throwing must transfer control flow
6877 // to a successor.
6878 return !I->mayThrow() && I->willReturn();
6879}
6880
6882 // TODO: This is slightly conservative for invoke instruction since exiting
6883 // via an exception *is* normal control for them.
6884 for (const Instruction &I : *BB)
6886 return false;
6887 return true;
6888}
6889
6896
6899 assert(ScanLimit && "scan limit must be non-zero");
6900 for (const Instruction &I : Range) {
6901 if (--ScanLimit == 0)
6902 return false;
6904 return false;
6905 }
6906 return true;
6907}
6908
6910 const Loop *L) {
6911 // The loop header is guaranteed to be executed for every iteration.
6912 //
6913 // FIXME: Relax this constraint to cover all basic blocks that are
6914 // guaranteed to be executed at every iteration.
6915 if (I->getParent() != L->getHeader()) return false;
6916
6917 for (const Instruction &LI : *L->getHeader()) {
6918 if (&LI == I) return true;
6919 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
6920 }
6921 llvm_unreachable("Instruction not contained in its own parent basic block.");
6922}
6923
6925 switch (IID) {
6926 // TODO: Add more intrinsics.
6927 case Intrinsic::sadd_with_overflow:
6928 case Intrinsic::ssub_with_overflow:
6929 case Intrinsic::smul_with_overflow:
6930 case Intrinsic::uadd_with_overflow:
6931 case Intrinsic::usub_with_overflow:
6932 case Intrinsic::umul_with_overflow:
6933 // If an input is a vector containing a poison element, the
6934 // two output vectors (calculated results, overflow bits)'
6935 // corresponding lanes are poison.
6936 return true;
6937 case Intrinsic::ctpop:
6938 case Intrinsic::ctlz:
6939 case Intrinsic::cttz:
6940 case Intrinsic::abs:
6941 case Intrinsic::smax:
6942 case Intrinsic::smin:
6943 case Intrinsic::umax:
6944 case Intrinsic::umin:
6945 case Intrinsic::scmp:
6946 case Intrinsic::smulh:
6947 case Intrinsic::umulh:
6948 case Intrinsic::is_fpclass:
6949 case Intrinsic::ptrmask:
6950 case Intrinsic::ucmp:
6951 case Intrinsic::bitreverse:
6952 case Intrinsic::bswap:
6953 case Intrinsic::sadd_sat:
6954 case Intrinsic::ssub_sat:
6955 case Intrinsic::sshl_sat:
6956 case Intrinsic::uadd_sat:
6957 case Intrinsic::usub_sat:
6958 case Intrinsic::ushl_sat:
6959 case Intrinsic::smul_fix:
6960 case Intrinsic::smul_fix_sat:
6961 case Intrinsic::umul_fix:
6962 case Intrinsic::umul_fix_sat:
6963 case Intrinsic::pow:
6964 case Intrinsic::experimental_constrained_pow:
6965 case Intrinsic::powi:
6966 case Intrinsic::experimental_constrained_powi:
6967 case Intrinsic::sin:
6968 case Intrinsic::experimental_constrained_sin:
6969 case Intrinsic::sinh:
6970 case Intrinsic::experimental_constrained_sinh:
6971 case Intrinsic::cos:
6972 case Intrinsic::experimental_constrained_cos:
6973 case Intrinsic::cosh:
6974 case Intrinsic::experimental_constrained_cosh:
6975 case Intrinsic::sincos:
6976 case Intrinsic::sincospi:
6977 case Intrinsic::tan:
6978 case Intrinsic::experimental_constrained_tan:
6979 case Intrinsic::tanh:
6980 case Intrinsic::experimental_constrained_tanh:
6981 case Intrinsic::asin:
6982 case Intrinsic::experimental_constrained_asin:
6983 case Intrinsic::acos:
6984 case Intrinsic::experimental_constrained_acos:
6985 case Intrinsic::atan:
6986 case Intrinsic::experimental_constrained_atan:
6987 case Intrinsic::atan2:
6988 case Intrinsic::experimental_constrained_atan2:
6989 case Intrinsic::canonicalize:
6990 case Intrinsic::sqrt:
6991 case Intrinsic::experimental_constrained_sqrt:
6992 case Intrinsic::fma:
6993 case Intrinsic::experimental_constrained_fma:
6994 case Intrinsic::fmuladd:
6995 case Intrinsic::experimental_constrained_fmuladd:
6996 case Intrinsic::exp:
6997 case Intrinsic::experimental_constrained_exp:
6998 case Intrinsic::exp2:
6999 case Intrinsic::experimental_constrained_exp2:
7000 case Intrinsic::exp10:
7001 case Intrinsic::log:
7002 case Intrinsic::experimental_constrained_log:
7003 case Intrinsic::log2:
7004 case Intrinsic::experimental_constrained_log2:
7005 case Intrinsic::log10:
7006 case Intrinsic::experimental_constrained_log10:
7007 case Intrinsic::modf:
7008 case Intrinsic::floor:
7009 case Intrinsic::experimental_constrained_floor:
7010 case Intrinsic::ceil:
7011 case Intrinsic::experimental_constrained_ceil:
7012 case Intrinsic::trunc:
7013 case Intrinsic::experimental_constrained_trunc:
7014 case Intrinsic::rint:
7015 case Intrinsic::experimental_constrained_rint:
7016 case Intrinsic::nearbyint:
7017 case Intrinsic::experimental_constrained_nearbyint:
7018 case Intrinsic::round:
7019 case Intrinsic::experimental_constrained_round:
7020 case Intrinsic::roundeven:
7021 case Intrinsic::experimental_constrained_roundeven:
7022 case Intrinsic::lrint:
7023 case Intrinsic::experimental_constrained_lrint:
7024 case Intrinsic::llrint:
7025 case Intrinsic::experimental_constrained_llrint:
7026 case Intrinsic::lround:
7027 case Intrinsic::experimental_constrained_lround:
7028 case Intrinsic::llround:
7029 case Intrinsic::experimental_constrained_llround:
7030 case Intrinsic::fshl:
7031 case Intrinsic::fshr:
7032 case Intrinsic::frexp:
7033 case Intrinsic::ldexp:
7034 case Intrinsic::experimental_constrained_ldexp:
7035 case Intrinsic::get_active_lane_mask:
7036 case Intrinsic::mask_beforefirst:
7037 return true;
7038 default:
7039 return false;
7040 }
7041}
7042
7043bool llvm::propagatesPoison(const Use &PoisonOp) {
7044 const Operator *I = cast<Operator>(PoisonOp.getUser());
7045 switch (I->getOpcode()) {
7046 case Instruction::Freeze:
7047 case Instruction::PHI:
7048 case Instruction::Invoke:
7049 return false;
7050 case Instruction::Select:
7051 return PoisonOp.getOperandNo() == 0;
7052 case Instruction::Call:
7053 if (auto *II = dyn_cast<IntrinsicInst>(I))
7054 return intrinsicPropagatesPoison(II->getIntrinsicID());
7055 return false;
7056 case Instruction::ICmp:
7057 case Instruction::FCmp:
7058 case Instruction::GetElementPtr:
7059 return true;
7060 default:
7062 return true;
7063
7064 // Be conservative and return false.
7065 return false;
7066 }
7067}
7068
7069/// Enumerates all operands of \p I that are guaranteed to not be undef or
7070/// poison. If the callback \p Handle returns true, stop processing and return
7071/// true. Otherwise, return false.
7072template <typename CallableT>
7074 const CallableT &Handle) {
7075 switch (I->getOpcode()) {
7076 case Instruction::Store:
7077 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
7078 return true;
7079 break;
7080
7081 case Instruction::Load:
7082 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
7083 return true;
7084 break;
7085
7086 // Since dereferenceable attribute imply noundef, atomic operations
7087 // also implicitly have noundef pointers too
7088 case Instruction::AtomicCmpXchg:
7090 return true;
7091 break;
7092
7093 case Instruction::AtomicRMW:
7094 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
7095 return true;
7096 break;
7097
7098 case Instruction::Call:
7099 case Instruction::Invoke: {
7100 const CallBase *CB = cast<CallBase>(I);
7101 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
7102 return true;
7103 for (unsigned i = 0; i < CB->arg_size(); ++i)
7104 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
7105 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
7106 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
7107 Handle(CB->getArgOperand(i)))
7108 return true;
7109 break;
7110 }
7111 case Instruction::Ret:
7112 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
7113 Handle(I->getOperand(0)))
7114 return true;
7115 break;
7116 case Instruction::Switch:
7117 if (Handle(cast<SwitchInst>(I)->getCondition()))
7118 return true;
7119 break;
7120 case Instruction::CondBr:
7121 if (Handle(cast<CondBrInst>(I)->getCondition()))
7122 return true;
7123 break;
7124 default:
7125 break;
7126 }
7127
7128 return false;
7129}
7130
7131/// Enumerates all operands of \p I that are guaranteed to not be poison.
7132template <typename CallableT>
7134 const CallableT &Handle) {
7135 if (handleGuaranteedWellDefinedOps(I, Handle))
7136 return true;
7137 switch (I->getOpcode()) {
7138 // Divisors of these operations are allowed to be partially undef.
7139 case Instruction::UDiv:
7140 case Instruction::SDiv:
7141 case Instruction::URem:
7142 case Instruction::SRem:
7143 return Handle(I->getOperand(1));
7144 default:
7145 return false;
7146 }
7147}
7148
7150 const SmallPtrSetImpl<const Value *> &KnownPoison) {
7152 I, [&](const Value *V) { return KnownPoison.count(V); });
7153}
7154
7156 bool PoisonOnly) {
7157 // We currently only look for uses of values within the same basic
7158 // block, as that makes it easier to guarantee that the uses will be
7159 // executed given that Inst is executed.
7160 //
7161 // FIXME: Expand this to consider uses beyond the same basic block. To do
7162 // this, look out for the distinction between post-dominance and strong
7163 // post-dominance.
7164 const BasicBlock *BB = nullptr;
7166 if (const auto *Inst = dyn_cast<Instruction>(V)) {
7167 BB = Inst->getParent();
7168 Begin = Inst->getIterator();
7169 Begin++;
7170 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
7171 if (Arg->getParent()->isDeclaration())
7172 return false;
7173 BB = &Arg->getParent()->getEntryBlock();
7174 Begin = BB->begin();
7175 } else {
7176 return false;
7177 }
7178
7179 // Limit number of instructions we look at, to avoid scanning through large
7180 // blocks. The current limit is chosen arbitrarily.
7181 unsigned ScanLimit = 32;
7183
7184 if (!PoisonOnly) {
7185 // Since undef does not propagate eagerly, be conservative & just check
7186 // whether a value is directly passed to an instruction that must take
7187 // well-defined operands.
7188
7189 for (const auto &I : make_range(Begin, End)) {
7190 if (--ScanLimit == 0)
7191 break;
7192
7193 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
7194 return WellDefinedOp == V;
7195 }))
7196 return true;
7197
7199 break;
7200 }
7201 return false;
7202 }
7203
7204 // Set of instructions that we have proved will yield poison if Inst
7205 // does.
7206 SmallPtrSet<const Value *, 16> YieldsPoison;
7208
7209 YieldsPoison.insert(V);
7210 Visited.insert(BB);
7211
7212 while (true) {
7213 for (const auto &I : make_range(Begin, End)) {
7214 if (--ScanLimit == 0)
7215 return false;
7216 if (mustTriggerUB(&I, YieldsPoison))
7217 return true;
7219 return false;
7220
7221 // If an operand is poison and propagates it, mark I as yielding poison.
7222 for (const Use &Op : I.operands()) {
7223 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
7224 YieldsPoison.insert(&I);
7225 break;
7226 }
7227 }
7228
7229 // Special handling for select, which returns poison if its operand 0 is
7230 // poison (handled in the loop above) *or* if both its true/false operands
7231 // are poison (handled here).
7232 if (I.getOpcode() == Instruction::Select &&
7233 YieldsPoison.count(I.getOperand(1)) &&
7234 YieldsPoison.count(I.getOperand(2))) {
7235 YieldsPoison.insert(&I);
7236 }
7237 }
7238
7239 BB = BB->getSingleSuccessor();
7240 if (!BB || !Visited.insert(BB).second)
7241 break;
7242
7243 Begin = BB->getFirstNonPHIIt();
7244 End = BB->end();
7245 }
7246 return false;
7247}
7248
7250 return ::programUndefinedIfUndefOrPoison(Inst, false);
7251}
7252
7254 return ::programUndefinedIfUndefOrPoison(Inst, true);
7255}
7256
7257static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
7258 if (FMF.noNaNs())
7259 return true;
7260
7261 if (auto *C = dyn_cast<ConstantFP>(V))
7262 return !C->isNaN();
7263
7264 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
7265 if (!C->getElementType()->isFloatingPointTy())
7266 return false;
7267 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
7268 if (C->getElementAsAPFloat(I).isNaN())
7269 return false;
7270 }
7271 return true;
7272 }
7273
7275 return true;
7276
7277 return false;
7278}
7279
7280static bool isKnownNonZero(const Value *V) {
7281 if (auto *C = dyn_cast<ConstantFP>(V))
7282 return !C->isZero();
7283
7284 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
7285 if (!C->getElementType()->isFloatingPointTy())
7286 return false;
7287 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
7288 if (C->getElementAsAPFloat(I).isZero())
7289 return false;
7290 }
7291 return true;
7292 }
7293
7294 return false;
7295}
7296
7297/// Match clamp pattern for float types without care about NaNs or signed zeros.
7298/// Given non-min/max outer cmp/select from the clamp pattern this
7299/// function recognizes if it can be substitued by a "canonical" min/max
7300/// pattern.
7302 Value *CmpLHS, Value *CmpRHS,
7303 Value *TrueVal, Value *FalseVal,
7304 Value *&LHS, Value *&RHS) {
7305 // Try to match
7306 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
7307 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
7308 // and return description of the outer Max/Min.
7309
7310 // First, check if select has inverse order:
7311 if (CmpRHS == FalseVal) {
7312 std::swap(TrueVal, FalseVal);
7314 }
7315
7316 // Assume success now. If there's no match, callers should not use these anyway.
7317 LHS = TrueVal;
7318 RHS = FalseVal;
7319
7320 const APFloat *FC1;
7321 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
7322 return {SPF_UNKNOWN, SPNB_NA, false};
7323
7324 const APFloat *FC2;
7325 switch (Pred) {
7326 case CmpInst::FCMP_OLT:
7327 case CmpInst::FCMP_OLE:
7328 case CmpInst::FCMP_ULT:
7329 case CmpInst::FCMP_ULE:
7330 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
7331 *FC1 < *FC2)
7332 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
7333 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
7334 *FC1 < *FC2)
7335 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
7336 break;
7337 case CmpInst::FCMP_OGT:
7338 case CmpInst::FCMP_OGE:
7339 case CmpInst::FCMP_UGT:
7340 case CmpInst::FCMP_UGE:
7341 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
7342 *FC1 > *FC2)
7343 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
7344 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
7345 *FC1 > *FC2)
7346 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
7347 break;
7348 default:
7349 break;
7350 }
7351
7352 return {SPF_UNKNOWN, SPNB_NA, false};
7353}
7354
7355/// Recognize variations of:
7356/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
7358 Value *CmpLHS, Value *CmpRHS,
7359 Value *TrueVal, Value *FalseVal) {
7360 // Swap the select operands and predicate to match the patterns below.
7361 if (CmpRHS != TrueVal) {
7363 std::swap(TrueVal, FalseVal);
7364 }
7365 const APInt *C1;
7366 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
7367 const APInt *C2;
7368 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
7369 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
7370 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
7371 return {SPF_SMAX, SPNB_NA, false};
7372
7373 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
7374 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
7375 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
7376 return {SPF_SMIN, SPNB_NA, false};
7377
7378 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
7379 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
7380 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
7381 return {SPF_UMAX, SPNB_NA, false};
7382
7383 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
7384 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
7385 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
7386 return {SPF_UMIN, SPNB_NA, false};
7387 }
7388 return {SPF_UNKNOWN, SPNB_NA, false};
7389}
7390
7391/// If the input value is the result of a 'not' op, constant integer, or vector
7392/// splat of a constant integer, return the bitwise-not source value.
7393/// TODO: This could be extended to handle non-splat vector integer constants.
7395 Value *NotV;
7396 if (match(V, m_Not(m_Value(NotV))))
7397 return NotV;
7398
7399 const APInt *C;
7400 if (match(V, m_APInt(C)))
7401 return ConstantInt::get(V->getType(), ~(*C));
7402
7403 return nullptr;
7404}
7405
7406/// Match non-obvious integer minimum and maximum sequences.
7408 Value *CmpRHS, Value *TrueVal,
7409 Value *FalseVal, Value *&LHS,
7410 Value *&RHS) {
7411 // Assume success. If there's no match, callers should not use these anyway.
7412 LHS = TrueVal;
7413 RHS = FalseVal;
7414
7415 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
7417 return SPR;
7418
7419 // Look through 'not' ops to find disguised min/max.
7420 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
7421 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
7422 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
7423 switch (Pred) {
7424 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
7425 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
7426 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
7427 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
7428 default: break;
7429 }
7430 }
7431
7432 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
7433 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
7434 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
7435 switch (Pred) {
7436 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
7437 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
7438 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
7439 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
7440 default: break;
7441 }
7442 }
7443
7445 return {SPF_UNKNOWN, SPNB_NA, false};
7446
7447 const APInt *C1;
7448 if (!match(CmpRHS, m_APInt(C1)))
7449 return {SPF_UNKNOWN, SPNB_NA, false};
7450
7451 // An unsigned min/max can be written with a signed compare.
7452 const APInt *C2;
7453 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
7454 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
7455 // Is the sign bit set?
7456 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
7457 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
7458 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
7459 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
7460
7461 // Is the sign bit clear?
7462 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
7463 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
7464 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
7465 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
7466 }
7467
7468 return {SPF_UNKNOWN, SPNB_NA, false};
7469}
7470
7471bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
7472 bool AllowPoison) {
7473 assert(X && Y && "Invalid operand");
7474
7475 auto IsNegationOf = [&](const Value *X, const Value *Y) {
7476 if (!match(X, m_Neg(m_Specific(Y))))
7477 return false;
7478
7479 auto *BO = cast<BinaryOperator>(X);
7480 if (NeedNSW && !BO->hasNoSignedWrap())
7481 return false;
7482
7483 auto *Zero = cast<Constant>(BO->getOperand(0));
7484 if (!AllowPoison && !Zero->isNullValue())
7485 return false;
7486
7487 return true;
7488 };
7489
7490 // X = -Y or Y = -X
7491 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
7492 return true;
7493
7494 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
7495 Value *A, *B;
7496 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
7497 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
7498 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
7500}
7501
7502bool llvm::isKnownInversion(const Value *X, const Value *Y) {
7503 // Handle X = icmp pred A, B, Y = icmp pred A, C.
7504 Value *A, *B, *C;
7505 CmpPredicate Pred1, Pred2;
7506 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
7507 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
7508 return false;
7509
7510 // They must both have samesign flag or not.
7511 if (Pred1.hasSameSign() != Pred2.hasSameSign())
7512 return false;
7513
7514 if (B == C)
7515 return Pred1 == ICmpInst::getInversePredicate(Pred2);
7516
7517 // Try to infer the relationship from constant ranges.
7518 const APInt *RHSC1, *RHSC2;
7519 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
7520 return false;
7521
7522 // Sign bits of two RHSCs should match.
7523 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
7524 return false;
7525
7526 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
7527 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
7528
7529 return CR1.inverse() == CR2;
7530}
7531
7533 SelectPatternNaNBehavior NaNBehavior,
7534 bool Ordered) {
7535 switch (Pred) {
7536 default:
7537 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
7538 case ICmpInst::ICMP_UGT:
7539 case ICmpInst::ICMP_UGE:
7540 return {SPF_UMAX, SPNB_NA, false};
7541 case ICmpInst::ICMP_SGT:
7542 case ICmpInst::ICMP_SGE:
7543 return {SPF_SMAX, SPNB_NA, false};
7544 case ICmpInst::ICMP_ULT:
7545 case ICmpInst::ICMP_ULE:
7546 return {SPF_UMIN, SPNB_NA, false};
7547 case ICmpInst::ICMP_SLT:
7548 case ICmpInst::ICMP_SLE:
7549 return {SPF_SMIN, SPNB_NA, false};
7550 case FCmpInst::FCMP_UGT:
7551 case FCmpInst::FCMP_UGE:
7552 case FCmpInst::FCMP_OGT:
7553 case FCmpInst::FCMP_OGE:
7554 return {SPF_FMAXNUM, NaNBehavior, Ordered};
7555 case FCmpInst::FCMP_ULT:
7556 case FCmpInst::FCMP_ULE:
7557 case FCmpInst::FCMP_OLT:
7558 case FCmpInst::FCMP_OLE:
7559 return {SPF_FMINNUM, NaNBehavior, Ordered};
7560 }
7561}
7562
7563std::optional<std::pair<CmpPredicate, Constant *>>
7566 "Only for relational integer predicates.");
7567 if (isa<UndefValue>(C))
7568 return std::nullopt;
7569
7570 Type *Type = C->getType();
7571 bool IsSigned = ICmpInst::isSigned(Pred);
7572
7574 bool WillIncrement =
7575 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
7576
7577 // Check if the constant operand can be safely incremented/decremented
7578 // without overflowing/underflowing.
7579 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
7580 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
7581 return false;
7582
7583 if (!Pred.hasSameSign())
7584 return true;
7585
7586 // Crossing the corresponding boundary in the other ordering changes the
7587 // sign bit, and therefore changes the poison domain.
7588 return WillIncrement ? !C->isMaxValue(!IsSigned)
7589 : !C->isMinValue(!IsSigned);
7590 };
7591
7592 Constant *SafeReplacementConstant = nullptr;
7593 if (auto *CI = dyn_cast<ConstantInt>(C)) {
7594 // Bail out if the constant can't be safely incremented/decremented.
7595 if (!ConstantIsOk(CI))
7596 return std::nullopt;
7597 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
7598 unsigned NumElts = FVTy->getNumElements();
7599 for (unsigned i = 0; i != NumElts; ++i) {
7600 Constant *Elt = C->getAggregateElement(i);
7601 if (!Elt)
7602 return std::nullopt;
7603
7604 if (isa<UndefValue>(Elt))
7605 continue;
7606
7607 // Bail out if we can't determine if this constant is min/max or if we
7608 // know that this constant is min/max.
7609 auto *CI = dyn_cast<ConstantInt>(Elt);
7610 if (!CI || !ConstantIsOk(CI))
7611 return std::nullopt;
7612
7613 if (!SafeReplacementConstant)
7614 SafeReplacementConstant = CI;
7615 }
7616 } else if (isa<VectorType>(C->getType())) {
7617 // Handle scalable splat
7618 Value *SplatC = C->getSplatValue();
7619 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
7620 // Bail out if the constant can't be safely incremented/decremented.
7621 if (!CI || !ConstantIsOk(CI))
7622 return std::nullopt;
7623 } else {
7624 // ConstantExpr?
7625 return std::nullopt;
7626 }
7627
7628 // It may not be safe to change a compare predicate in the presence of
7629 // undefined elements, so replace those elements with the first safe constant
7630 // that we found.
7631 // TODO: in case of poison, it is safe; let's replace undefs only.
7632 if (C->containsUndefOrPoisonElement()) {
7633 assert(SafeReplacementConstant && "Replacement constant not set");
7634 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
7635 }
7636
7638 Pred.hasSameSign());
7639
7640 // Increment or decrement the constant.
7641 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
7642 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
7643
7644 return std::make_pair(NewPred, NewC);
7645}
7646
7648 FastMathFlags FMF, Value *CmpLHS,
7649 Value *CmpRHS, Value *TrueVal,
7650 Value *FalseVal, Value *&LHS,
7651 Value *&RHS) {
7653 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
7654 // 0.0 operand, set the compare's 0.0 operands to that same value for the
7655 // purpose of identifying min/max. Disregard vector constants with undefined
7656 // elements because those can not be back-propagated for analysis.
7657 Value *OutputZeroVal = nullptr;
7658 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
7659 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
7660 OutputZeroVal = TrueVal;
7661 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
7662 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
7663 OutputZeroVal = FalseVal;
7664
7665 if (OutputZeroVal) {
7666 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
7667 CmpLHS = OutputZeroVal;
7668 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
7669 CmpRHS = OutputZeroVal;
7670 }
7671 }
7672
7673 LHS = CmpLHS;
7674 RHS = CmpRHS;
7675
7676 // Signed zero may return inconsistent results between implementations.
7677 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
7678 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
7679 // Therefore, we behave conservatively and only proceed if at least one of the
7680 // operands is known to not be zero or if we don't care about signed zero.
7682 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
7683 !isKnownNonZero(CmpRHS))
7684 return {SPF_UNKNOWN, SPNB_NA, false};
7685 }
7686
7687 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
7688 bool Ordered = false;
7689
7690 // When given one NaN and one non-NaN input:
7691 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
7692 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
7693 // ordered comparison fails), which could be NaN or non-NaN.
7694 // so here we discover exactly what NaN behavior is required/accepted.
7696 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
7697 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
7698
7699 if (LHSSafe && RHSSafe) {
7700 // Both operands are known non-NaN.
7701 NaNBehavior = SPNB_RETURNS_ANY;
7702 Ordered = CmpInst::isOrdered(Pred);
7703 } else if (CmpInst::isOrdered(Pred)) {
7704 // An ordered comparison will return false when given a NaN, so it
7705 // returns the RHS.
7706 Ordered = true;
7707 if (LHSSafe)
7708 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
7709 NaNBehavior = SPNB_RETURNS_NAN;
7710 else if (RHSSafe)
7711 NaNBehavior = SPNB_RETURNS_OTHER;
7712 else
7713 // Completely unsafe.
7714 return {SPF_UNKNOWN, SPNB_NA, false};
7715 } else {
7716 Ordered = false;
7717 // An unordered comparison will return true when given a NaN, so it
7718 // returns the LHS.
7719 if (LHSSafe)
7720 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
7721 NaNBehavior = SPNB_RETURNS_OTHER;
7722 else if (RHSSafe)
7723 NaNBehavior = SPNB_RETURNS_NAN;
7724 else
7725 // Completely unsafe.
7726 return {SPF_UNKNOWN, SPNB_NA, false};
7727 }
7728 }
7729
7730 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
7731 std::swap(CmpLHS, CmpRHS);
7733 if (NaNBehavior == SPNB_RETURNS_NAN)
7734 NaNBehavior = SPNB_RETURNS_OTHER;
7735 else if (NaNBehavior == SPNB_RETURNS_OTHER)
7736 NaNBehavior = SPNB_RETURNS_NAN;
7737 Ordered = !Ordered;
7738 }
7739
7740 // ([if]cmp X, Y) ? X : Y
7741 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
7742 return getSelectPattern(Pred, NaNBehavior, Ordered);
7743
7744 if (isKnownNegation(TrueVal, FalseVal)) {
7745 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
7746 // match against either LHS or sign-preserving operations on LHS, like
7747 // sext(LHS), or binary ops that do not wrap in signed sense.
7748 auto CmpLHSOrSExt =
7749 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
7750 auto MaybeSExtOrMulCmpLHS =
7751 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
7752 m_NSWShl(CmpLHSOrSExt, m_Value()));
7753 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
7754 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
7755 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
7756 // Set the return values. If the compare uses the negated value (-X >s 0),
7757 // swap the return values because the negated value is always 'RHS'.
7758 LHS = TrueVal;
7759 RHS = FalseVal;
7760 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
7761 std::swap(LHS, RHS);
7762
7763 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
7764 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
7765 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
7766 return {SPF_ABS, SPNB_NA, false};
7767
7768 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
7769 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
7770 return {SPF_ABS, SPNB_NA, false};
7771
7772 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
7773 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
7774 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
7775 return {SPF_NABS, SPNB_NA, false};
7776 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
7777 // Set the return values. If the compare uses the negated value (-X >s 0),
7778 // swap the return values because the negated value is always 'RHS'.
7779 LHS = FalseVal;
7780 RHS = TrueVal;
7781 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
7782 std::swap(LHS, RHS);
7783
7784 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
7785 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
7786 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
7787 return {SPF_NABS, SPNB_NA, false};
7788
7789 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
7790 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
7791 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
7792 return {SPF_ABS, SPNB_NA, false};
7793 }
7794 }
7795
7797 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
7798
7799 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
7800 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
7801 // semantics than minNum. Be conservative in such case.
7802 if (NaNBehavior != SPNB_RETURNS_ANY ||
7803 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
7804 !isKnownNonZero(CmpRHS)))
7805 return {SPF_UNKNOWN, SPNB_NA, false};
7806
7807 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
7808}
7809
7811 Instruction::CastOps *CastOp) {
7812 const DataLayout &DL = CmpI->getDataLayout();
7813
7814 Constant *CastedTo = nullptr;
7815 switch (*CastOp) {
7816 case Instruction::ZExt:
7817 if (CmpI->isUnsigned())
7818 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
7819 break;
7820 case Instruction::SExt:
7821 if (CmpI->isSigned())
7822 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
7823 break;
7824 case Instruction::Trunc:
7825 Constant *CmpConst;
7826 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
7827 CmpConst->getType() == SrcTy) {
7828 // Here we have the following case:
7829 //
7830 // %cond = cmp iN %x, CmpConst
7831 // %tr = trunc iN %x to iK
7832 // %narrowsel = select i1 %cond, iK %t, iK C
7833 //
7834 // We can always move trunc after select operation:
7835 //
7836 // %cond = cmp iN %x, CmpConst
7837 // %widesel = select i1 %cond, iN %x, iN CmpConst
7838 // %tr = trunc iN %widesel to iK
7839 //
7840 // Note that C could be extended in any way because we don't care about
7841 // upper bits after truncation. It can't be abs pattern, because it would
7842 // look like:
7843 //
7844 // select i1 %cond, x, -x.
7845 //
7846 // So only min/max pattern could be matched. Such match requires widened C
7847 // == CmpConst. That is why set widened C = CmpConst, condition trunc
7848 // CmpConst == C is checked below.
7849 CastedTo = CmpConst;
7850 } else {
7851 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
7852 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
7853 }
7854 break;
7855 case Instruction::FPTrunc:
7856 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
7857 break;
7858 case Instruction::FPExt:
7859 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
7860 break;
7861 case Instruction::FPToUI:
7862 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
7863 break;
7864 case Instruction::FPToSI:
7865 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
7866 break;
7867 case Instruction::UIToFP:
7868 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
7869 break;
7870 case Instruction::SIToFP:
7871 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
7872 break;
7873 default:
7874 break;
7875 }
7876
7877 if (!CastedTo)
7878 return nullptr;
7879
7880 // Make sure the cast doesn't lose any information.
7881 Constant *CastedBack =
7882 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
7883 if (CastedBack && CastedBack != C)
7884 return nullptr;
7885
7886 return CastedTo;
7887}
7888
7889/// Helps to match a select pattern in case of a type mismatch.
7890///
7891/// The function processes the case when type of true and false values of a
7892/// select instruction differs from type of the cmp instruction operands because
7893/// of a cast instruction. The function checks if it is legal to move the cast
7894/// operation after "select". If yes, it returns the new second value of
7895/// "select" (with the assumption that cast is moved):
7896/// 1. As operand of cast instruction when both values of "select" are same cast
7897/// instructions.
7898/// 2. As restored constant (by applying reverse cast operation) when the first
7899/// value of the "select" is a cast operation and the second value is a
7900/// constant. It is implemented in lookThroughCastConst().
7901/// 3. As one operand is cast instruction and the other is not. The operands in
7902/// sel(cmp) are in different type integer.
7903/// NOTE: We return only the new second value because the first value could be
7904/// accessed as operand of cast instruction.
7906 Instruction::CastOps *CastOp) {
7907 auto *Cast1 = dyn_cast<CastInst>(V1);
7908 if (!Cast1)
7909 return nullptr;
7910
7911 *CastOp = Cast1->getOpcode();
7912 Type *SrcTy = Cast1->getSrcTy();
7913 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
7914 // If V1 and V2 are both the same cast from the same type, look through V1.
7915 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
7916 return Cast2->getOperand(0);
7917 return nullptr;
7918 }
7919
7920 auto *C = dyn_cast<Constant>(V2);
7921 if (C)
7922 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
7923
7924 Value *CastedTo = nullptr;
7925 if (*CastOp == Instruction::Trunc) {
7926 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
7927 // Here we have the following case:
7928 // %y_ext = sext iK %y to iN
7929 // %cond = cmp iN %x, %y_ext
7930 // %tr = trunc iN %x to iK
7931 // %narrowsel = select i1 %cond, iK %tr, iK %y
7932 //
7933 // We can always move trunc after select operation:
7934 // %y_ext = sext iK %y to iN
7935 // %cond = cmp iN %x, %y_ext
7936 // %widesel = select i1 %cond, iN %x, iN %y_ext
7937 // %tr = trunc iN %widesel to iK
7938 assert(V2->getType() == Cast1->getType() &&
7939 "V2 and Cast1 should be the same type.");
7940 CastedTo = CmpI->getOperand(1);
7941 }
7942 }
7943
7944 return CastedTo;
7945}
7947 Instruction::CastOps *CastOp) {
7949 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
7950
7951 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
7952 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
7953
7954 Value *TrueVal = SI->getTrueValue();
7955 Value *FalseVal = SI->getFalseValue();
7956
7958 CmpI, TrueVal, FalseVal, LHS, RHS, SI->getFastMathFlagsOrNone(), CastOp);
7959}
7960
7962 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
7963 FastMathFlags FMF, Instruction::CastOps *CastOp) {
7964 CmpInst::Predicate Pred = CmpI->getPredicate();
7965 Value *CmpLHS = CmpI->getOperand(0);
7966 Value *CmpRHS = CmpI->getOperand(1);
7967 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
7968 FMF.setNoNaNs();
7969
7970 // Bail out early.
7971 if (CmpI->isEquality())
7972 return {SPF_UNKNOWN, SPNB_NA, false};
7973
7974 // Deal with type mismatches.
7975 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
7976 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
7977 // If this is a potential fmin/fmax with a cast to integer, then ignore
7978 // -0.0 because there is no corresponding integer value.
7979 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
7980 FMF.setNoSignedZeros();
7981 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
7982 cast<CastInst>(TrueVal)->getOperand(0), C,
7983 LHS, RHS);
7984 }
7985 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
7986 // If this is a potential fmin/fmax with a cast to integer, then ignore
7987 // -0.0 because there is no corresponding integer value.
7988 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
7989 FMF.setNoSignedZeros();
7990 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, C,
7991 cast<CastInst>(FalseVal)->getOperand(0), LHS,
7992 RHS);
7993 }
7994 }
7995 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS,
7996 RHS);
7997}
7998
8000 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
8001 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
8002 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
8003 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
8004 if (SPF == SPF_FMINNUM)
8005 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
8006 if (SPF == SPF_FMAXNUM)
8007 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
8008 llvm_unreachable("unhandled!");
8009}
8010
8012 switch (SPF) {
8014 return Intrinsic::umin;
8016 return Intrinsic::umax;
8018 return Intrinsic::smin;
8020 return Intrinsic::smax;
8021 default:
8022 llvm_unreachable("Unexpected SPF");
8023 }
8024}
8025
8027 if (SPF == SPF_SMIN) return SPF_SMAX;
8028 if (SPF == SPF_UMIN) return SPF_UMAX;
8029 if (SPF == SPF_SMAX) return SPF_SMIN;
8030 if (SPF == SPF_UMAX) return SPF_UMIN;
8031 llvm_unreachable("unhandled!");
8032}
8033
8035 switch (MinMaxID) {
8036 case Intrinsic::smax: return Intrinsic::smin;
8037 case Intrinsic::smin: return Intrinsic::smax;
8038 case Intrinsic::umax: return Intrinsic::umin;
8039 case Intrinsic::umin: return Intrinsic::umax;
8040 // Please note that next four intrinsics may produce the same result for
8041 // original and inverted case even if X != Y due to NaN is handled specially.
8042 case Intrinsic::maximum: return Intrinsic::minimum;
8043 case Intrinsic::minimum: return Intrinsic::maximum;
8044 case Intrinsic::maxnum: return Intrinsic::minnum;
8045 case Intrinsic::minnum: return Intrinsic::maxnum;
8046 case Intrinsic::maximumnum:
8047 return Intrinsic::minimumnum;
8048 case Intrinsic::minimumnum:
8049 return Intrinsic::maximumnum;
8050 default: llvm_unreachable("Unexpected intrinsic");
8051 }
8052}
8053
8055 switch (SPF) {
8058 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
8059 case SPF_UMIN: return APInt::getMinValue(BitWidth);
8060 default: llvm_unreachable("Unexpected flavor");
8061 }
8062}
8063
8064std::pair<Intrinsic::ID, bool>
8066 // Check if VL contains select instructions that can be folded into a min/max
8067 // vector intrinsic and return the intrinsic if it is possible.
8068 // TODO: Support floating point min/max.
8069 bool AllCmpSingleUse = true;
8070 SelectPatternResult SelectPattern;
8071 SelectPattern.Flavor = SPF_UNKNOWN;
8072 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
8073 Value *LHS, *RHS;
8074 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
8075 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
8076 return false;
8077 if (SelectPattern.Flavor != SPF_UNKNOWN &&
8078 SelectPattern.Flavor != CurrentPattern.Flavor)
8079 return false;
8080 SelectPattern = CurrentPattern;
8081 AllCmpSingleUse &=
8083 return true;
8084 })) {
8085 switch (SelectPattern.Flavor) {
8086 case SPF_SMIN:
8087 return {Intrinsic::smin, AllCmpSingleUse};
8088 case SPF_UMIN:
8089 return {Intrinsic::umin, AllCmpSingleUse};
8090 case SPF_SMAX:
8091 return {Intrinsic::smax, AllCmpSingleUse};
8092 case SPF_UMAX:
8093 return {Intrinsic::umax, AllCmpSingleUse};
8094 case SPF_FMAXNUM:
8095 return {Intrinsic::maxnum, AllCmpSingleUse};
8096 case SPF_FMINNUM:
8097 return {Intrinsic::minnum, AllCmpSingleUse};
8098 default:
8099 llvm_unreachable("unexpected select pattern flavor");
8100 }
8101 }
8102 return {Intrinsic::not_intrinsic, false};
8103}
8104
8105template <typename InstTy>
8106static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
8107 Value *&Init, Value *&OtherOp) {
8108 // Handle the case of a simple two-predecessor recurrence PHI.
8109 // There's a lot more that could theoretically be done here, but
8110 // this is sufficient to catch some interesting cases.
8111 // TODO: Expand list -- gep, uadd.sat etc.
8112 if (PN->getNumIncomingValues() != 2)
8113 return false;
8114
8115 for (unsigned I = 0; I != 2; ++I) {
8116 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
8117 Operation && Operation->getNumOperands() >= 2) {
8118 Value *LHS = Operation->getOperand(0);
8119 Value *RHS = Operation->getOperand(1);
8120 if (LHS != PN && RHS != PN)
8121 continue;
8122
8123 Inst = Operation;
8124 Init = PN->getIncomingValue(!I);
8125 OtherOp = (LHS == PN) ? RHS : LHS;
8126 return true;
8127 }
8128 }
8129 return false;
8130}
8131
8132template <typename InstTy>
8133static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
8134 Value *&Init, Value *&OtherOp0,
8135 Value *&OtherOp1) {
8136 if (PN->getNumIncomingValues() != 2)
8137 return false;
8138
8139 for (unsigned I = 0; I != 2; ++I) {
8140 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
8141 Operation && Operation->getNumOperands() >= 3) {
8142 Value *Op0 = Operation->getOperand(0);
8143 Value *Op1 = Operation->getOperand(1);
8144 Value *Op2 = Operation->getOperand(2);
8145
8146 if (Op0 != PN && Op1 != PN && Op2 != PN)
8147 continue;
8148
8149 Inst = Operation;
8150 Init = PN->getIncomingValue(!I);
8151 if (Op0 == PN) {
8152 OtherOp0 = Op1;
8153 OtherOp1 = Op2;
8154 } else if (Op1 == PN) {
8155 OtherOp0 = Op0;
8156 OtherOp1 = Op2;
8157 } else {
8158 OtherOp0 = Op0;
8159 OtherOp1 = Op1;
8160 }
8161 return true;
8162 }
8163 }
8164 return false;
8165}
8167 Value *&Start, Value *&Step) {
8168 // We try to match a recurrence of the form:
8169 // %iv = [Start, %entry], [%iv.next, %backedge]
8170 // %iv.next = binop %iv, Step
8171 // Or:
8172 // %iv = [Start, %entry], [%iv.next, %backedge]
8173 // %iv.next = binop Step, %iv
8174 return matchTwoInputRecurrence(P, BO, Start, Step);
8175}
8176
8178 Value *&Start, Value *&Step) {
8179 BinaryOperator *BO = nullptr;
8180 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
8181 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
8182}
8183
8185 PHINode *&P, Value *&Init,
8186 Value *&OtherOp) {
8187 // Binary intrinsics only supported for now.
8188 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
8189 I->getType() != I->getArgOperand(1)->getType())
8190 return false;
8191
8192 IntrinsicInst *II = nullptr;
8193 P = dyn_cast<PHINode>(I->getArgOperand(0));
8194 if (!P)
8195 P = dyn_cast<PHINode>(I->getArgOperand(1));
8196
8197 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
8198}
8199
8201 PHINode *&P, Value *&Init,
8202 Value *&OtherOp0,
8203 Value *&OtherOp1) {
8204 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
8205 I->getType() != I->getArgOperand(1)->getType() ||
8206 I->getType() != I->getArgOperand(2)->getType())
8207 return false;
8208 IntrinsicInst *II = nullptr;
8209 P = dyn_cast<PHINode>(I->getArgOperand(0));
8210 if (!P) {
8211 P = dyn_cast<PHINode>(I->getArgOperand(1));
8212 if (!P)
8213 P = dyn_cast<PHINode>(I->getArgOperand(2));
8214 }
8215 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
8216 II == I;
8217}
8218
8219/// Return true if "icmp Pred LHS RHS" is always true.
8221 const Value *RHS) {
8223 return true;
8224
8225 switch (Pred) {
8226 default:
8227 return false;
8228
8229 case CmpInst::ICMP_SLE: {
8230 const APInt *C;
8231
8232 // LHS s<= LHS +_{nsw} C if C >= 0
8233 // LHS s<= LHS | C if C >= 0
8234 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
8236 return !C->isNegative();
8237
8238 // LHS s<= smax(LHS, V) for any V
8240 return true;
8241
8242 // smin(RHS, V) s<= RHS for any V
8244 return true;
8245
8246 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
8247 const Value *X;
8248 const APInt *CLHS, *CRHS;
8249 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
8251 return CLHS->sle(*CRHS);
8252
8253 return false;
8254 }
8255
8256 case CmpInst::ICMP_ULE: {
8257 // LHS u<= LHS +_{nuw} V for any V
8258 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
8260 return true;
8261
8262 // LHS u<= LHS | V for any V
8263 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
8264 return true;
8265
8266 // LHS u<= umax(LHS, V) for any V
8268 return true;
8269
8270 // RHS >> V u<= RHS for any V
8271 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
8272 return true;
8273
8274 // RHS u/ C_ugt_1 u<= RHS
8275 const APInt *C;
8276 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
8277 return true;
8278
8279 // RHS & V u<= RHS for any V
8281 return true;
8282
8283 // umin(RHS, V) u<= RHS for any V
8285 return true;
8286
8287 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
8288 const Value *X;
8289 const APInt *CLHS, *CRHS;
8290 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
8292 return CLHS->ule(*CRHS);
8293
8294 return false;
8295 }
8296 }
8297}
8298
8299/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
8300/// ALHS ARHS" is true. Otherwise, return std::nullopt.
8301static std::optional<bool>
8303 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
8304 switch (Pred) {
8305 default:
8306 return std::nullopt;
8307
8308 case CmpInst::ICMP_SLT:
8309 case CmpInst::ICMP_SLE:
8310 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
8312 return true;
8313 return std::nullopt;
8314
8315 case CmpInst::ICMP_SGT:
8316 case CmpInst::ICMP_SGE:
8317 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
8319 return true;
8320 return std::nullopt;
8321
8322 case CmpInst::ICMP_ULT:
8323 case CmpInst::ICMP_ULE:
8324 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
8326 return true;
8327 return std::nullopt;
8328
8329 case CmpInst::ICMP_UGT:
8330 case CmpInst::ICMP_UGE:
8331 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
8333 return true;
8334 return std::nullopt;
8335 }
8336}
8337
8338/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
8339/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
8340/// Otherwise, return std::nullopt if we can't infer anything.
8341static std::optional<bool>
8343 CmpPredicate RPred, const ConstantRange &RCR) {
8344 auto CRImpliesPred = [&](ConstantRange CR,
8345 CmpInst::Predicate Pred) -> std::optional<bool> {
8346 // If all true values for lhs and true for rhs, lhs implies rhs
8347 if (CR.icmp(Pred, RCR))
8348 return true;
8349
8350 // If there is no overlap, lhs implies not rhs
8352 return false;
8353
8354 return std::nullopt;
8355 };
8356 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
8357 RPred))
8358 return Res;
8359 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
8361 : LPred.dropSameSign();
8363 : RPred.dropSameSign();
8364 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
8365 RPred);
8366 }
8367 return std::nullopt;
8368}
8369
8370/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
8371/// is true. Return false if LHS implies RHS is false. Otherwise, return
8372/// std::nullopt if we can't infer anything.
8373static std::optional<bool>
8374isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
8375 CmpPredicate RPred, const Value *R0, const Value *R1,
8376 const DataLayout &DL, bool LHSIsTrue) {
8377 // The rest of the logic assumes the LHS condition is true. If that's not the
8378 // case, invert the predicate to make it so.
8379 if (!LHSIsTrue)
8380 LPred = ICmpInst::getInverseCmpPredicate(LPred);
8381
8382 // We can have non-canonical operands, so try to normalize any common operand
8383 // to L0/R0.
8384 if (L0 == R1) {
8385 std::swap(R0, R1);
8386 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
8387 }
8388 if (R0 == L1) {
8389 std::swap(L0, L1);
8390 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
8391 }
8392 if (L1 == R1) {
8393 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
8394 if (L0 != R0 || match(L0, m_ImmConstant())) {
8395 std::swap(L0, L1);
8396 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
8397 std::swap(R0, R1);
8398 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
8399 }
8400 }
8401
8402 // See if we can infer anything if operand-0 matches and we have at least one
8403 // constant.
8404 const APInt *Unused;
8405 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
8406 // Potential TODO: We could also further use the constant range of L0/R0 to
8407 // further constraint the constant ranges. At the moment this leads to
8408 // several regressions related to not transforming `multi_use(A + C0) eq/ne
8409 // C1` (see discussion: D58633).
8410 SimplifyQuery SQ(DL);
8415
8416 // Even if L1/R1 are not both constant, we can still sometimes deduce
8417 // relationship from a single constant. For example X u> Y implies X != 0.
8418 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
8419 return R;
8420 // If both L1/R1 were exact constant ranges and we didn't get anything
8421 // here, we won't be able to deduce this.
8422 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
8423 return std::nullopt;
8424 }
8425
8426 // Can we infer anything when the two compares have matching operands?
8427 if (L0 == R0 && L1 == R1)
8428 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
8429
8430 // It only really makes sense in the context of signed comparison for "X - Y
8431 // must be positive if X >= Y and no overflow".
8432 // Take SGT as an example: L0:x > L1:y and C >= 0
8433 // ==> R0:(x -nsw y) < R1:(-C) is false
8434 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
8435 if ((SignedLPred == ICmpInst::ICMP_SGT ||
8436 SignedLPred == ICmpInst::ICMP_SGE) &&
8437 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
8438 if (match(R1, m_NonPositive()) &&
8439 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
8440 return false;
8441 }
8442
8443 // Take SLT as an example: L0:x < L1:y and C <= 0
8444 // ==> R0:(x -nsw y) < R1:(-C) is true
8445 if ((SignedLPred == ICmpInst::ICMP_SLT ||
8446 SignedLPred == ICmpInst::ICMP_SLE) &&
8447 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
8448 if (match(R1, m_NonNegative()) &&
8449 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
8450 return true;
8451 }
8452
8453 // (a - b) pred C -> a != b, if 0 pred C is false
8454 // (ptrtoint(a) - ptrtoint(b)) pred C -> a != b, if 0 pred C is false
8455 Value *A, *B;
8456 if (ICmpInst::isEquality(RPred) && cmpExcludesZero(LPred, L1) &&
8457 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
8458 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
8463 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
8464 }
8465
8466 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
8467 if (L0 == R0 &&
8468 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
8469 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
8470 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
8471 return CmpPredicate::getMatching(LPred, RPred).has_value();
8472
8473 if (auto P = CmpPredicate::getMatching(LPred, RPred))
8474 return isImpliedCondOperands(*P, L0, L1, R0, R1);
8475
8476 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
8477 // Example: L0 u< 13 => (L0 & 16) == 0
8478 const APInt *LC, *RC, *MaskC;
8479 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
8480 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
8482 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
8483 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
8484 return true;
8485 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
8486 ConstantRange(*RC)))
8487 return false;
8488 }
8489
8490 return std::nullopt;
8491}
8492
8493/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
8494/// is true. Return false if LHS implies RHS is false. Otherwise, return
8495/// std::nullopt if we can't infer anything.
8496static std::optional<bool>
8498 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
8499 const DataLayout &DL, bool LHSIsTrue) {
8500 // The rest of the logic assumes the LHS condition is true. If that's not the
8501 // case, invert the predicate to make it so.
8502 if (!LHSIsTrue)
8503 LPred = FCmpInst::getInversePredicate(LPred);
8504
8505 // We can have non-canonical operands, so try to normalize any common operand
8506 // to L0/R0.
8507 if (L0 == R1) {
8508 std::swap(R0, R1);
8509 RPred = FCmpInst::getSwappedPredicate(RPred);
8510 }
8511 if (R0 == L1) {
8512 std::swap(L0, L1);
8513 LPred = FCmpInst::getSwappedPredicate(LPred);
8514 }
8515 if (L1 == R1) {
8516 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
8517 if (L0 != R0 || match(L0, m_ImmConstant())) {
8518 std::swap(L0, L1);
8519 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
8520 std::swap(R0, R1);
8521 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
8522 }
8523 }
8524
8525 // Can we infer anything when the two compares have matching operands?
8526 if (L0 == R0 && L1 == R1) {
8527 if ((LPred & RPred) == LPred)
8528 return true;
8529 if ((LPred & ~RPred) == LPred)
8530 return false;
8531 }
8532
8533 // See if we can infer anything if operand-0 matches and we have at least one
8534 // constant.
8535 const APFloat *L1C, *R1C;
8536 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
8537 if (std::optional<ConstantFPRange> DomCR =
8539 if (std::optional<ConstantFPRange> ImpliedCR =
8541 if (ImpliedCR->contains(*DomCR))
8542 return true;
8543 }
8544 if (std::optional<ConstantFPRange> ImpliedCR =
8546 FCmpInst::getInversePredicate(RPred), *R1C)) {
8547 if (ImpliedCR->contains(*DomCR))
8548 return false;
8549 }
8550 }
8551 }
8552
8553 return std::nullopt;
8554}
8555
8556/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
8557/// false. Otherwise, return std::nullopt if we can't infer anything. We
8558/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
8559/// instruction.
8560static std::optional<bool>
8562 const Value *RHSOp0, const Value *RHSOp1,
8563 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
8564 // The LHS must be an 'or', 'and', or a 'select' instruction.
8565 assert((LHS->getOpcode() == Instruction::And ||
8566 LHS->getOpcode() == Instruction::Or ||
8567 LHS->getOpcode() == Instruction::Select) &&
8568 "Expected LHS to be 'and', 'or', or 'select'.");
8569
8570 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
8571
8572 // If the result of an 'or' is false, then we know both legs of the 'or' are
8573 // false. Similarly, if the result of an 'and' is true, then we know both
8574 // legs of the 'and' are true.
8575 const Value *ALHS, *ARHS;
8576 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
8577 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
8578 // FIXME: Make this non-recursion.
8579 if (std::optional<bool> Implication = isImpliedCondition(
8580 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
8581 return Implication;
8582 if (std::optional<bool> Implication = isImpliedCondition(
8583 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
8584 return Implication;
8585 return std::nullopt;
8586 }
8587 return std::nullopt;
8588}
8589
8590std::optional<bool>
8592 const Value *RHSOp0, const Value *RHSOp1,
8593 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
8594 // Bail out when we hit the limit.
8596 return std::nullopt;
8597
8598 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
8599 // example.
8600 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
8601 return std::nullopt;
8602
8603 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
8604 "Expected integer type only!");
8605
8606 // Match not
8607 if (match(LHS, m_Not(m_Value(LHS))))
8608 LHSIsTrue = !LHSIsTrue;
8609
8610 // Both LHS and RHS are icmps.
8611 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
8612 CmpPredicate LHSPred;
8613 Value *LHSOp0, *LHSOp1;
8614 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
8615 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
8616 RHSOp1, DL, LHSIsTrue);
8617 } else {
8618 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
8619 "Expected floating point type only!");
8620 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
8621 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
8622 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
8623 DL, LHSIsTrue);
8624 }
8625
8626 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
8627 /// the RHS to be an icmp.
8628 /// FIXME: Add support for and/or/select on the RHS.
8629 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
8630 if ((LHSI->getOpcode() == Instruction::And ||
8631 LHSI->getOpcode() == Instruction::Or ||
8632 LHSI->getOpcode() == Instruction::Select))
8633 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
8634 Depth);
8635 }
8636 return std::nullopt;
8637}
8638
8639std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
8640 const DataLayout &DL,
8641 bool LHSIsTrue, unsigned Depth) {
8642 // LHS ==> RHS by definition
8643 if (LHS == RHS)
8644 return LHSIsTrue;
8645
8646 // Match not
8647 bool InvertRHS = false;
8648 if (match(RHS, m_Not(m_Value(RHS)))) {
8649 if (LHS == RHS)
8650 return !LHSIsTrue;
8651 InvertRHS = true;
8652 }
8653
8654 CmpPredicate RHSPred;
8655 Value *RHSOp0, *RHSOp1;
8656 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
8657 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
8658 LHSIsTrue, Depth))
8659 return InvertRHS ? !*Implied : *Implied;
8660 return std::nullopt;
8661 }
8662 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
8663 if (auto Implied = isImpliedCondition(
8664 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
8665 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
8666 return InvertRHS ? !*Implied : *Implied;
8667 return std::nullopt;
8668 }
8669
8671 return std::nullopt;
8672
8673 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
8674 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
8675 const Value *RHS1, *RHS2;
8676 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
8677 if (std::optional<bool> Imp =
8678 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
8679 if (*Imp == true)
8680 return !InvertRHS;
8681 if (std::optional<bool> Imp =
8682 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
8683 if (*Imp == true)
8684 return !InvertRHS;
8685 }
8686 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
8687 if (std::optional<bool> Imp =
8688 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
8689 if (*Imp == false)
8690 return InvertRHS;
8691 if (std::optional<bool> Imp =
8692 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
8693 if (*Imp == false)
8694 return InvertRHS;
8695 }
8696
8697 return std::nullopt;
8698}
8699
8700// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
8701// condition dominating ContextI or nullptr, if no condition is found.
8702static std::pair<Value *, bool>
8704 if (!ContextI || !ContextI->getParent())
8705 return {nullptr, false};
8706
8707 // TODO: This is a poor/cheap way to determine dominance. Should we use a
8708 // dominator tree (eg, from a SimplifyQuery) instead?
8709 const BasicBlock *ContextBB = ContextI->getParent();
8710 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
8711 if (!PredBB)
8712 return {nullptr, false};
8713
8714 // We need a conditional branch in the predecessor.
8715 Value *PredCond;
8716 BasicBlock *TrueBB, *FalseBB;
8717 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
8718 return {nullptr, false};
8719
8720 // The branch should get simplified. Don't bother simplifying this condition.
8721 if (TrueBB == FalseBB)
8722 return {nullptr, false};
8723
8724 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
8725 "Predecessor block does not point to successor?");
8726
8727 // Is this condition implied by the predecessor condition?
8728 return {PredCond, TrueBB == ContextBB};
8729}
8730
8731std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
8732 const Instruction *ContextI,
8733 const DataLayout &DL) {
8734 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
8735 auto PredCond = getDomPredecessorCondition(ContextI);
8736 if (PredCond.first)
8737 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
8738 return std::nullopt;
8739}
8740
8742 const Value *LHS,
8743 const Value *RHS,
8744 const Instruction *ContextI,
8745 const DataLayout &DL) {
8746 auto PredCond = getDomPredecessorCondition(ContextI);
8747 if (PredCond.first)
8748 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
8749 PredCond.second);
8750 return std::nullopt;
8751}
8752
8754 APInt &Upper, const InstrInfoQuery &IIQ,
8755 bool PreferSignedRange) {
8756 unsigned Width = Lower.getBitWidth();
8757 const APInt *C;
8758 switch (BO.getOpcode()) {
8759 case Instruction::Sub:
8760 if (match(BO.getOperand(0), m_APInt(C))) {
8761 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
8762 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
8763
8764 // If the caller expects a signed compare, then try to use a signed range.
8765 // Otherwise if both no-wraps are set, use the unsigned range because it
8766 // is never larger than the signed range. Example:
8767 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
8768 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
8769 if (PreferSignedRange && HasNSW && HasNUW)
8770 HasNUW = false;
8771
8772 if (HasNUW) {
8773 // 'sub nuw c, x' produces [0, C].
8774 Upper = *C + 1;
8775 } else if (HasNSW) {
8776 if (C->isNegative()) {
8777 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
8779 Upper = *C - APInt::getSignedMaxValue(Width);
8780 } else {
8781 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
8782 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
8783 Lower = *C - APInt::getSignedMaxValue(Width);
8785 }
8786 }
8787 }
8788 break;
8789 case Instruction::Add:
8790 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
8791 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
8792 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
8793
8794 // If the caller expects a signed compare, then try to use a signed
8795 // range. Otherwise if both no-wraps are set, use the unsigned range
8796 // because it is never larger than the signed range. Example: "add nuw
8797 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
8798 if (PreferSignedRange && HasNSW && HasNUW)
8799 HasNUW = false;
8800
8801 if (HasNUW) {
8802 // 'add nuw x, C' produces [C, UINT_MAX].
8803 Lower = *C;
8804 } else if (HasNSW) {
8805 if (C->isNegative()) {
8806 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
8808 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
8809 } else {
8810 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
8811 Lower = APInt::getSignedMinValue(Width) + *C;
8812 Upper = APInt::getSignedMaxValue(Width) + 1;
8813 }
8814 }
8815 }
8816 break;
8817
8818 case Instruction::And:
8819 if (match(BO.getOperand(1), m_APInt(C)))
8820 // 'and x, C' produces [0, C].
8821 Upper = *C + 1;
8822 // X & -X is a power of two or zero. So we can cap the value at max power of
8823 // two.
8824 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
8825 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
8826 Upper = APInt::getSignedMinValue(Width) + 1;
8827 break;
8828
8829 case Instruction::Or:
8830 if (match(BO.getOperand(1), m_APInt(C)))
8831 // 'or x, C' produces [C, UINT_MAX].
8832 Lower = *C;
8833 break;
8834
8835 case Instruction::AShr:
8836 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
8837 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
8839 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
8840 } else if (match(BO.getOperand(0), m_APInt(C))) {
8841 unsigned ShiftAmount = Width - 1;
8842 if (!C->isZero() && IIQ.isExact(&BO))
8843 ShiftAmount = C->countr_zero();
8844 if (C->isNegative()) {
8845 // 'ashr C, x' produces [C, C >> (Width-1)]
8846 Lower = *C;
8847 Upper = C->ashr(ShiftAmount) + 1;
8848 } else {
8849 // 'ashr C, x' produces [C >> (Width-1), C]
8850 Lower = C->ashr(ShiftAmount);
8851 Upper = *C + 1;
8852 }
8853 }
8854 break;
8855
8856 case Instruction::LShr:
8857 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
8858 // 'lshr x, C' produces [0, UINT_MAX >> C].
8859 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
8860 } else if (match(BO.getOperand(0), m_APInt(C))) {
8861 // 'lshr C, x' produces [C >> (Width-1), C].
8862 unsigned ShiftAmount = Width - 1;
8863 if (!C->isZero() && IIQ.isExact(&BO))
8864 ShiftAmount = C->countr_zero();
8865 Lower = C->lshr(ShiftAmount);
8866 Upper = *C + 1;
8867 }
8868 break;
8869
8870 case Instruction::Shl:
8871 if (match(BO.getOperand(0), m_APInt(C))) {
8872 if (IIQ.hasNoUnsignedWrap(&BO)) {
8873 // 'shl nuw C, x' produces [C, C << CLZ(C)]
8874 Lower = *C;
8875 Upper = Lower.shl(Lower.countl_zero()) + 1;
8876 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
8877 if (C->isNegative()) {
8878 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
8879 unsigned ShiftAmount = C->countl_one() - 1;
8880 Lower = C->shl(ShiftAmount);
8881 Upper = *C + 1;
8882 } else {
8883 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
8884 unsigned ShiftAmount = C->countl_zero() - 1;
8885 Lower = *C;
8886 Upper = C->shl(ShiftAmount) + 1;
8887 }
8888 } else {
8889 // If lowbit is set, value can never be zero.
8890 if ((*C)[0])
8891 Lower = APInt::getOneBitSet(Width, 0);
8892 // If we are shifting a constant the largest it can be is if the longest
8893 // sequence of consecutive ones is shifted to the highbits (breaking
8894 // ties for which sequence is higher). At the moment we take a liberal
8895 // upper bound on this by just popcounting the constant.
8896 // TODO: There may be a bitwise trick for it longest/highest
8897 // consecutative sequence of ones (naive method is O(Width) loop).
8898 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
8899 }
8900 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
8901 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
8902 }
8903 break;
8904
8905 case Instruction::SDiv:
8906 if (match(BO.getOperand(1), m_APInt(C))) {
8907 APInt IntMin = APInt::getSignedMinValue(Width);
8908 APInt IntMax = APInt::getSignedMaxValue(Width);
8909 if (C->isAllOnes()) {
8910 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
8911 // where C != -1 and C != 0 and C != 1
8912 Lower = IntMin + 1;
8913 Upper = IntMax + 1;
8914 } else if (C->countl_zero() < Width - 1) {
8915 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
8916 // where C != -1 and C != 0 and C != 1
8917 Lower = IntMin.sdiv(*C);
8918 Upper = IntMax.sdiv(*C);
8919 if (Lower.sgt(Upper))
8921 Upper = Upper + 1;
8922 assert(Upper != Lower && "Upper part of range has wrapped!");
8923 }
8924 } else if (match(BO.getOperand(0), m_APInt(C))) {
8925 if (C->isMinSignedValue()) {
8926 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
8927 Lower = *C;
8928 Upper = Lower.lshr(1) + 1;
8929 } else {
8930 // 'sdiv C, x' produces [-|C|, |C|].
8931 Upper = C->abs() + 1;
8932 Lower = (-Upper) + 1;
8933 }
8934 }
8935 break;
8936
8937 case Instruction::UDiv:
8938 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
8939 // 'udiv x, C' produces [0, UINT_MAX / C].
8940 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
8941 } else if (match(BO.getOperand(0), m_APInt(C))) {
8942 // 'udiv C, x' produces [0, C].
8943 Upper = *C + 1;
8944 }
8945 break;
8946
8947 case Instruction::SRem:
8948 if (match(BO.getOperand(1), m_APInt(C))) {
8949 // 'srem x, C' produces (-|C|, |C|).
8950 Upper = C->abs();
8951 Lower = (-Upper) + 1;
8952 } else if (match(BO.getOperand(0), m_APInt(C))) {
8953 if (C->isNegative()) {
8954 // 'srem -|C|, x' produces [-|C|, 0].
8955 Upper = 1;
8956 Lower = *C;
8957 } else {
8958 // 'srem |C|, x' produces [0, |C|].
8959 Upper = *C + 1;
8960 }
8961 }
8962 break;
8963
8964 case Instruction::URem:
8965 if (match(BO.getOperand(1), m_APInt(C)))
8966 // 'urem x, C' produces [0, C).
8967 Upper = *C;
8968 else if (match(BO.getOperand(0), m_APInt(C)))
8969 // 'urem C, x' produces [0, C].
8970 Upper = *C + 1;
8971 break;
8972
8973 default:
8974 break;
8975 }
8976}
8977
8979 bool UseInstrInfo) {
8980 unsigned Width = II.getType()->getScalarSizeInBits();
8981 const APInt *C;
8982 switch (II.getIntrinsicID()) {
8983 case Intrinsic::ctlz:
8984 case Intrinsic::cttz: {
8985 APInt Upper(Width, Width);
8986 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
8987 Upper += 1;
8988 // Maximum of set/clear bits is the bit width.
8990 }
8991 case Intrinsic::ctpop:
8992 // Maximum of set/clear bits is the bit width.
8994 APInt(Width, Width) + 1);
8995 case Intrinsic::uadd_sat:
8996 // uadd.sat(x, C) produces [C, UINT_MAX].
8997 if (match(II.getOperand(0), m_APInt(C)) ||
8998 match(II.getOperand(1), m_APInt(C)))
9000 break;
9001 case Intrinsic::sadd_sat:
9002 if (match(II.getOperand(0), m_APInt(C)) ||
9003 match(II.getOperand(1), m_APInt(C))) {
9004 if (C->isNegative())
9005 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
9007 APInt::getSignedMaxValue(Width) + *C +
9008 1);
9009
9010 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
9012 APInt::getSignedMaxValue(Width) + 1);
9013 }
9014 break;
9015 case Intrinsic::usub_sat:
9016 // usub.sat(C, x) produces [0, C].
9017 if (match(II.getOperand(0), m_APInt(C)))
9018 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
9019
9020 // usub.sat(x, C) produces [0, UINT_MAX - C].
9021 if (match(II.getOperand(1), m_APInt(C)))
9023 APInt::getMaxValue(Width) - *C + 1);
9024 break;
9025 case Intrinsic::ssub_sat:
9026 if (match(II.getOperand(0), m_APInt(C))) {
9027 if (C->isNegative())
9028 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
9030 *C - APInt::getSignedMinValue(Width) +
9031 1);
9032
9033 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
9035 APInt::getSignedMaxValue(Width) + 1);
9036 } else if (match(II.getOperand(1), m_APInt(C))) {
9037 if (C->isNegative())
9038 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
9040 APInt::getSignedMaxValue(Width) + 1);
9041
9042 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
9044 APInt::getSignedMaxValue(Width) - *C +
9045 1);
9046 }
9047 break;
9048 case Intrinsic::ushl_sat:
9049 if (match(II.getOperand(0), m_APInt(C)))
9051 break;
9052 case Intrinsic::sshl_sat:
9053 if (match(II.getOperand(0), m_APInt(C))) {
9054 if (C->isNegative())
9056 *C + 1);
9058 APInt::getSignedMaxValue(Width) + 1);
9059 }
9060 break;
9061 case Intrinsic::umin:
9062 case Intrinsic::umax:
9063 case Intrinsic::smin:
9064 case Intrinsic::smax:
9065 if (!match(II.getOperand(0), m_APInt(C)) &&
9066 !match(II.getOperand(1), m_APInt(C)))
9067 break;
9068
9069 switch (II.getIntrinsicID()) {
9070 case Intrinsic::umin:
9071 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
9072 case Intrinsic::umax:
9074 case Intrinsic::smin:
9076 *C + 1);
9077 case Intrinsic::smax:
9079 APInt::getSignedMaxValue(Width) + 1);
9080 default:
9081 llvm_unreachable("Must be min/max intrinsic");
9082 }
9083 break;
9084 case Intrinsic::abs:
9085 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
9086 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
9087 if (match(II.getOperand(1), m_One()))
9089 APInt::getSignedMaxValue(Width) + 1);
9090
9092 APInt::getSignedMinValue(Width) + 1);
9093 case Intrinsic::vscale:
9094 if (!II.getParent() || !II.getFunction())
9095 break;
9096 return getVScaleRange(II.getFunction(), Width);
9097 case Intrinsic::read_register:
9098 case Intrinsic::read_volatile_register: {
9099 const Module *M = II.getModule();
9100 if (!M || !M->getTargetTriple().isRISCV())
9101 break;
9102 if (II.getFunction() && isReadVLENB(II))
9103 return getRISCVVLENBRange(II, Width);
9104 break;
9105 }
9106 default:
9107 break;
9108 }
9109
9110 return ConstantRange::getFull(Width);
9111}
9112
9114 const InstrInfoQuery &IIQ) {
9115 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
9116 const Value *LHS = nullptr, *RHS = nullptr;
9118 if (R.Flavor == SPF_UNKNOWN)
9119 return ConstantRange::getFull(BitWidth);
9120
9121 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
9122 // If the negation part of the abs (in RHS) has the NSW flag,
9123 // then the result of abs(X) is [0..SIGNED_MAX],
9124 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
9125 if (match(RHS, m_Neg(m_Specific(LHS))) &&
9129
9132 }
9133
9134 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
9135 // The result of -abs(X) is <= 0.
9137 APInt(BitWidth, 1));
9138 }
9139
9140 const APInt *C;
9141 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
9142 return ConstantRange::getFull(BitWidth);
9143
9144 switch (R.Flavor) {
9145 case SPF_UMIN:
9147 case SPF_UMAX:
9149 case SPF_SMIN:
9151 *C + 1);
9152 case SPF_SMAX:
9155 default:
9156 return ConstantRange::getFull(BitWidth);
9157 }
9158}
9159
9161 // The maximum representable value of a half is 65504. For floats the maximum
9162 // value is 3.4e38 which requires roughly 129 bits.
9163 unsigned BitWidth = I->getType()->getScalarSizeInBits();
9164 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
9165 return;
9166 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
9167 Lower = APInt(BitWidth, -65504, true);
9168 Upper = APInt(BitWidth, 65505);
9169 }
9170
9171 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
9172 // For a fptoui the lower limit is left as 0.
9173 Upper = APInt(BitWidth, 65505);
9174 }
9175}
9176
9178 const SimplifyQuery &SQ,
9179 unsigned Depth) {
9180 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
9181
9183 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
9184
9185 if (auto *C = dyn_cast<Constant>(V))
9186 return C->toConstantRange();
9187
9188 unsigned BitWidth = V->getType()->getScalarSizeInBits();
9189 ConstantRange CR = ConstantRange::getFull(BitWidth);
9190 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
9191 APInt Lower = APInt(BitWidth, 0);
9192 APInt Upper = APInt(BitWidth, 0);
9193 // TODO: Return ConstantRange.
9194 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
9196 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
9198 else if (auto *SI = dyn_cast<SelectInst>(V)) {
9199 ConstantRange CRTrue =
9200 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
9201 ConstantRange CRFalse =
9202 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
9203 CR = CRTrue.unionWith(CRFalse, ForSigned ? ConstantRange::Signed
9206 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
9207 ConstantRange SrcCR =
9208 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
9209 CR = SrcCR.truncate(BitWidth);
9210 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
9211 ConstantRange SrcCR =
9212 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
9213 CR = SrcCR.zeroExtend(BitWidth);
9214 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
9215 ConstantRange SrcCR =
9216 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
9217 CR = SrcCR.signExtend(BitWidth);
9218 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
9219 APInt Lower = APInt(BitWidth, 0);
9220 APInt Upper = APInt(BitWidth, 0);
9221 // TODO: Return ConstantRange.
9224 } else if (const auto *A = dyn_cast<Argument>(V))
9225 if (std::optional<ConstantRange> Range = A->getRange())
9226 CR = *Range;
9227
9228 if (auto *I = dyn_cast<Instruction>(V)) {
9229 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
9231
9232 Value *FrexpSrc;
9233 if (const auto *CB = dyn_cast<CallBase>(V)) {
9234 if (std::optional<ConstantRange> Range = CB->getRange())
9235 CR = CR.intersectWith(*Range);
9237 m_Value(FrexpSrc))))) {
9238 const fltSemantics &FltSem =
9239 FrexpSrc->getType()->getScalarType()->getFltSemantics();
9240 // It should be possible to implement this for any type, but this logic
9241 // only computes the range assuming standard subnormal handling.
9242 if (APFloat::isIEEELikeFP(FltSem)) {
9244 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
9245
9246 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
9247 // constrain its range when the source can be neither.
9248 if (KnownSrc.isKnownNeverInfOrNaN()) {
9249 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
9250
9251 // Offset to find the true minimum exponent value for a denormal.
9252 if (!KnownSrc.isKnownNeverSubnormal())
9253 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
9254
9255 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
9256
9257 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
9259
9260 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
9261 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
9262
9263 MinExp = std::max(AdjustedMin, MinExp);
9264 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
9265 MaxExp);
9266
9268 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
9269 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
9270 /*isSigned=*/true));
9271 }
9272 }
9273 }
9274 }
9275
9276 if (SQ.CtxI && SQ.AC) {
9277 // Try to restrict the range based on information from assumptions.
9278 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
9279 if (!AssumeVH)
9280 continue;
9281 CallInst *I = cast<CallInst>(AssumeVH);
9282 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
9283 "Got assumption for the wrong function!");
9284 assert(I->getIntrinsicID() == Intrinsic::assume &&
9285 "must be an assume intrinsic");
9286
9287 if (AssumeVH.Index != AssumptionCache::ExprResultIdx) {
9288 auto OBU = I->getOperandBundleAt(AssumeVH.Index);
9289 if (getBundleAttrFromOBU(OBU) == BundleAttr::Range) {
9290 auto [Val, Range] = getAssumeRangeInfo(OBU);
9291 if (Val == V && isValidAssumeForContext(I, SQ))
9292 CR = CR.intersectWith(Range);
9293 }
9294 continue;
9295 }
9296
9297 if (!isValidAssumeForContext(I, SQ))
9298 continue;
9299 Value *Arg = I->getArgOperand(0);
9300 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
9301 // Currently we just use information from comparisons.
9302 if (!Cmp || Cmp->getOperand(0) != V)
9303 continue;
9304 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
9305 ConstantRange RHS =
9306 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
9307 SQ.getWithInstruction(I), Depth + 1);
9308 CR = CR.intersectWith(
9309 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
9310 }
9311 }
9312
9313 return CR;
9314}
9315
9316static void
9318 function_ref<void(Value *)> InsertAffected) {
9319 assert(V != nullptr);
9320 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
9321 InsertAffected(V);
9322 } else if (auto *I = dyn_cast<Instruction>(V)) {
9323 InsertAffected(V);
9324
9325 // Peek through unary operators to find the source of the condition.
9326 Value *Op;
9328 m_Trunc(m_Value(Op))))) {
9330 InsertAffected(Op);
9331 }
9332 }
9333}
9334
9336 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
9337 auto AddAffected = [&InsertAffected](Value *V) {
9338 addValueAffectedByCondition(V, InsertAffected);
9339 };
9340
9341 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
9342 if (IsAssume) {
9343 AddAffected(LHS);
9344 AddAffected(RHS);
9345 } else if (match(RHS, m_Constant()))
9346 AddAffected(LHS);
9347 };
9348
9349 SmallVector<Value *, 8> Worklist;
9351 Worklist.push_back(Cond);
9352 while (!Worklist.empty()) {
9353 Value *V = Worklist.pop_back_val();
9354 if (!Visited.insert(V).second)
9355 continue;
9356
9357 CmpPredicate Pred;
9358 Value *A, *B, *X;
9359
9360 if (IsAssume) {
9361 AddAffected(V);
9362 if (match(V, m_Not(m_Value(X))))
9363 AddAffected(X);
9364 }
9365
9366 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
9367 // assume(A && B) is split to -> assume(A); assume(B);
9368 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
9369 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
9370 // enough information to be worth handling (intersection of information as
9371 // opposed to union).
9372 if (!IsAssume) {
9373 Worklist.push_back(A);
9374 Worklist.push_back(B);
9375 }
9376 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
9377 bool HasRHSC = match(B, m_ConstantInt());
9378 if (ICmpInst::isEquality(Pred)) {
9379 AddAffected(A);
9380 if (IsAssume)
9381 AddAffected(B);
9382
9383 // If the remainder is zero, then the division is exact.
9384 Value *RemLHS, *RemRHS;
9385 if (match(B, m_Zero()) &&
9386 match(A, m_IRem(m_Value(RemLHS), m_Value(RemRHS)))) {
9387 AddAffected(RemLHS);
9388 AddAffected(RemRHS);
9389 }
9390
9391 if (HasRHSC) {
9392 Value *Y;
9393 // (X << C) or (X >>_s C) or (X >>_u C).
9394 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
9395 AddAffected(X);
9396 // (X & C) or (X | C).
9397 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
9398 match(A, m_Or(m_Value(X), m_Value(Y)))) {
9399 AddAffected(X);
9400 AddAffected(Y);
9401 }
9402 // X - Y
9403 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
9404 AddAffected(X);
9405 AddAffected(Y);
9406 }
9407 }
9408 } else {
9409 AddCmpOperands(A, B);
9410 if (HasRHSC) {
9411 Value *Y;
9412 // Handle (A + C1) u< C2, which is the canonical form of
9413 // A > C3 && A < C4.
9415 AddAffected(X);
9416 // X - Y pred C, which implies X != Y if 0 pred C is false.
9417 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
9418 AddAffected(X);
9419 AddAffected(Y);
9420 }
9421
9422 if (ICmpInst::isUnsigned(Pred)) {
9423 // X & Y u> C -> X >u C && Y >u C
9424 // X | Y u< C -> X u< C && Y u< C
9425 // X nuw+ Y u< C -> X u< C && Y u< C
9426 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
9427 match(A, m_Or(m_Value(X), m_Value(Y))) ||
9428 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
9429 AddAffected(X);
9430 AddAffected(Y);
9431 }
9432 }
9433 if (ICmpInst::isSigned(Pred)) {
9434 // X | Y s> -1 -> X s> -1 && Y s> -1
9435 Value *Y = nullptr;
9436 if (match(B, m_AllOnes()) &&
9437 match(A, m_Or(m_Value(X), m_Value(Y)))) {
9438 AddAffected(X);
9439 AddAffected(Y);
9440 }
9441 // X & Y s< 0 -> X s< 0 && Y s< 0
9442 if (match(B, m_Zero()) && match(A, m_And(m_Value(X), m_Value(Y)))) {
9443 AddAffected(X);
9444 AddAffected(Y);
9445 }
9446 }
9447 }
9448
9449 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
9450 // by computeKnownFPClass().
9452 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
9453 InsertAffected(X);
9454 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
9455 InsertAffected(X);
9456 }
9457 }
9458
9459 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
9460 Value *SquareOp = nullptr;
9461 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
9462 AddAffected(SquareOp);
9463 };
9464 AddNuwSquareOperand(A);
9465 AddNuwSquareOperand(B);
9466
9467 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
9468 AddAffected(X);
9469 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
9470 AddCmpOperands(A, B);
9471
9472 // fcmp fneg(x), y
9473 // fcmp fabs(x), y
9474 // fcmp fneg(fabs(x)), y
9475 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
9477 AddAffected(A);
9478 if (match(A, m_FAbs(m_Value(A))))
9479 AddAffected(A);
9480
9482 m_Value()))) {
9483 // Handle patterns that computeKnownFPClass() support.
9484 AddAffected(A);
9485 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
9486 // Assume is checked here as X is already added above for assumes in
9487 // addValueAffectedByCondition
9488 AddAffected(X);
9489 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
9490 // Assume is checked here to avoid issues with ephemeral values
9491 Worklist.push_back(X);
9492 }
9493 }
9494}
9495
9497 // (X >> C) or/add (X & mask(C) != 0)
9498 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
9499 if (BO->getOpcode() == Instruction::Add ||
9500 BO->getOpcode() == Instruction::Or) {
9501 const Value *X;
9502 const APInt *C1, *C2;
9503 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
9507 m_Zero())))) &&
9508 C2->popcount() == C1->getZExtValue())
9509 return X;
9510 }
9511 }
9512
9513 // select(cond, X, -X)
9514 {
9515 const Value *X;
9516 if (match(V, m_c_Select(m_Value(X), m_Neg(m_Deferred(X)))))
9517 return X;
9518 }
9519
9520 return nullptr;
9521}
9522
9524 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
9525}
9526
9529 unsigned MaxCount, bool AllowUndefOrPoison) {
9532 auto Push = [&](const Value *V) -> bool {
9533 Constant *C;
9534 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
9535 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
9536 return false;
9537 // Check existence first to avoid unnecessary allocations.
9538 if (Constants.contains(C))
9539 return true;
9540 if (Constants.size() == MaxCount)
9541 return false;
9542 Constants.insert(C);
9543 return true;
9544 }
9545
9546 if (auto *Inst = dyn_cast<Instruction>(V)) {
9547 if (Visited.insert(Inst).second)
9548 Worklist.push_back(Inst);
9549 return true;
9550 }
9551 return false;
9552 };
9553 if (!Push(V))
9554 return false;
9555 while (!Worklist.empty()) {
9556 const Instruction *CurInst = Worklist.pop_back_val();
9557 switch (CurInst->getOpcode()) {
9558 case Instruction::Select:
9559 if (!Push(CurInst->getOperand(1)))
9560 return false;
9561 if (!Push(CurInst->getOperand(2)))
9562 return false;
9563 break;
9564 case Instruction::PHI:
9565 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
9566 // Fast path for recurrence PHI.
9567 if (IncomingValue == CurInst)
9568 continue;
9569 if (!Push(IncomingValue))
9570 return false;
9571 }
9572 break;
9573 default:
9574 return false;
9575 }
9576 }
9577 return true;
9578}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define RegName(no)
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
if(PassOpts->AAPipeline)
R600 Clause Merge
int64_t C1
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static const Instruction * safeCtxI(const Value *V, const Instruction *CtxI)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static bool isNonZeroAddrPlusOffset(const SimplifyQuery &Q, Value *X, Value *Y)
Return true if "addr(P) + Off" cannot be zero.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void computeKnownBitsFromEuclideanRem(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Infer non-negativity for R + (R < 0 ?
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static bool hasNoFreeInRange(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, unsigned &NumChecked)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static ConstantRange getRISCVVLENBRange(const IntrinsicInst &II, unsigned Width)
Return the value range of a RISC-V vlenb CSR read.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match non-obvious integer minimum and maximum sequences.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static unsigned computeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:617
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:613
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:609
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:650
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1687
bool isFinite() const
Definition APFloat.h:1621
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2018
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1411
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition APInt.h:1405
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1253
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:170
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:219
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:520
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:793
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:803
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI bool isAbsoluteSymbolRef() const
Returns whether this is a reference to an absolute symbol.
Definition Globals.cpp:526
bool hasExternalWeakLinkage() const
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
bool isKnownNever(FPClassMask Mask) const
Return true if it's known this can never be one of the mask entries.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1087
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:589
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:745
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3052
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
static constexpr unsigned RVVBytesPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:680
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:453
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const SimplifyQuery &SQ, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1740
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI bool isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
@ Off
Use window algorithm after SMS algorithm fails.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:247
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI AssumeRangeInfo getAssumeRangeInfo(OperandBundleUse)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI unsigned computeNumSignBits(const Value *Op, const SimplifyQuery &Q, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
Choose the value to analyze for the incoming use U of PHI, avoiding recursion back into PHI.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
LLVM_ABI KnownBits ctlz(bool ZeroIsPoison=false) const
Compute known bits for the count of leading zeros.
KnownBits byteSwap() const
Definition KnownBits.h:562
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:566
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:62
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const Instruction * CtxI
const Function * getFunction() const
const InstrInfoQuery IIQ
const CondContext * CC