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 14 #include "llvm/Analysis/ValueTracking.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/ADT/iterator_range.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/AssumeBundleQueries.h" 28 #include "llvm/Analysis/AssumptionCache.h" 29 #include "llvm/Analysis/EHPersonalities.h" 30 #include "llvm/Analysis/GuardUtils.h" 31 #include "llvm/Analysis/InstructionSimplify.h" 32 #include "llvm/Analysis/Loads.h" 33 #include "llvm/Analysis/LoopInfo.h" 34 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/IR/Argument.h" 37 #include "llvm/IR/Attributes.h" 38 #include "llvm/IR/BasicBlock.h" 39 #include "llvm/IR/Constant.h" 40 #include "llvm/IR/ConstantRange.h" 41 #include "llvm/IR/Constants.h" 42 #include "llvm/IR/DerivedTypes.h" 43 #include "llvm/IR/DiagnosticInfo.h" 44 #include "llvm/IR/Dominators.h" 45 #include "llvm/IR/Function.h" 46 #include "llvm/IR/GetElementPtrTypeIterator.h" 47 #include "llvm/IR/GlobalAlias.h" 48 #include "llvm/IR/GlobalValue.h" 49 #include "llvm/IR/GlobalVariable.h" 50 #include "llvm/IR/InstrTypes.h" 51 #include "llvm/IR/Instruction.h" 52 #include "llvm/IR/Instructions.h" 53 #include "llvm/IR/IntrinsicInst.h" 54 #include "llvm/IR/Intrinsics.h" 55 #include "llvm/IR/IntrinsicsAArch64.h" 56 #include "llvm/IR/IntrinsicsRISCV.h" 57 #include "llvm/IR/IntrinsicsX86.h" 58 #include "llvm/IR/LLVMContext.h" 59 #include "llvm/IR/Metadata.h" 60 #include "llvm/IR/Module.h" 61 #include "llvm/IR/Operator.h" 62 #include "llvm/IR/PatternMatch.h" 63 #include "llvm/IR/Type.h" 64 #include "llvm/IR/User.h" 65 #include "llvm/IR/Value.h" 66 #include "llvm/Support/Casting.h" 67 #include "llvm/Support/CommandLine.h" 68 #include "llvm/Support/Compiler.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/KnownBits.h" 71 #include "llvm/Support/MathExtras.h" 72 #include <algorithm> 73 #include <array> 74 #include <cassert> 75 #include <cstdint> 76 #include <iterator> 77 #include <utility> 78 79 using namespace llvm; 80 using namespace llvm::PatternMatch; 81 82 // Controls the number of uses of the value searched for possible 83 // dominating comparisons. 84 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses", 85 cl::Hidden, cl::init(20)); 86 87 /// Returns the bitwidth of the given scalar or pointer type. For vector types, 88 /// returns the element type's bitwidth. 89 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) { 90 if (unsigned BitWidth = Ty->getScalarSizeInBits()) 91 return BitWidth; 92 93 return DL.getPointerTypeSizeInBits(Ty); 94 } 95 96 namespace { 97 98 // Simplifying using an assume can only be done in a particular control-flow 99 // context (the context instruction provides that context). If an assume and 100 // the context instruction are not in the same block then the DT helps in 101 // figuring out if we can use it. 102 struct Query { 103 const DataLayout &DL; 104 AssumptionCache *AC; 105 const Instruction *CxtI; 106 const DominatorTree *DT; 107 108 // Unlike the other analyses, this may be a nullptr because not all clients 109 // provide it currently. 110 OptimizationRemarkEmitter *ORE; 111 112 /// If true, it is safe to use metadata during simplification. 113 InstrInfoQuery IIQ; 114 115 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, 116 const DominatorTree *DT, bool UseInstrInfo, 117 OptimizationRemarkEmitter *ORE = nullptr) 118 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {} 119 }; 120 121 } // end anonymous namespace 122 123 // Given the provided Value and, potentially, a context instruction, return 124 // the preferred context instruction (if any). 125 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) { 126 // If we've been provided with a context instruction, then use that (provided 127 // it has been inserted). 128 if (CxtI && CxtI->getParent()) 129 return CxtI; 130 131 // If the value is really an already-inserted instruction, then use that. 132 CxtI = dyn_cast<Instruction>(V); 133 if (CxtI && CxtI->getParent()) 134 return CxtI; 135 136 return nullptr; 137 } 138 139 static const Instruction *safeCxtI(const Value *V1, const Value *V2, const Instruction *CxtI) { 140 // If we've been provided with a context instruction, then use that (provided 141 // it has been inserted). 142 if (CxtI && CxtI->getParent()) 143 return CxtI; 144 145 // If the value is really an already-inserted instruction, then use that. 146 CxtI = dyn_cast<Instruction>(V1); 147 if (CxtI && CxtI->getParent()) 148 return CxtI; 149 150 CxtI = dyn_cast<Instruction>(V2); 151 if (CxtI && CxtI->getParent()) 152 return CxtI; 153 154 return nullptr; 155 } 156 157 static bool getShuffleDemandedElts(const ShuffleVectorInst *Shuf, 158 const APInt &DemandedElts, 159 APInt &DemandedLHS, APInt &DemandedRHS) { 160 // The length of scalable vectors is unknown at compile time, thus we 161 // cannot check their values 162 if (isa<ScalableVectorType>(Shuf->getType())) 163 return false; 164 165 int NumElts = 166 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements(); 167 int NumMaskElts = cast<FixedVectorType>(Shuf->getType())->getNumElements(); 168 DemandedLHS = DemandedRHS = APInt::getZero(NumElts); 169 if (DemandedElts.isZero()) 170 return true; 171 // Simple case of a shuffle with zeroinitializer. 172 if (all_of(Shuf->getShuffleMask(), [](int Elt) { return Elt == 0; })) { 173 DemandedLHS.setBit(0); 174 return true; 175 } 176 for (int i = 0; i != NumMaskElts; ++i) { 177 if (!DemandedElts[i]) 178 continue; 179 int M = Shuf->getMaskValue(i); 180 assert(M < (NumElts * 2) && "Invalid shuffle mask constant"); 181 182 // For undef elements, we don't know anything about the common state of 183 // the shuffle result. 184 if (M == -1) 185 return false; 186 if (M < NumElts) 187 DemandedLHS.setBit(M % NumElts); 188 else 189 DemandedRHS.setBit(M % NumElts); 190 } 191 192 return true; 193 } 194 195 static void computeKnownBits(const Value *V, const APInt &DemandedElts, 196 KnownBits &Known, unsigned Depth, const Query &Q); 197 198 static void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, 199 const Query &Q) { 200 // FIXME: We currently have no way to represent the DemandedElts of a scalable 201 // vector 202 if (isa<ScalableVectorType>(V->getType())) { 203 Known.resetAll(); 204 return; 205 } 206 207 auto *FVTy = dyn_cast<FixedVectorType>(V->getType()); 208 APInt DemandedElts = 209 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1); 210 computeKnownBits(V, DemandedElts, Known, Depth, Q); 211 } 212 213 void llvm::computeKnownBits(const Value *V, KnownBits &Known, 214 const DataLayout &DL, unsigned Depth, 215 AssumptionCache *AC, const Instruction *CxtI, 216 const DominatorTree *DT, 217 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) { 218 ::computeKnownBits(V, Known, Depth, 219 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE)); 220 } 221 222 void llvm::computeKnownBits(const Value *V, const APInt &DemandedElts, 223 KnownBits &Known, const DataLayout &DL, 224 unsigned Depth, AssumptionCache *AC, 225 const Instruction *CxtI, const DominatorTree *DT, 226 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) { 227 ::computeKnownBits(V, DemandedElts, Known, Depth, 228 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE)); 229 } 230 231 static KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts, 232 unsigned Depth, const Query &Q); 233 234 static KnownBits computeKnownBits(const Value *V, unsigned Depth, 235 const Query &Q); 236 237 KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL, 238 unsigned Depth, AssumptionCache *AC, 239 const Instruction *CxtI, 240 const DominatorTree *DT, 241 OptimizationRemarkEmitter *ORE, 242 bool UseInstrInfo) { 243 return ::computeKnownBits( 244 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE)); 245 } 246 247 KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts, 248 const DataLayout &DL, unsigned Depth, 249 AssumptionCache *AC, const Instruction *CxtI, 250 const DominatorTree *DT, 251 OptimizationRemarkEmitter *ORE, 252 bool UseInstrInfo) { 253 return ::computeKnownBits( 254 V, DemandedElts, Depth, 255 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE)); 256 } 257 258 bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS, 259 const DataLayout &DL, AssumptionCache *AC, 260 const Instruction *CxtI, const DominatorTree *DT, 261 bool UseInstrInfo) { 262 assert(LHS->getType() == RHS->getType() && 263 "LHS and RHS should have the same type"); 264 assert(LHS->getType()->isIntOrIntVectorTy() && 265 "LHS and RHS should be integers"); 266 // Look for an inverted mask: (X & ~M) op (Y & M). 267 Value *M; 268 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) && 269 match(RHS, m_c_And(m_Specific(M), m_Value()))) 270 return true; 271 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) && 272 match(LHS, m_c_And(m_Specific(M), m_Value()))) 273 return true; 274 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType()); 275 KnownBits LHSKnown(IT->getBitWidth()); 276 KnownBits RHSKnown(IT->getBitWidth()); 277 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo); 278 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo); 279 return KnownBits::haveNoCommonBitsSet(LHSKnown, RHSKnown); 280 } 281 282 bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *I) { 283 return !I->user_empty() && all_of(I->users(), [](const User *U) { 284 ICmpInst::Predicate P; 285 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P); 286 }); 287 } 288 289 static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth, 290 const Query &Q); 291 292 bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, 293 bool OrZero, unsigned Depth, 294 AssumptionCache *AC, const Instruction *CxtI, 295 const DominatorTree *DT, bool UseInstrInfo) { 296 return ::isKnownToBeAPowerOfTwo( 297 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo)); 298 } 299 300 static bool isKnownNonZero(const Value *V, const APInt &DemandedElts, 301 unsigned Depth, const Query &Q); 302 303 static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q); 304 305 bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth, 306 AssumptionCache *AC, const Instruction *CxtI, 307 const DominatorTree *DT, bool UseInstrInfo) { 308 return ::isKnownNonZero(V, Depth, 309 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo)); 310 } 311 312 bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL, 313 unsigned Depth, AssumptionCache *AC, 314 const Instruction *CxtI, const DominatorTree *DT, 315 bool UseInstrInfo) { 316 KnownBits Known = 317 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo); 318 return Known.isNonNegative(); 319 } 320 321 bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth, 322 AssumptionCache *AC, const Instruction *CxtI, 323 const DominatorTree *DT, bool UseInstrInfo) { 324 if (auto *CI = dyn_cast<ConstantInt>(V)) 325 return CI->getValue().isStrictlyPositive(); 326 327 // TODO: We'd doing two recursive queries here. We should factor this such 328 // that only a single query is needed. 329 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) && 330 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo); 331 } 332 333 bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth, 334 AssumptionCache *AC, const Instruction *CxtI, 335 const DominatorTree *DT, bool UseInstrInfo) { 336 KnownBits Known = 337 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo); 338 return Known.isNegative(); 339 } 340 341 static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth, 342 const Query &Q); 343 344 bool llvm::isKnownNonEqual(const Value *V1, const Value *V2, 345 const DataLayout &DL, AssumptionCache *AC, 346 const Instruction *CxtI, const DominatorTree *DT, 347 bool UseInstrInfo) { 348 return ::isKnownNonEqual(V1, V2, 0, 349 Query(DL, AC, safeCxtI(V2, V1, CxtI), DT, 350 UseInstrInfo, /*ORE=*/nullptr)); 351 } 352 353 static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth, 354 const Query &Q); 355 356 bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask, 357 const DataLayout &DL, unsigned Depth, 358 AssumptionCache *AC, const Instruction *CxtI, 359 const DominatorTree *DT, bool UseInstrInfo) { 360 return ::MaskedValueIsZero( 361 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo)); 362 } 363 364 static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts, 365 unsigned Depth, const Query &Q); 366 367 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth, 368 const Query &Q) { 369 // FIXME: We currently have no way to represent the DemandedElts of a scalable 370 // vector 371 if (isa<ScalableVectorType>(V->getType())) 372 return 1; 373 374 auto *FVTy = dyn_cast<FixedVectorType>(V->getType()); 375 APInt DemandedElts = 376 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1); 377 return ComputeNumSignBits(V, DemandedElts, Depth, Q); 378 } 379 380 unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL, 381 unsigned Depth, AssumptionCache *AC, 382 const Instruction *CxtI, 383 const DominatorTree *DT, bool UseInstrInfo) { 384 return ::ComputeNumSignBits( 385 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo)); 386 } 387 388 static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, 389 bool NSW, const APInt &DemandedElts, 390 KnownBits &KnownOut, KnownBits &Known2, 391 unsigned Depth, const Query &Q) { 392 computeKnownBits(Op1, DemandedElts, KnownOut, Depth + 1, Q); 393 394 // If one operand is unknown and we have no nowrap information, 395 // the result will be unknown independently of the second operand. 396 if (KnownOut.isUnknown() && !NSW) 397 return; 398 399 computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q); 400 KnownOut = KnownBits::computeForAddSub(Add, NSW, Known2, KnownOut); 401 } 402 403 static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, 404 const APInt &DemandedElts, KnownBits &Known, 405 KnownBits &Known2, unsigned Depth, 406 const Query &Q) { 407 computeKnownBits(Op1, DemandedElts, Known, Depth + 1, Q); 408 computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q); 409 410 bool isKnownNegative = false; 411 bool isKnownNonNegative = false; 412 // If the multiplication is known not to overflow, compute the sign bit. 413 if (NSW) { 414 if (Op0 == Op1) { 415 // The product of a number with itself is non-negative. 416 isKnownNonNegative = true; 417 } else { 418 bool isKnownNonNegativeOp1 = Known.isNonNegative(); 419 bool isKnownNonNegativeOp0 = Known2.isNonNegative(); 420 bool isKnownNegativeOp1 = Known.isNegative(); 421 bool isKnownNegativeOp0 = Known2.isNegative(); 422 // The product of two numbers with the same sign is non-negative. 423 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) || 424 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0); 425 // The product of a negative number and a non-negative number is either 426 // negative or zero. 427 if (!isKnownNonNegative) 428 isKnownNegative = 429 (isKnownNegativeOp1 && isKnownNonNegativeOp0 && 430 Known2.isNonZero()) || 431 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero()); 432 } 433 } 434 435 Known = KnownBits::mul(Known, Known2); 436 437 // Only make use of no-wrap flags if we failed to compute the sign bit 438 // directly. This matters if the multiplication always overflows, in 439 // which case we prefer to follow the result of the direct computation, 440 // though as the program is invoking undefined behaviour we can choose 441 // whatever we like here. 442 if (isKnownNonNegative && !Known.isNegative()) 443 Known.makeNonNegative(); 444 else if (isKnownNegative && !Known.isNonNegative()) 445 Known.makeNegative(); 446 } 447 448 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges, 449 KnownBits &Known) { 450 unsigned BitWidth = Known.getBitWidth(); 451 unsigned NumRanges = Ranges.getNumOperands() / 2; 452 assert(NumRanges >= 1); 453 454 Known.Zero.setAllBits(); 455 Known.One.setAllBits(); 456 457 for (unsigned i = 0; i < NumRanges; ++i) { 458 ConstantInt *Lower = 459 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0)); 460 ConstantInt *Upper = 461 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1)); 462 ConstantRange Range(Lower->getValue(), Upper->getValue()); 463 464 // The first CommonPrefixBits of all values in Range are equal. 465 unsigned CommonPrefixBits = 466 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros(); 467 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits); 468 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth); 469 Known.One &= UnsignedMax & Mask; 470 Known.Zero &= ~UnsignedMax & Mask; 471 } 472 } 473 474 static bool isEphemeralValueOf(const Instruction *I, const Value *E) { 475 SmallVector<const Value *, 16> WorkSet(1, I); 476 SmallPtrSet<const Value *, 32> Visited; 477 SmallPtrSet<const Value *, 16> EphValues; 478 479 // The instruction defining an assumption's condition itself is always 480 // considered ephemeral to that assumption (even if it has other 481 // non-ephemeral users). See r246696's test case for an example. 482 if (is_contained(I->operands(), E)) 483 return true; 484 485 while (!WorkSet.empty()) { 486 const Value *V = WorkSet.pop_back_val(); 487 if (!Visited.insert(V).second) 488 continue; 489 490 // If all uses of this value are ephemeral, then so is this value. 491 if (llvm::all_of(V->users(), [&](const User *U) { 492 return EphValues.count(U); 493 })) { 494 if (V == E) 495 return true; 496 497 if (V == I || isSafeToSpeculativelyExecute(V)) { 498 EphValues.insert(V); 499 if (const User *U = dyn_cast<User>(V)) 500 append_range(WorkSet, U->operands()); 501 } 502 } 503 } 504 505 return false; 506 } 507 508 // Is this an intrinsic that cannot be speculated but also cannot trap? 509 bool llvm::isAssumeLikeIntrinsic(const Instruction *I) { 510 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I)) 511 return CI->isAssumeLikeIntrinsic(); 512 513 return false; 514 } 515 516 bool llvm::isValidAssumeForContext(const Instruction *Inv, 517 const Instruction *CxtI, 518 const DominatorTree *DT) { 519 // There are two restrictions on the use of an assume: 520 // 1. The assume must dominate the context (or the control flow must 521 // reach the assume whenever it reaches the context). 522 // 2. The context must not be in the assume's set of ephemeral values 523 // (otherwise we will use the assume to prove that the condition 524 // feeding the assume is trivially true, thus causing the removal of 525 // the assume). 526 527 if (Inv->getParent() == CxtI->getParent()) { 528 // If Inv and CtxI are in the same block, check if the assume (Inv) is first 529 // in the BB. 530 if (Inv->comesBefore(CxtI)) 531 return true; 532 533 // Don't let an assume affect itself - this would cause the problems 534 // `isEphemeralValueOf` is trying to prevent, and it would also make 535 // the loop below go out of bounds. 536 if (Inv == CxtI) 537 return false; 538 539 // The context comes first, but they're both in the same block. 540 // Make sure there is nothing in between that might interrupt 541 // the control flow, not even CxtI itself. 542 // We limit the scan distance between the assume and its context instruction 543 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so 544 // it can be adjusted if needed (could be turned into a cl::opt). 545 unsigned ScanLimit = 15; 546 for (BasicBlock::const_iterator I(CxtI), IE(Inv); I != IE; ++I) 547 if (!isGuaranteedToTransferExecutionToSuccessor(&*I) || --ScanLimit == 0) 548 return false; 549 550 return !isEphemeralValueOf(Inv, CxtI); 551 } 552 553 // Inv and CxtI are in different blocks. 554 if (DT) { 555 if (DT->dominates(Inv, CxtI)) 556 return true; 557 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) { 558 // We don't have a DT, but this trivially dominates. 559 return true; 560 } 561 562 return false; 563 } 564 565 static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) { 566 // v u> y implies v != 0. 567 if (Pred == ICmpInst::ICMP_UGT) 568 return true; 569 570 // Special-case v != 0 to also handle v != null. 571 if (Pred == ICmpInst::ICMP_NE) 572 return match(RHS, m_Zero()); 573 574 // All other predicates - rely on generic ConstantRange handling. 575 const APInt *C; 576 if (!match(RHS, m_APInt(C))) 577 return false; 578 579 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(Pred, *C); 580 return !TrueValues.contains(APInt::getZero(C->getBitWidth())); 581 } 582 583 static bool isKnownNonZeroFromAssume(const Value *V, const Query &Q) { 584 // Use of assumptions is context-sensitive. If we don't have a context, we 585 // cannot use them! 586 if (!Q.AC || !Q.CxtI) 587 return false; 588 589 if (Q.CxtI && V->getType()->isPointerTy()) { 590 SmallVector<Attribute::AttrKind, 2> AttrKinds{Attribute::NonNull}; 591 if (!NullPointerIsDefined(Q.CxtI->getFunction(), 592 V->getType()->getPointerAddressSpace())) 593 AttrKinds.push_back(Attribute::Dereferenceable); 594 595 if (getKnowledgeValidInContext(V, AttrKinds, Q.CxtI, Q.DT, Q.AC)) 596 return true; 597 } 598 599 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) { 600 if (!AssumeVH) 601 continue; 602 CallInst *I = cast<CallInst>(AssumeVH); 603 assert(I->getFunction() == Q.CxtI->getFunction() && 604 "Got assumption for the wrong function!"); 605 606 // Warning: This loop can end up being somewhat performance sensitive. 607 // We're running this loop for once for each value queried resulting in a 608 // runtime of ~O(#assumes * #values). 609 610 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && 611 "must be an assume intrinsic"); 612 613 Value *RHS; 614 CmpInst::Predicate Pred; 615 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V))); 616 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS)))) 617 return false; 618 619 if (cmpExcludesZero(Pred, RHS) && isValidAssumeForContext(I, Q.CxtI, Q.DT)) 620 return true; 621 } 622 623 return false; 624 } 625 626 static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known, 627 unsigned Depth, const Query &Q) { 628 // Use of assumptions is context-sensitive. If we don't have a context, we 629 // cannot use them! 630 if (!Q.AC || !Q.CxtI) 631 return; 632 633 unsigned BitWidth = Known.getBitWidth(); 634 635 // Refine Known set if the pointer alignment is set by assume bundles. 636 if (V->getType()->isPointerTy()) { 637 if (RetainedKnowledge RK = getKnowledgeValidInContext( 638 V, {Attribute::Alignment}, Q.CxtI, Q.DT, Q.AC)) { 639 Known.Zero.setLowBits(Log2_32(RK.ArgValue)); 640 } 641 } 642 643 // Note that the patterns below need to be kept in sync with the code 644 // in AssumptionCache::updateAffectedValues. 645 646 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) { 647 if (!AssumeVH) 648 continue; 649 CallInst *I = cast<CallInst>(AssumeVH); 650 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() && 651 "Got assumption for the wrong function!"); 652 653 // Warning: This loop can end up being somewhat performance sensitive. 654 // We're running this loop for once for each value queried resulting in a 655 // runtime of ~O(#assumes * #values). 656 657 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && 658 "must be an assume intrinsic"); 659 660 Value *Arg = I->getArgOperand(0); 661 662 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 663 assert(BitWidth == 1 && "assume operand is not i1?"); 664 Known.setAllOnes(); 665 return; 666 } 667 if (match(Arg, m_Not(m_Specific(V))) && 668 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 669 assert(BitWidth == 1 && "assume operand is not i1?"); 670 Known.setAllZero(); 671 return; 672 } 673 674 // The remaining tests are all recursive, so bail out if we hit the limit. 675 if (Depth == MaxAnalysisRecursionDepth) 676 continue; 677 678 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg); 679 if (!Cmp) 680 continue; 681 682 // We are attempting to compute known bits for the operands of an assume. 683 // Do not try to use other assumptions for those recursive calls because 684 // that can lead to mutual recursion and a compile-time explosion. 685 // An example of the mutual recursion: computeKnownBits can call 686 // isKnownNonZero which calls computeKnownBitsFromAssume (this function) 687 // and so on. 688 Query QueryNoAC = Q; 689 QueryNoAC.AC = nullptr; 690 691 // Note that ptrtoint may change the bitwidth. 692 Value *A, *B; 693 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V))); 694 695 CmpInst::Predicate Pred; 696 uint64_t C; 697 switch (Cmp->getPredicate()) { 698 default: 699 break; 700 case ICmpInst::ICMP_EQ: 701 // assume(v = a) 702 if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) && 703 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 704 KnownBits RHSKnown = 705 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 706 Known.Zero |= RHSKnown.Zero; 707 Known.One |= RHSKnown.One; 708 // assume(v & b = a) 709 } else if (match(Cmp, 710 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) && 711 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 712 KnownBits RHSKnown = 713 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 714 KnownBits MaskKnown = 715 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 716 717 // For those bits in the mask that are known to be one, we can propagate 718 // known bits from the RHS to V. 719 Known.Zero |= RHSKnown.Zero & MaskKnown.One; 720 Known.One |= RHSKnown.One & MaskKnown.One; 721 // assume(~(v & b) = a) 722 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))), 723 m_Value(A))) && 724 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 725 KnownBits RHSKnown = 726 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 727 KnownBits MaskKnown = 728 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 729 730 // For those bits in the mask that are known to be one, we can propagate 731 // inverted known bits from the RHS to V. 732 Known.Zero |= RHSKnown.One & MaskKnown.One; 733 Known.One |= RHSKnown.Zero & MaskKnown.One; 734 // assume(v | b = a) 735 } else if (match(Cmp, 736 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) && 737 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 738 KnownBits RHSKnown = 739 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 740 KnownBits BKnown = 741 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 742 743 // For those bits in B that are known to be zero, we can propagate known 744 // bits from the RHS to V. 745 Known.Zero |= RHSKnown.Zero & BKnown.Zero; 746 Known.One |= RHSKnown.One & BKnown.Zero; 747 // assume(~(v | b) = a) 748 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))), 749 m_Value(A))) && 750 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 751 KnownBits RHSKnown = 752 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 753 KnownBits BKnown = 754 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 755 756 // For those bits in B that are known to be zero, we can propagate 757 // inverted known bits from the RHS to V. 758 Known.Zero |= RHSKnown.One & BKnown.Zero; 759 Known.One |= RHSKnown.Zero & BKnown.Zero; 760 // assume(v ^ b = a) 761 } else if (match(Cmp, 762 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) && 763 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 764 KnownBits RHSKnown = 765 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 766 KnownBits BKnown = 767 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 768 769 // For those bits in B that are known to be zero, we can propagate known 770 // bits from the RHS to V. For those bits in B that are known to be one, 771 // we can propagate inverted known bits from the RHS to V. 772 Known.Zero |= RHSKnown.Zero & BKnown.Zero; 773 Known.One |= RHSKnown.One & BKnown.Zero; 774 Known.Zero |= RHSKnown.One & BKnown.One; 775 Known.One |= RHSKnown.Zero & BKnown.One; 776 // assume(~(v ^ b) = a) 777 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))), 778 m_Value(A))) && 779 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 780 KnownBits RHSKnown = 781 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 782 KnownBits BKnown = 783 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 784 785 // For those bits in B that are known to be zero, we can propagate 786 // inverted known bits from the RHS to V. For those bits in B that are 787 // known to be one, we can propagate known bits from the RHS to V. 788 Known.Zero |= RHSKnown.One & BKnown.Zero; 789 Known.One |= RHSKnown.Zero & BKnown.Zero; 790 Known.Zero |= RHSKnown.Zero & BKnown.One; 791 Known.One |= RHSKnown.One & BKnown.One; 792 // assume(v << c = a) 793 } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)), 794 m_Value(A))) && 795 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) { 796 KnownBits RHSKnown = 797 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 798 799 // For those bits in RHS that are known, we can propagate them to known 800 // bits in V shifted to the right by C. 801 RHSKnown.Zero.lshrInPlace(C); 802 Known.Zero |= RHSKnown.Zero; 803 RHSKnown.One.lshrInPlace(C); 804 Known.One |= RHSKnown.One; 805 // assume(~(v << c) = a) 806 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))), 807 m_Value(A))) && 808 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) { 809 KnownBits RHSKnown = 810 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 811 // For those bits in RHS that are known, we can propagate them inverted 812 // to known bits in V shifted to the right by C. 813 RHSKnown.One.lshrInPlace(C); 814 Known.Zero |= RHSKnown.One; 815 RHSKnown.Zero.lshrInPlace(C); 816 Known.One |= RHSKnown.Zero; 817 // assume(v >> c = a) 818 } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)), 819 m_Value(A))) && 820 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) { 821 KnownBits RHSKnown = 822 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 823 // For those bits in RHS that are known, we can propagate them to known 824 // bits in V shifted to the right by C. 825 Known.Zero |= RHSKnown.Zero << C; 826 Known.One |= RHSKnown.One << C; 827 // assume(~(v >> c) = a) 828 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))), 829 m_Value(A))) && 830 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) { 831 KnownBits RHSKnown = 832 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 833 // For those bits in RHS that are known, we can propagate them inverted 834 // to known bits in V shifted to the right by C. 835 Known.Zero |= RHSKnown.One << C; 836 Known.One |= RHSKnown.Zero << C; 837 } 838 break; 839 case ICmpInst::ICMP_SGE: 840 // assume(v >=_s c) where c is non-negative 841 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) && 842 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 843 KnownBits RHSKnown = 844 computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth); 845 846 if (RHSKnown.isNonNegative()) { 847 // We know that the sign bit is zero. 848 Known.makeNonNegative(); 849 } 850 } 851 break; 852 case ICmpInst::ICMP_SGT: 853 // assume(v >_s c) where c is at least -1. 854 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) && 855 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 856 KnownBits RHSKnown = 857 computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth); 858 859 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) { 860 // We know that the sign bit is zero. 861 Known.makeNonNegative(); 862 } 863 } 864 break; 865 case ICmpInst::ICMP_SLE: 866 // assume(v <=_s c) where c is negative 867 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) && 868 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 869 KnownBits RHSKnown = 870 computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth); 871 872 if (RHSKnown.isNegative()) { 873 // We know that the sign bit is one. 874 Known.makeNegative(); 875 } 876 } 877 break; 878 case ICmpInst::ICMP_SLT: 879 // assume(v <_s c) where c is non-positive 880 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) && 881 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 882 KnownBits RHSKnown = 883 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 884 885 if (RHSKnown.isZero() || RHSKnown.isNegative()) { 886 // We know that the sign bit is one. 887 Known.makeNegative(); 888 } 889 } 890 break; 891 case ICmpInst::ICMP_ULE: 892 // assume(v <=_u c) 893 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) && 894 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 895 KnownBits RHSKnown = 896 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 897 898 // Whatever high bits in c are zero are known to be zero. 899 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros()); 900 } 901 break; 902 case ICmpInst::ICMP_ULT: 903 // assume(v <_u c) 904 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) && 905 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 906 KnownBits RHSKnown = 907 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth); 908 909 // If the RHS is known zero, then this assumption must be wrong (nothing 910 // is unsigned less than zero). Signal a conflict and get out of here. 911 if (RHSKnown.isZero()) { 912 Known.Zero.setAllBits(); 913 Known.One.setAllBits(); 914 break; 915 } 916 917 // Whatever high bits in c are zero are known to be zero (if c is a power 918 // of 2, then one more). 919 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, QueryNoAC)) 920 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1); 921 else 922 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros()); 923 } 924 break; 925 } 926 } 927 928 // If assumptions conflict with each other or previous known bits, then we 929 // have a logical fallacy. It's possible that the assumption is not reachable, 930 // so this isn't a real bug. On the other hand, the program may have undefined 931 // behavior, or we might have a bug in the compiler. We can't assert/crash, so 932 // clear out the known bits, try to warn the user, and hope for the best. 933 if (Known.Zero.intersects(Known.One)) { 934 Known.resetAll(); 935 936 if (Q.ORE) 937 Q.ORE->emit([&]() { 938 auto *CxtI = const_cast<Instruction *>(Q.CxtI); 939 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption", 940 CxtI) 941 << "Detected conflicting code assumptions. Program may " 942 "have undefined behavior, or compiler may have " 943 "internal error."; 944 }); 945 } 946 } 947 948 /// Compute known bits from a shift operator, including those with a 949 /// non-constant shift amount. Known is the output of this function. Known2 is a 950 /// pre-allocated temporary with the same bit width as Known and on return 951 /// contains the known bit of the shift value source. KF is an 952 /// operator-specific function that, given the known-bits and a shift amount, 953 /// compute the implied known-bits of the shift operator's result respectively 954 /// for that shift amount. The results from calling KF are conservatively 955 /// combined for all permitted shift amounts. 956 static void computeKnownBitsFromShiftOperator( 957 const Operator *I, const APInt &DemandedElts, KnownBits &Known, 958 KnownBits &Known2, unsigned Depth, const Query &Q, 959 function_ref<KnownBits(const KnownBits &, const KnownBits &)> KF) { 960 unsigned BitWidth = Known.getBitWidth(); 961 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q); 962 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q); 963 964 // Note: We cannot use Known.Zero.getLimitedValue() here, because if 965 // BitWidth > 64 and any upper bits are known, we'll end up returning the 966 // limit value (which implies all bits are known). 967 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue(); 968 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue(); 969 bool ShiftAmtIsConstant = Known.isConstant(); 970 bool MaxShiftAmtIsOutOfRange = Known.getMaxValue().uge(BitWidth); 971 972 if (ShiftAmtIsConstant) { 973 Known = KF(Known2, Known); 974 975 // If the known bits conflict, this must be an overflowing left shift, so 976 // the shift result is poison. We can return anything we want. Choose 0 for 977 // the best folding opportunity. 978 if (Known.hasConflict()) 979 Known.setAllZero(); 980 981 return; 982 } 983 984 // If the shift amount could be greater than or equal to the bit-width of the 985 // LHS, the value could be poison, but bail out because the check below is 986 // expensive. 987 // TODO: Should we just carry on? 988 if (MaxShiftAmtIsOutOfRange) { 989 Known.resetAll(); 990 return; 991 } 992 993 // It would be more-clearly correct to use the two temporaries for this 994 // calculation. Reusing the APInts here to prevent unnecessary allocations. 995 Known.resetAll(); 996 997 // If we know the shifter operand is nonzero, we can sometimes infer more 998 // known bits. However this is expensive to compute, so be lazy about it and 999 // only compute it when absolutely necessary. 1000 Optional<bool> ShifterOperandIsNonZero; 1001 1002 // Early exit if we can't constrain any well-defined shift amount. 1003 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) && 1004 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) { 1005 ShifterOperandIsNonZero = 1006 isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q); 1007 if (!*ShifterOperandIsNonZero) 1008 return; 1009 } 1010 1011 Known.Zero.setAllBits(); 1012 Known.One.setAllBits(); 1013 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) { 1014 // Combine the shifted known input bits only for those shift amounts 1015 // compatible with its known constraints. 1016 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt) 1017 continue; 1018 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt) 1019 continue; 1020 // If we know the shifter is nonzero, we may be able to infer more known 1021 // bits. This check is sunk down as far as possible to avoid the expensive 1022 // call to isKnownNonZero if the cheaper checks above fail. 1023 if (ShiftAmt == 0) { 1024 if (!ShifterOperandIsNonZero.hasValue()) 1025 ShifterOperandIsNonZero = 1026 isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q); 1027 if (*ShifterOperandIsNonZero) 1028 continue; 1029 } 1030 1031 Known = KnownBits::commonBits( 1032 Known, KF(Known2, KnownBits::makeConstant(APInt(32, ShiftAmt)))); 1033 } 1034 1035 // If the known bits conflict, the result is poison. Return a 0 and hope the 1036 // caller can further optimize that. 1037 if (Known.hasConflict()) 1038 Known.setAllZero(); 1039 } 1040 1041 static void computeKnownBitsFromOperator(const Operator *I, 1042 const APInt &DemandedElts, 1043 KnownBits &Known, unsigned Depth, 1044 const Query &Q) { 1045 unsigned BitWidth = Known.getBitWidth(); 1046 1047 KnownBits Known2(BitWidth); 1048 switch (I->getOpcode()) { 1049 default: break; 1050 case Instruction::Load: 1051 if (MDNode *MD = 1052 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range)) 1053 computeKnownBitsFromRangeMetadata(*MD, Known); 1054 break; 1055 case Instruction::And: { 1056 // If either the LHS or the RHS are Zero, the result is zero. 1057 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q); 1058 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q); 1059 1060 Known &= Known2; 1061 1062 // and(x, add (x, -1)) is a common idiom that always clears the low bit; 1063 // here we handle the more general case of adding any odd number by 1064 // matching the form add(x, add(x, y)) where y is odd. 1065 // TODO: This could be generalized to clearing any bit set in y where the 1066 // following bit is known to be unset in y. 1067 Value *X = nullptr, *Y = nullptr; 1068 if (!Known.Zero[0] && !Known.One[0] && 1069 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) { 1070 Known2.resetAll(); 1071 computeKnownBits(Y, DemandedElts, Known2, Depth + 1, Q); 1072 if (Known2.countMinTrailingOnes() > 0) 1073 Known.Zero.setBit(0); 1074 } 1075 break; 1076 } 1077 case Instruction::Or: 1078 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q); 1079 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q); 1080 1081 Known |= Known2; 1082 break; 1083 case Instruction::Xor: 1084 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q); 1085 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q); 1086 1087 Known ^= Known2; 1088 break; 1089 case Instruction::Mul: { 1090 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I)); 1091 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, DemandedElts, 1092 Known, Known2, Depth, Q); 1093 break; 1094 } 1095 case Instruction::UDiv: { 1096 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1097 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1098 Known = KnownBits::udiv(Known, Known2); 1099 break; 1100 } 1101 case Instruction::Select: { 1102 const Value *LHS = nullptr, *RHS = nullptr; 1103 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor; 1104 if (SelectPatternResult::isMinOrMax(SPF)) { 1105 computeKnownBits(RHS, Known, Depth + 1, Q); 1106 computeKnownBits(LHS, Known2, Depth + 1, Q); 1107 switch (SPF) { 1108 default: 1109 llvm_unreachable("Unhandled select pattern flavor!"); 1110 case SPF_SMAX: 1111 Known = KnownBits::smax(Known, Known2); 1112 break; 1113 case SPF_SMIN: 1114 Known = KnownBits::smin(Known, Known2); 1115 break; 1116 case SPF_UMAX: 1117 Known = KnownBits::umax(Known, Known2); 1118 break; 1119 case SPF_UMIN: 1120 Known = KnownBits::umin(Known, Known2); 1121 break; 1122 } 1123 break; 1124 } 1125 1126 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q); 1127 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1128 1129 // Only known if known in both the LHS and RHS. 1130 Known = KnownBits::commonBits(Known, Known2); 1131 1132 if (SPF == SPF_ABS) { 1133 // RHS from matchSelectPattern returns the negation part of abs pattern. 1134 // If the negate has an NSW flag we can assume the sign bit of the result 1135 // will be 0 because that makes abs(INT_MIN) undefined. 1136 if (match(RHS, m_Neg(m_Specific(LHS))) && 1137 Q.IIQ.hasNoSignedWrap(cast<Instruction>(RHS))) 1138 Known.Zero.setSignBit(); 1139 } 1140 1141 break; 1142 } 1143 case Instruction::FPTrunc: 1144 case Instruction::FPExt: 1145 case Instruction::FPToUI: 1146 case Instruction::FPToSI: 1147 case Instruction::SIToFP: 1148 case Instruction::UIToFP: 1149 break; // Can't work with floating point. 1150 case Instruction::PtrToInt: 1151 case Instruction::IntToPtr: 1152 // Fall through and handle them the same as zext/trunc. 1153 LLVM_FALLTHROUGH; 1154 case Instruction::ZExt: 1155 case Instruction::Trunc: { 1156 Type *SrcTy = I->getOperand(0)->getType(); 1157 1158 unsigned SrcBitWidth; 1159 // Note that we handle pointer operands here because of inttoptr/ptrtoint 1160 // which fall through here. 1161 Type *ScalarTy = SrcTy->getScalarType(); 1162 SrcBitWidth = ScalarTy->isPointerTy() ? 1163 Q.DL.getPointerTypeSizeInBits(ScalarTy) : 1164 Q.DL.getTypeSizeInBits(ScalarTy); 1165 1166 assert(SrcBitWidth && "SrcBitWidth can't be zero"); 1167 Known = Known.anyextOrTrunc(SrcBitWidth); 1168 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1169 Known = Known.zextOrTrunc(BitWidth); 1170 break; 1171 } 1172 case Instruction::BitCast: { 1173 Type *SrcTy = I->getOperand(0)->getType(); 1174 if (SrcTy->isIntOrPtrTy() && 1175 // TODO: For now, not handling conversions like: 1176 // (bitcast i64 %x to <2 x i32>) 1177 !I->getType()->isVectorTy()) { 1178 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1179 break; 1180 } 1181 1182 // Handle cast from vector integer type to scalar or vector integer. 1183 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy); 1184 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() || 1185 !I->getType()->isIntOrIntVectorTy()) 1186 break; 1187 1188 // Look through a cast from narrow vector elements to wider type. 1189 // Examples: v4i32 -> v2i64, v3i8 -> v24 1190 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits(); 1191 if (BitWidth % SubBitWidth == 0) { 1192 // Known bits are automatically intersected across demanded elements of a 1193 // vector. So for example, if a bit is computed as known zero, it must be 1194 // zero across all demanded elements of the vector. 1195 // 1196 // For this bitcast, each demanded element of the output is sub-divided 1197 // across a set of smaller vector elements in the source vector. To get 1198 // the known bits for an entire element of the output, compute the known 1199 // bits for each sub-element sequentially. This is done by shifting the 1200 // one-set-bit demanded elements parameter across the sub-elements for 1201 // consecutive calls to computeKnownBits. We are using the demanded 1202 // elements parameter as a mask operator. 1203 // 1204 // The known bits of each sub-element are then inserted into place 1205 // (dependent on endian) to form the full result of known bits. 1206 unsigned NumElts = DemandedElts.getBitWidth(); 1207 unsigned SubScale = BitWidth / SubBitWidth; 1208 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale); 1209 for (unsigned i = 0; i != NumElts; ++i) { 1210 if (DemandedElts[i]) 1211 SubDemandedElts.setBit(i * SubScale); 1212 } 1213 1214 KnownBits KnownSrc(SubBitWidth); 1215 for (unsigned i = 0; i != SubScale; ++i) { 1216 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, 1217 Depth + 1, Q); 1218 unsigned ShiftElt = Q.DL.isLittleEndian() ? i : SubScale - 1 - i; 1219 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth); 1220 } 1221 } 1222 break; 1223 } 1224 case Instruction::SExt: { 1225 // Compute the bits in the result that are not present in the input. 1226 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 1227 1228 Known = Known.trunc(SrcBitWidth); 1229 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1230 // If the sign bit of the input is known set or clear, then we know the 1231 // top bits of the result. 1232 Known = Known.sext(BitWidth); 1233 break; 1234 } 1235 case Instruction::Shl: { 1236 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I)); 1237 auto KF = [NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt) { 1238 KnownBits Result = KnownBits::shl(KnownVal, KnownAmt); 1239 // If this shift has "nsw" keyword, then the result is either a poison 1240 // value or has the same sign bit as the first operand. 1241 if (NSW) { 1242 if (KnownVal.Zero.isSignBitSet()) 1243 Result.Zero.setSignBit(); 1244 if (KnownVal.One.isSignBitSet()) 1245 Result.One.setSignBit(); 1246 } 1247 return Result; 1248 }; 1249 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q, 1250 KF); 1251 // Trailing zeros of a right-shifted constant never decrease. 1252 const APInt *C; 1253 if (match(I->getOperand(0), m_APInt(C))) 1254 Known.Zero.setLowBits(C->countTrailingZeros()); 1255 break; 1256 } 1257 case Instruction::LShr: { 1258 auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) { 1259 return KnownBits::lshr(KnownVal, KnownAmt); 1260 }; 1261 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q, 1262 KF); 1263 // Leading zeros of a left-shifted constant never decrease. 1264 const APInt *C; 1265 if (match(I->getOperand(0), m_APInt(C))) 1266 Known.Zero.setHighBits(C->countLeadingZeros()); 1267 break; 1268 } 1269 case Instruction::AShr: { 1270 auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) { 1271 return KnownBits::ashr(KnownVal, KnownAmt); 1272 }; 1273 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q, 1274 KF); 1275 break; 1276 } 1277 case Instruction::Sub: { 1278 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I)); 1279 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, 1280 DemandedElts, Known, Known2, Depth, Q); 1281 break; 1282 } 1283 case Instruction::Add: { 1284 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I)); 1285 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, 1286 DemandedElts, Known, Known2, Depth, Q); 1287 break; 1288 } 1289 case Instruction::SRem: 1290 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1291 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1292 Known = KnownBits::srem(Known, Known2); 1293 break; 1294 1295 case Instruction::URem: 1296 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1297 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1298 Known = KnownBits::urem(Known, Known2); 1299 break; 1300 case Instruction::Alloca: 1301 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign())); 1302 break; 1303 case Instruction::GetElementPtr: { 1304 // Analyze all of the subscripts of this getelementptr instruction 1305 // to determine if we can prove known low zero bits. 1306 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1307 // Accumulate the constant indices in a separate variable 1308 // to minimize the number of calls to computeForAddSub. 1309 APInt AccConstIndices(BitWidth, 0, /*IsSigned*/ true); 1310 1311 gep_type_iterator GTI = gep_type_begin(I); 1312 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) { 1313 // TrailZ can only become smaller, short-circuit if we hit zero. 1314 if (Known.isUnknown()) 1315 break; 1316 1317 Value *Index = I->getOperand(i); 1318 1319 // Handle case when index is zero. 1320 Constant *CIndex = dyn_cast<Constant>(Index); 1321 if (CIndex && CIndex->isZeroValue()) 1322 continue; 1323 1324 if (StructType *STy = GTI.getStructTypeOrNull()) { 1325 // Handle struct member offset arithmetic. 1326 1327 assert(CIndex && 1328 "Access to structure field must be known at compile time"); 1329 1330 if (CIndex->getType()->isVectorTy()) 1331 Index = CIndex->getSplatValue(); 1332 1333 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue(); 1334 const StructLayout *SL = Q.DL.getStructLayout(STy); 1335 uint64_t Offset = SL->getElementOffset(Idx); 1336 AccConstIndices += Offset; 1337 continue; 1338 } 1339 1340 // Handle array index arithmetic. 1341 Type *IndexedTy = GTI.getIndexedType(); 1342 if (!IndexedTy->isSized()) { 1343 Known.resetAll(); 1344 break; 1345 } 1346 1347 unsigned IndexBitWidth = Index->getType()->getScalarSizeInBits(); 1348 KnownBits IndexBits(IndexBitWidth); 1349 computeKnownBits(Index, IndexBits, Depth + 1, Q); 1350 TypeSize IndexTypeSize = Q.DL.getTypeAllocSize(IndexedTy); 1351 uint64_t TypeSizeInBytes = IndexTypeSize.getKnownMinSize(); 1352 KnownBits ScalingFactor(IndexBitWidth); 1353 // Multiply by current sizeof type. 1354 // &A[i] == A + i * sizeof(*A[i]). 1355 if (IndexTypeSize.isScalable()) { 1356 // For scalable types the only thing we know about sizeof is 1357 // that this is a multiple of the minimum size. 1358 ScalingFactor.Zero.setLowBits(countTrailingZeros(TypeSizeInBytes)); 1359 } else if (IndexBits.isConstant()) { 1360 APInt IndexConst = IndexBits.getConstant(); 1361 APInt ScalingFactor(IndexBitWidth, TypeSizeInBytes); 1362 IndexConst *= ScalingFactor; 1363 AccConstIndices += IndexConst.sextOrTrunc(BitWidth); 1364 continue; 1365 } else { 1366 ScalingFactor = 1367 KnownBits::makeConstant(APInt(IndexBitWidth, TypeSizeInBytes)); 1368 } 1369 IndexBits = KnownBits::mul(IndexBits, ScalingFactor); 1370 1371 // If the offsets have a different width from the pointer, according 1372 // to the language reference we need to sign-extend or truncate them 1373 // to the width of the pointer. 1374 IndexBits = IndexBits.sextOrTrunc(BitWidth); 1375 1376 // Note that inbounds does *not* guarantee nsw for the addition, as only 1377 // the offset is signed, while the base address is unsigned. 1378 Known = KnownBits::computeForAddSub( 1379 /*Add=*/true, /*NSW=*/false, Known, IndexBits); 1380 } 1381 if (!Known.isUnknown() && !AccConstIndices.isZero()) { 1382 KnownBits Index = KnownBits::makeConstant(AccConstIndices); 1383 Known = KnownBits::computeForAddSub( 1384 /*Add=*/true, /*NSW=*/false, Known, Index); 1385 } 1386 break; 1387 } 1388 case Instruction::PHI: { 1389 const PHINode *P = cast<PHINode>(I); 1390 BinaryOperator *BO = nullptr; 1391 Value *R = nullptr, *L = nullptr; 1392 if (matchSimpleRecurrence(P, BO, R, L)) { 1393 // Handle the case of a simple two-predecessor recurrence PHI. 1394 // There's a lot more that could theoretically be done here, but 1395 // this is sufficient to catch some interesting cases. 1396 unsigned Opcode = BO->getOpcode(); 1397 1398 // If this is a shift recurrence, we know the bits being shifted in. 1399 // We can combine that with information about the start value of the 1400 // recurrence to conclude facts about the result. 1401 if ((Opcode == Instruction::LShr || Opcode == Instruction::AShr || 1402 Opcode == Instruction::Shl) && 1403 BO->getOperand(0) == I) { 1404 1405 // We have matched a recurrence of the form: 1406 // %iv = [R, %entry], [%iv.next, %backedge] 1407 // %iv.next = shift_op %iv, L 1408 1409 // Recurse with the phi context to avoid concern about whether facts 1410 // inferred hold at original context instruction. TODO: It may be 1411 // correct to use the original context. IF warranted, explore and 1412 // add sufficient tests to cover. 1413 Query RecQ = Q; 1414 RecQ.CxtI = P; 1415 computeKnownBits(R, DemandedElts, Known2, Depth + 1, RecQ); 1416 switch (Opcode) { 1417 case Instruction::Shl: 1418 // A shl recurrence will only increase the tailing zeros 1419 Known.Zero.setLowBits(Known2.countMinTrailingZeros()); 1420 break; 1421 case Instruction::LShr: 1422 // A lshr recurrence will preserve the leading zeros of the 1423 // start value 1424 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 1425 break; 1426 case Instruction::AShr: 1427 // An ashr recurrence will extend the initial sign bit 1428 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 1429 Known.One.setHighBits(Known2.countMinLeadingOnes()); 1430 break; 1431 }; 1432 } 1433 1434 // Check for operations that have the property that if 1435 // both their operands have low zero bits, the result 1436 // will have low zero bits. 1437 if (Opcode == Instruction::Add || 1438 Opcode == Instruction::Sub || 1439 Opcode == Instruction::And || 1440 Opcode == Instruction::Or || 1441 Opcode == Instruction::Mul) { 1442 // Change the context instruction to the "edge" that flows into the 1443 // phi. This is important because that is where the value is actually 1444 // "evaluated" even though it is used later somewhere else. (see also 1445 // D69571). 1446 Query RecQ = Q; 1447 1448 unsigned OpNum = P->getOperand(0) == R ? 0 : 1; 1449 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator(); 1450 Instruction *LInst = P->getIncomingBlock(1-OpNum)->getTerminator(); 1451 1452 // Ok, we have a PHI of the form L op= R. Check for low 1453 // zero bits. 1454 RecQ.CxtI = RInst; 1455 computeKnownBits(R, Known2, Depth + 1, RecQ); 1456 1457 // We need to take the minimum number of known bits 1458 KnownBits Known3(BitWidth); 1459 RecQ.CxtI = LInst; 1460 computeKnownBits(L, Known3, Depth + 1, RecQ); 1461 1462 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(), 1463 Known3.countMinTrailingZeros())); 1464 1465 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO); 1466 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) { 1467 // If initial value of recurrence is nonnegative, and we are adding 1468 // a nonnegative number with nsw, the result can only be nonnegative 1469 // or poison value regardless of the number of times we execute the 1470 // add in phi recurrence. If initial value is negative and we are 1471 // adding a negative number with nsw, the result can only be 1472 // negative or poison value. Similar arguments apply to sub and mul. 1473 // 1474 // (add non-negative, non-negative) --> non-negative 1475 // (add negative, negative) --> negative 1476 if (Opcode == Instruction::Add) { 1477 if (Known2.isNonNegative() && Known3.isNonNegative()) 1478 Known.makeNonNegative(); 1479 else if (Known2.isNegative() && Known3.isNegative()) 1480 Known.makeNegative(); 1481 } 1482 1483 // (sub nsw non-negative, negative) --> non-negative 1484 // (sub nsw negative, non-negative) --> negative 1485 else if (Opcode == Instruction::Sub && BO->getOperand(0) == I) { 1486 if (Known2.isNonNegative() && Known3.isNegative()) 1487 Known.makeNonNegative(); 1488 else if (Known2.isNegative() && Known3.isNonNegative()) 1489 Known.makeNegative(); 1490 } 1491 1492 // (mul nsw non-negative, non-negative) --> non-negative 1493 else if (Opcode == Instruction::Mul && Known2.isNonNegative() && 1494 Known3.isNonNegative()) 1495 Known.makeNonNegative(); 1496 } 1497 1498 break; 1499 } 1500 } 1501 1502 // Unreachable blocks may have zero-operand PHI nodes. 1503 if (P->getNumIncomingValues() == 0) 1504 break; 1505 1506 // Otherwise take the unions of the known bit sets of the operands, 1507 // taking conservative care to avoid excessive recursion. 1508 if (Depth < MaxAnalysisRecursionDepth - 1 && !Known.Zero && !Known.One) { 1509 // Skip if every incoming value references to ourself. 1510 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue())) 1511 break; 1512 1513 Known.Zero.setAllBits(); 1514 Known.One.setAllBits(); 1515 for (unsigned u = 0, e = P->getNumIncomingValues(); u < e; ++u) { 1516 Value *IncValue = P->getIncomingValue(u); 1517 // Skip direct self references. 1518 if (IncValue == P) continue; 1519 1520 // Change the context instruction to the "edge" that flows into the 1521 // phi. This is important because that is where the value is actually 1522 // "evaluated" even though it is used later somewhere else. (see also 1523 // D69571). 1524 Query RecQ = Q; 1525 RecQ.CxtI = P->getIncomingBlock(u)->getTerminator(); 1526 1527 Known2 = KnownBits(BitWidth); 1528 // Recurse, but cap the recursion to one level, because we don't 1529 // want to waste time spinning around in loops. 1530 computeKnownBits(IncValue, Known2, MaxAnalysisRecursionDepth - 1, RecQ); 1531 Known = KnownBits::commonBits(Known, Known2); 1532 // If all bits have been ruled out, there's no need to check 1533 // more operands. 1534 if (Known.isUnknown()) 1535 break; 1536 } 1537 } 1538 break; 1539 } 1540 case Instruction::Call: 1541 case Instruction::Invoke: 1542 // If range metadata is attached to this call, set known bits from that, 1543 // and then intersect with known bits based on other properties of the 1544 // function. 1545 if (MDNode *MD = 1546 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range)) 1547 computeKnownBitsFromRangeMetadata(*MD, Known); 1548 if (const Value *RV = cast<CallBase>(I)->getReturnedArgOperand()) { 1549 computeKnownBits(RV, Known2, Depth + 1, Q); 1550 Known.Zero |= Known2.Zero; 1551 Known.One |= Known2.One; 1552 } 1553 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 1554 switch (II->getIntrinsicID()) { 1555 default: break; 1556 case Intrinsic::abs: { 1557 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); 1558 bool IntMinIsPoison = match(II->getArgOperand(1), m_One()); 1559 Known = Known2.abs(IntMinIsPoison); 1560 break; 1561 } 1562 case Intrinsic::bitreverse: 1563 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q); 1564 Known.Zero |= Known2.Zero.reverseBits(); 1565 Known.One |= Known2.One.reverseBits(); 1566 break; 1567 case Intrinsic::bswap: 1568 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q); 1569 Known.Zero |= Known2.Zero.byteSwap(); 1570 Known.One |= Known2.One.byteSwap(); 1571 break; 1572 case Intrinsic::ctlz: { 1573 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); 1574 // If we have a known 1, its position is our upper bound. 1575 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 1576 // If this call is undefined for 0, the result will be less than 2^n. 1577 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext())) 1578 PossibleLZ = std::min(PossibleLZ, BitWidth - 1); 1579 unsigned LowBits = Log2_32(PossibleLZ)+1; 1580 Known.Zero.setBitsFrom(LowBits); 1581 break; 1582 } 1583 case Intrinsic::cttz: { 1584 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); 1585 // If we have a known 1, its position is our upper bound. 1586 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 1587 // If this call is undefined for 0, the result will be less than 2^n. 1588 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext())) 1589 PossibleTZ = std::min(PossibleTZ, BitWidth - 1); 1590 unsigned LowBits = Log2_32(PossibleTZ)+1; 1591 Known.Zero.setBitsFrom(LowBits); 1592 break; 1593 } 1594 case Intrinsic::ctpop: { 1595 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); 1596 // We can bound the space the count needs. Also, bits known to be zero 1597 // can't contribute to the population. 1598 unsigned BitsPossiblySet = Known2.countMaxPopulation(); 1599 unsigned LowBits = Log2_32(BitsPossiblySet)+1; 1600 Known.Zero.setBitsFrom(LowBits); 1601 // TODO: we could bound KnownOne using the lower bound on the number 1602 // of bits which might be set provided by popcnt KnownOne2. 1603 break; 1604 } 1605 case Intrinsic::fshr: 1606 case Intrinsic::fshl: { 1607 const APInt *SA; 1608 if (!match(I->getOperand(2), m_APInt(SA))) 1609 break; 1610 1611 // Normalize to funnel shift left. 1612 uint64_t ShiftAmt = SA->urem(BitWidth); 1613 if (II->getIntrinsicID() == Intrinsic::fshr) 1614 ShiftAmt = BitWidth - ShiftAmt; 1615 1616 KnownBits Known3(BitWidth); 1617 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q); 1618 computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q); 1619 1620 Known.Zero = 1621 Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt); 1622 Known.One = 1623 Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt); 1624 break; 1625 } 1626 case Intrinsic::uadd_sat: 1627 case Intrinsic::usub_sat: { 1628 bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat; 1629 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1630 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1631 1632 // Add: Leading ones of either operand are preserved. 1633 // Sub: Leading zeros of LHS and leading ones of RHS are preserved 1634 // as leading zeros in the result. 1635 unsigned LeadingKnown; 1636 if (IsAdd) 1637 LeadingKnown = std::max(Known.countMinLeadingOnes(), 1638 Known2.countMinLeadingOnes()); 1639 else 1640 LeadingKnown = std::max(Known.countMinLeadingZeros(), 1641 Known2.countMinLeadingOnes()); 1642 1643 Known = KnownBits::computeForAddSub( 1644 IsAdd, /* NSW */ false, Known, Known2); 1645 1646 // We select between the operation result and all-ones/zero 1647 // respectively, so we can preserve known ones/zeros. 1648 if (IsAdd) { 1649 Known.One.setHighBits(LeadingKnown); 1650 Known.Zero.clearAllBits(); 1651 } else { 1652 Known.Zero.setHighBits(LeadingKnown); 1653 Known.One.clearAllBits(); 1654 } 1655 break; 1656 } 1657 case Intrinsic::umin: 1658 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1659 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1660 Known = KnownBits::umin(Known, Known2); 1661 break; 1662 case Intrinsic::umax: 1663 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1664 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1665 Known = KnownBits::umax(Known, Known2); 1666 break; 1667 case Intrinsic::smin: 1668 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1669 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1670 Known = KnownBits::smin(Known, Known2); 1671 break; 1672 case Intrinsic::smax: 1673 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1674 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q); 1675 Known = KnownBits::smax(Known, Known2); 1676 break; 1677 case Intrinsic::x86_sse42_crc32_64_64: 1678 Known.Zero.setBitsFrom(32); 1679 break; 1680 case Intrinsic::riscv_vsetvli: 1681 case Intrinsic::riscv_vsetvlimax: 1682 // Assume that VL output is positive and would fit in an int32_t. 1683 // TODO: VLEN might be capped at 16 bits in a future V spec update. 1684 if (BitWidth >= 32) 1685 Known.Zero.setBitsFrom(31); 1686 break; 1687 case Intrinsic::vscale: { 1688 if (!II->getParent() || !II->getFunction() || 1689 !II->getFunction()->hasFnAttribute(Attribute::VScaleRange)) 1690 break; 1691 1692 auto VScaleRange = II->getFunction() 1693 ->getFnAttribute(Attribute::VScaleRange) 1694 .getVScaleRangeArgs(); 1695 1696 if (VScaleRange.second == 0) 1697 break; 1698 1699 // If vscale min = max then we know the exact value at compile time 1700 // and hence we know the exact bits. 1701 if (VScaleRange.first == VScaleRange.second) { 1702 Known.One = VScaleRange.first; 1703 Known.Zero = VScaleRange.first; 1704 Known.Zero.flipAllBits(); 1705 break; 1706 } 1707 1708 unsigned FirstZeroHighBit = 32 - countLeadingZeros(VScaleRange.second); 1709 if (FirstZeroHighBit < BitWidth) 1710 Known.Zero.setBitsFrom(FirstZeroHighBit); 1711 1712 break; 1713 } 1714 } 1715 } 1716 break; 1717 case Instruction::ShuffleVector: { 1718 auto *Shuf = dyn_cast<ShuffleVectorInst>(I); 1719 // FIXME: Do we need to handle ConstantExpr involving shufflevectors? 1720 if (!Shuf) { 1721 Known.resetAll(); 1722 return; 1723 } 1724 // For undef elements, we don't know anything about the common state of 1725 // the shuffle result. 1726 APInt DemandedLHS, DemandedRHS; 1727 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) { 1728 Known.resetAll(); 1729 return; 1730 } 1731 Known.One.setAllBits(); 1732 Known.Zero.setAllBits(); 1733 if (!!DemandedLHS) { 1734 const Value *LHS = Shuf->getOperand(0); 1735 computeKnownBits(LHS, DemandedLHS, Known, Depth + 1, Q); 1736 // If we don't know any bits, early out. 1737 if (Known.isUnknown()) 1738 break; 1739 } 1740 if (!!DemandedRHS) { 1741 const Value *RHS = Shuf->getOperand(1); 1742 computeKnownBits(RHS, DemandedRHS, Known2, Depth + 1, Q); 1743 Known = KnownBits::commonBits(Known, Known2); 1744 } 1745 break; 1746 } 1747 case Instruction::InsertElement: { 1748 const Value *Vec = I->getOperand(0); 1749 const Value *Elt = I->getOperand(1); 1750 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2)); 1751 // Early out if the index is non-constant or out-of-range. 1752 unsigned NumElts = DemandedElts.getBitWidth(); 1753 if (!CIdx || CIdx->getValue().uge(NumElts)) { 1754 Known.resetAll(); 1755 return; 1756 } 1757 Known.One.setAllBits(); 1758 Known.Zero.setAllBits(); 1759 unsigned EltIdx = CIdx->getZExtValue(); 1760 // Do we demand the inserted element? 1761 if (DemandedElts[EltIdx]) { 1762 computeKnownBits(Elt, Known, Depth + 1, Q); 1763 // If we don't know any bits, early out. 1764 if (Known.isUnknown()) 1765 break; 1766 } 1767 // We don't need the base vector element that has been inserted. 1768 APInt DemandedVecElts = DemandedElts; 1769 DemandedVecElts.clearBit(EltIdx); 1770 if (!!DemandedVecElts) { 1771 computeKnownBits(Vec, DemandedVecElts, Known2, Depth + 1, Q); 1772 Known = KnownBits::commonBits(Known, Known2); 1773 } 1774 break; 1775 } 1776 case Instruction::ExtractElement: { 1777 // Look through extract element. If the index is non-constant or 1778 // out-of-range demand all elements, otherwise just the extracted element. 1779 const Value *Vec = I->getOperand(0); 1780 const Value *Idx = I->getOperand(1); 1781 auto *CIdx = dyn_cast<ConstantInt>(Idx); 1782 if (isa<ScalableVectorType>(Vec->getType())) { 1783 // FIXME: there's probably *something* we can do with scalable vectors 1784 Known.resetAll(); 1785 break; 1786 } 1787 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 1788 APInt DemandedVecElts = APInt::getAllOnes(NumElts); 1789 if (CIdx && CIdx->getValue().ult(NumElts)) 1790 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue()); 1791 computeKnownBits(Vec, DemandedVecElts, Known, Depth + 1, Q); 1792 break; 1793 } 1794 case Instruction::ExtractValue: 1795 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) { 1796 const ExtractValueInst *EVI = cast<ExtractValueInst>(I); 1797 if (EVI->getNumIndices() != 1) break; 1798 if (EVI->getIndices()[0] == 0) { 1799 switch (II->getIntrinsicID()) { 1800 default: break; 1801 case Intrinsic::uadd_with_overflow: 1802 case Intrinsic::sadd_with_overflow: 1803 computeKnownBitsAddSub(true, II->getArgOperand(0), 1804 II->getArgOperand(1), false, DemandedElts, 1805 Known, Known2, Depth, Q); 1806 break; 1807 case Intrinsic::usub_with_overflow: 1808 case Intrinsic::ssub_with_overflow: 1809 computeKnownBitsAddSub(false, II->getArgOperand(0), 1810 II->getArgOperand(1), false, DemandedElts, 1811 Known, Known2, Depth, Q); 1812 break; 1813 case Intrinsic::umul_with_overflow: 1814 case Intrinsic::smul_with_overflow: 1815 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false, 1816 DemandedElts, Known, Known2, Depth, Q); 1817 break; 1818 } 1819 } 1820 } 1821 break; 1822 case Instruction::Freeze: 1823 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT, 1824 Depth + 1)) 1825 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q); 1826 break; 1827 } 1828 } 1829 1830 /// Determine which bits of V are known to be either zero or one and return 1831 /// them. 1832 KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts, 1833 unsigned Depth, const Query &Q) { 1834 KnownBits Known(getBitWidth(V->getType(), Q.DL)); 1835 computeKnownBits(V, DemandedElts, Known, Depth, Q); 1836 return Known; 1837 } 1838 1839 /// Determine which bits of V are known to be either zero or one and return 1840 /// them. 1841 KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) { 1842 KnownBits Known(getBitWidth(V->getType(), Q.DL)); 1843 computeKnownBits(V, Known, Depth, Q); 1844 return Known; 1845 } 1846 1847 /// Determine which bits of V are known to be either zero or one and return 1848 /// them in the Known bit set. 1849 /// 1850 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that 1851 /// we cannot optimize based on the assumption that it is zero without changing 1852 /// it to be an explicit zero. If we don't change it to zero, other code could 1853 /// optimized based on the contradictory assumption that it is non-zero. 1854 /// Because instcombine aggressively folds operations with undef args anyway, 1855 /// this won't lose us code quality. 1856 /// 1857 /// This function is defined on values with integer type, values with pointer 1858 /// type, and vectors of integers. In the case 1859 /// where V is a vector, known zero, and known one values are the 1860 /// same width as the vector element, and the bit is set only if it is true 1861 /// for all of the demanded elements in the vector specified by DemandedElts. 1862 void computeKnownBits(const Value *V, const APInt &DemandedElts, 1863 KnownBits &Known, unsigned Depth, const Query &Q) { 1864 if (!DemandedElts || isa<ScalableVectorType>(V->getType())) { 1865 // No demanded elts or V is a scalable vector, better to assume we don't 1866 // know anything. 1867 Known.resetAll(); 1868 return; 1869 } 1870 1871 assert(V && "No Value?"); 1872 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth"); 1873 1874 #ifndef NDEBUG 1875 Type *Ty = V->getType(); 1876 unsigned BitWidth = Known.getBitWidth(); 1877 1878 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) && 1879 "Not integer or pointer type!"); 1880 1881 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) { 1882 assert( 1883 FVTy->getNumElements() == DemandedElts.getBitWidth() && 1884 "DemandedElt width should equal the fixed vector number of elements"); 1885 } else { 1886 assert(DemandedElts == APInt(1, 1) && 1887 "DemandedElt width should be 1 for scalars"); 1888 } 1889 1890 Type *ScalarTy = Ty->getScalarType(); 1891 if (ScalarTy->isPointerTy()) { 1892 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) && 1893 "V and Known should have same BitWidth"); 1894 } else { 1895 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) && 1896 "V and Known should have same BitWidth"); 1897 } 1898 #endif 1899 1900 const APInt *C; 1901 if (match(V, m_APInt(C))) { 1902 // We know all of the bits for a scalar constant or a splat vector constant! 1903 Known = KnownBits::makeConstant(*C); 1904 return; 1905 } 1906 // Null and aggregate-zero are all-zeros. 1907 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) { 1908 Known.setAllZero(); 1909 return; 1910 } 1911 // Handle a constant vector by taking the intersection of the known bits of 1912 // each element. 1913 if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) { 1914 // We know that CDV must be a vector of integers. Take the intersection of 1915 // each element. 1916 Known.Zero.setAllBits(); Known.One.setAllBits(); 1917 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) { 1918 if (!DemandedElts[i]) 1919 continue; 1920 APInt Elt = CDV->getElementAsAPInt(i); 1921 Known.Zero &= ~Elt; 1922 Known.One &= Elt; 1923 } 1924 return; 1925 } 1926 1927 if (const auto *CV = dyn_cast<ConstantVector>(V)) { 1928 // We know that CV must be a vector of integers. Take the intersection of 1929 // each element. 1930 Known.Zero.setAllBits(); Known.One.setAllBits(); 1931 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 1932 if (!DemandedElts[i]) 1933 continue; 1934 Constant *Element = CV->getAggregateElement(i); 1935 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element); 1936 if (!ElementCI) { 1937 Known.resetAll(); 1938 return; 1939 } 1940 const APInt &Elt = ElementCI->getValue(); 1941 Known.Zero &= ~Elt; 1942 Known.One &= Elt; 1943 } 1944 return; 1945 } 1946 1947 // Start out not knowing anything. 1948 Known.resetAll(); 1949 1950 // We can't imply anything about undefs. 1951 if (isa<UndefValue>(V)) 1952 return; 1953 1954 // There's no point in looking through other users of ConstantData for 1955 // assumptions. Confirm that we've handled them all. 1956 assert(!isa<ConstantData>(V) && "Unhandled constant data!"); 1957 1958 // All recursive calls that increase depth must come after this. 1959 if (Depth == MaxAnalysisRecursionDepth) 1960 return; 1961 1962 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has 1963 // the bits of its aliasee. 1964 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 1965 if (!GA->isInterposable()) 1966 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q); 1967 return; 1968 } 1969 1970 if (const Operator *I = dyn_cast<Operator>(V)) 1971 computeKnownBitsFromOperator(I, DemandedElts, Known, Depth, Q); 1972 1973 // Aligned pointers have trailing zeros - refine Known.Zero set 1974 if (isa<PointerType>(V->getType())) { 1975 Align Alignment = V->getPointerAlignment(Q.DL); 1976 Known.Zero.setLowBits(Log2(Alignment)); 1977 } 1978 1979 // computeKnownBitsFromAssume strictly refines Known. 1980 // Therefore, we run them after computeKnownBitsFromOperator. 1981 1982 // Check whether a nearby assume intrinsic can determine some known bits. 1983 computeKnownBitsFromAssume(V, Known, Depth, Q); 1984 1985 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?"); 1986 } 1987 1988 /// Return true if the given value is known to have exactly one 1989 /// bit set when defined. For vectors return true if every element is known to 1990 /// be a power of two when defined. Supports values with integer or pointer 1991 /// types and vectors of integers. 1992 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth, 1993 const Query &Q) { 1994 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth"); 1995 1996 // Attempt to match against constants. 1997 if (OrZero && match(V, m_Power2OrZero())) 1998 return true; 1999 if (match(V, m_Power2())) 2000 return true; 2001 2002 // 1 << X is clearly a power of two if the one is not shifted off the end. If 2003 // it is shifted off the end then the result is undefined. 2004 if (match(V, m_Shl(m_One(), m_Value()))) 2005 return true; 2006 2007 // (signmask) >>l X is clearly a power of two if the one is not shifted off 2008 // the bottom. If it is shifted off the bottom then the result is undefined. 2009 if (match(V, m_LShr(m_SignMask(), m_Value()))) 2010 return true; 2011 2012 // The remaining tests are all recursive, so bail out if we hit the limit. 2013 if (Depth++ == MaxAnalysisRecursionDepth) 2014 return false; 2015 2016 Value *X = nullptr, *Y = nullptr; 2017 // A shift left or a logical shift right of a power of two is a power of two 2018 // or zero. 2019 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) || 2020 match(V, m_LShr(m_Value(X), m_Value())))) 2021 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q); 2022 2023 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V)) 2024 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q); 2025 2026 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) 2027 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) && 2028 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q); 2029 2030 // Peek through min/max. 2031 if (match(V, m_MaxOrMin(m_Value(X), m_Value(Y)))) { 2032 return isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q) && 2033 isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q); 2034 } 2035 2036 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) { 2037 // A power of two and'd with anything is a power of two or zero. 2038 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) || 2039 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q)) 2040 return true; 2041 // X & (-X) is always a power of two or zero. 2042 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X)))) 2043 return true; 2044 return false; 2045 } 2046 2047 // Adding a power-of-two or zero to the same power-of-two or zero yields 2048 // either the original power-of-two, a larger power-of-two or zero. 2049 if (match(V, m_Add(m_Value(X), m_Value(Y)))) { 2050 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V); 2051 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) || 2052 Q.IIQ.hasNoSignedWrap(VOBO)) { 2053 if (match(X, m_And(m_Specific(Y), m_Value())) || 2054 match(X, m_And(m_Value(), m_Specific(Y)))) 2055 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q)) 2056 return true; 2057 if (match(Y, m_And(m_Specific(X), m_Value())) || 2058 match(Y, m_And(m_Value(), m_Specific(X)))) 2059 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q)) 2060 return true; 2061 2062 unsigned BitWidth = V->getType()->getScalarSizeInBits(); 2063 KnownBits LHSBits(BitWidth); 2064 computeKnownBits(X, LHSBits, Depth, Q); 2065 2066 KnownBits RHSBits(BitWidth); 2067 computeKnownBits(Y, RHSBits, Depth, Q); 2068 // If i8 V is a power of two or zero: 2069 // ZeroBits: 1 1 1 0 1 1 1 1 2070 // ~ZeroBits: 0 0 0 1 0 0 0 0 2071 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2()) 2072 // If OrZero isn't set, we cannot give back a zero result. 2073 // Make sure either the LHS or RHS has a bit set. 2074 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue()) 2075 return true; 2076 } 2077 } 2078 2079 // An exact divide or right shift can only shift off zero bits, so the result 2080 // is a power of two only if the first operand is a power of two and not 2081 // copying a sign bit (sdiv int_min, 2). 2082 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) || 2083 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) { 2084 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero, 2085 Depth, Q); 2086 } 2087 2088 return false; 2089 } 2090 2091 /// Test whether a GEP's result is known to be non-null. 2092 /// 2093 /// Uses properties inherent in a GEP to try to determine whether it is known 2094 /// to be non-null. 2095 /// 2096 /// Currently this routine does not support vector GEPs. 2097 static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth, 2098 const Query &Q) { 2099 const Function *F = nullptr; 2100 if (const Instruction *I = dyn_cast<Instruction>(GEP)) 2101 F = I->getFunction(); 2102 2103 if (!GEP->isInBounds() || 2104 NullPointerIsDefined(F, GEP->getPointerAddressSpace())) 2105 return false; 2106 2107 // FIXME: Support vector-GEPs. 2108 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP"); 2109 2110 // If the base pointer is non-null, we cannot walk to a null address with an 2111 // inbounds GEP in address space zero. 2112 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q)) 2113 return true; 2114 2115 // Walk the GEP operands and see if any operand introduces a non-zero offset. 2116 // If so, then the GEP cannot produce a null pointer, as doing so would 2117 // inherently violate the inbounds contract within address space zero. 2118 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 2119 GTI != GTE; ++GTI) { 2120 // Struct types are easy -- they must always be indexed by a constant. 2121 if (StructType *STy = GTI.getStructTypeOrNull()) { 2122 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand()); 2123 unsigned ElementIdx = OpC->getZExtValue(); 2124 const StructLayout *SL = Q.DL.getStructLayout(STy); 2125 uint64_t ElementOffset = SL->getElementOffset(ElementIdx); 2126 if (ElementOffset > 0) 2127 return true; 2128 continue; 2129 } 2130 2131 // If we have a zero-sized type, the index doesn't matter. Keep looping. 2132 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()).getKnownMinSize() == 0) 2133 continue; 2134 2135 // Fast path the constant operand case both for efficiency and so we don't 2136 // increment Depth when just zipping down an all-constant GEP. 2137 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) { 2138 if (!OpC->isZero()) 2139 return true; 2140 continue; 2141 } 2142 2143 // We post-increment Depth here because while isKnownNonZero increments it 2144 // as well, when we pop back up that increment won't persist. We don't want 2145 // to recurse 10k times just because we have 10k GEP operands. We don't 2146 // bail completely out because we want to handle constant GEPs regardless 2147 // of depth. 2148 if (Depth++ >= MaxAnalysisRecursionDepth) 2149 continue; 2150 2151 if (isKnownNonZero(GTI.getOperand(), Depth, Q)) 2152 return true; 2153 } 2154 2155 return false; 2156 } 2157 2158 static bool isKnownNonNullFromDominatingCondition(const Value *V, 2159 const Instruction *CtxI, 2160 const DominatorTree *DT) { 2161 if (isa<Constant>(V)) 2162 return false; 2163 2164 if (!CtxI || !DT) 2165 return false; 2166 2167 unsigned NumUsesExplored = 0; 2168 for (auto *U : V->users()) { 2169 // Avoid massive lists 2170 if (NumUsesExplored >= DomConditionsMaxUses) 2171 break; 2172 NumUsesExplored++; 2173 2174 // If the value is used as an argument to a call or invoke, then argument 2175 // attributes may provide an answer about null-ness. 2176 if (const auto *CB = dyn_cast<CallBase>(U)) 2177 if (auto *CalledFunc = CB->getCalledFunction()) 2178 for (const Argument &Arg : CalledFunc->args()) 2179 if (CB->getArgOperand(Arg.getArgNo()) == V && 2180 Arg.hasNonNullAttr(/* AllowUndefOrPoison */ false) && 2181 DT->dominates(CB, CtxI)) 2182 return true; 2183 2184 // If the value is used as a load/store, then the pointer must be non null. 2185 if (V == getLoadStorePointerOperand(U)) { 2186 const Instruction *I = cast<Instruction>(U); 2187 if (!NullPointerIsDefined(I->getFunction(), 2188 V->getType()->getPointerAddressSpace()) && 2189 DT->dominates(I, CtxI)) 2190 return true; 2191 } 2192 2193 // Consider only compare instructions uniquely controlling a branch 2194 Value *RHS; 2195 CmpInst::Predicate Pred; 2196 if (!match(U, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS)))) 2197 continue; 2198 2199 bool NonNullIfTrue; 2200 if (cmpExcludesZero(Pred, RHS)) 2201 NonNullIfTrue = true; 2202 else if (cmpExcludesZero(CmpInst::getInversePredicate(Pred), RHS)) 2203 NonNullIfTrue = false; 2204 else 2205 continue; 2206 2207 SmallVector<const User *, 4> WorkList; 2208 SmallPtrSet<const User *, 4> Visited; 2209 for (auto *CmpU : U->users()) { 2210 assert(WorkList.empty() && "Should be!"); 2211 if (Visited.insert(CmpU).second) 2212 WorkList.push_back(CmpU); 2213 2214 while (!WorkList.empty()) { 2215 auto *Curr = WorkList.pop_back_val(); 2216 2217 // If a user is an AND, add all its users to the work list. We only 2218 // propagate "pred != null" condition through AND because it is only 2219 // correct to assume that all conditions of AND are met in true branch. 2220 // TODO: Support similar logic of OR and EQ predicate? 2221 if (NonNullIfTrue) 2222 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) { 2223 for (auto *CurrU : Curr->users()) 2224 if (Visited.insert(CurrU).second) 2225 WorkList.push_back(CurrU); 2226 continue; 2227 } 2228 2229 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) { 2230 assert(BI->isConditional() && "uses a comparison!"); 2231 2232 BasicBlock *NonNullSuccessor = 2233 BI->getSuccessor(NonNullIfTrue ? 0 : 1); 2234 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor); 2235 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent())) 2236 return true; 2237 } else if (NonNullIfTrue && isGuard(Curr) && 2238 DT->dominates(cast<Instruction>(Curr), CtxI)) { 2239 return true; 2240 } 2241 } 2242 } 2243 } 2244 2245 return false; 2246 } 2247 2248 /// Does the 'Range' metadata (which must be a valid MD_range operand list) 2249 /// ensure that the value it's attached to is never Value? 'RangeType' is 2250 /// is the type of the value described by the range. 2251 static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) { 2252 const unsigned NumRanges = Ranges->getNumOperands() / 2; 2253 assert(NumRanges >= 1); 2254 for (unsigned i = 0; i < NumRanges; ++i) { 2255 ConstantInt *Lower = 2256 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0)); 2257 ConstantInt *Upper = 2258 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1)); 2259 ConstantRange Range(Lower->getValue(), Upper->getValue()); 2260 if (Range.contains(Value)) 2261 return false; 2262 } 2263 return true; 2264 } 2265 2266 /// Try to detect a recurrence that monotonically increases/decreases from a 2267 /// non-zero starting value. These are common as induction variables. 2268 static bool isNonZeroRecurrence(const PHINode *PN) { 2269 BinaryOperator *BO = nullptr; 2270 Value *Start = nullptr, *Step = nullptr; 2271 const APInt *StartC, *StepC; 2272 if (!matchSimpleRecurrence(PN, BO, Start, Step) || 2273 !match(Start, m_APInt(StartC)) || StartC->isZero()) 2274 return false; 2275 2276 switch (BO->getOpcode()) { 2277 case Instruction::Add: 2278 // Starting from non-zero and stepping away from zero can never wrap back 2279 // to zero. 2280 return BO->hasNoUnsignedWrap() || 2281 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) && 2282 StartC->isNegative() == StepC->isNegative()); 2283 case Instruction::Mul: 2284 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) && 2285 match(Step, m_APInt(StepC)) && !StepC->isZero(); 2286 case Instruction::Shl: 2287 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap(); 2288 case Instruction::AShr: 2289 case Instruction::LShr: 2290 return BO->isExact(); 2291 default: 2292 return false; 2293 } 2294 } 2295 2296 /// Return true if the given value is known to be non-zero when defined. For 2297 /// vectors, return true if every demanded element is known to be non-zero when 2298 /// defined. For pointers, if the context instruction and dominator tree are 2299 /// specified, perform context-sensitive analysis and return true if the 2300 /// pointer couldn't possibly be null at the specified instruction. 2301 /// Supports values with integer or pointer type and vectors of integers. 2302 bool isKnownNonZero(const Value *V, const APInt &DemandedElts, unsigned Depth, 2303 const Query &Q) { 2304 // FIXME: We currently have no way to represent the DemandedElts of a scalable 2305 // vector 2306 if (isa<ScalableVectorType>(V->getType())) 2307 return false; 2308 2309 if (auto *C = dyn_cast<Constant>(V)) { 2310 if (C->isNullValue()) 2311 return false; 2312 if (isa<ConstantInt>(C)) 2313 // Must be non-zero due to null test above. 2314 return true; 2315 2316 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 2317 // See the comment for IntToPtr/PtrToInt instructions below. 2318 if (CE->getOpcode() == Instruction::IntToPtr || 2319 CE->getOpcode() == Instruction::PtrToInt) 2320 if (Q.DL.getTypeSizeInBits(CE->getOperand(0)->getType()) 2321 .getFixedSize() <= 2322 Q.DL.getTypeSizeInBits(CE->getType()).getFixedSize()) 2323 return isKnownNonZero(CE->getOperand(0), Depth, Q); 2324 } 2325 2326 // For constant vectors, check that all elements are undefined or known 2327 // non-zero to determine that the whole vector is known non-zero. 2328 if (auto *VecTy = dyn_cast<FixedVectorType>(C->getType())) { 2329 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) { 2330 if (!DemandedElts[i]) 2331 continue; 2332 Constant *Elt = C->getAggregateElement(i); 2333 if (!Elt || Elt->isNullValue()) 2334 return false; 2335 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt)) 2336 return false; 2337 } 2338 return true; 2339 } 2340 2341 // A global variable in address space 0 is non null unless extern weak 2342 // or an absolute symbol reference. Other address spaces may have null as a 2343 // valid address for a global, so we can't assume anything. 2344 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 2345 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() && 2346 GV->getType()->getAddressSpace() == 0) 2347 return true; 2348 } else 2349 return false; 2350 } 2351 2352 if (auto *I = dyn_cast<Instruction>(V)) { 2353 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) { 2354 // If the possible ranges don't contain zero, then the value is 2355 // definitely non-zero. 2356 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) { 2357 const APInt ZeroValue(Ty->getBitWidth(), 0); 2358 if (rangeMetadataExcludesValue(Ranges, ZeroValue)) 2359 return true; 2360 } 2361 } 2362 } 2363 2364 if (isKnownNonZeroFromAssume(V, Q)) 2365 return true; 2366 2367 // Some of the tests below are recursive, so bail out if we hit the limit. 2368 if (Depth++ >= MaxAnalysisRecursionDepth) 2369 return false; 2370 2371 // Check for pointer simplifications. 2372 2373 if (PointerType *PtrTy = dyn_cast<PointerType>(V->getType())) { 2374 // Alloca never returns null, malloc might. 2375 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0) 2376 return true; 2377 2378 // A byval, inalloca may not be null in a non-default addres space. A 2379 // nonnull argument is assumed never 0. 2380 if (const Argument *A = dyn_cast<Argument>(V)) { 2381 if (((A->hasPassPointeeByValueCopyAttr() && 2382 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) || 2383 A->hasNonNullAttr())) 2384 return true; 2385 } 2386 2387 // A Load tagged with nonnull metadata is never null. 2388 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) 2389 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull)) 2390 return true; 2391 2392 if (const auto *Call = dyn_cast<CallBase>(V)) { 2393 if (Call->isReturnNonNull()) 2394 return true; 2395 if (const auto *RP = getArgumentAliasingToReturnedPointer(Call, true)) 2396 return isKnownNonZero(RP, Depth, Q); 2397 } 2398 } 2399 2400 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT)) 2401 return true; 2402 2403 // Check for recursive pointer simplifications. 2404 if (V->getType()->isPointerTy()) { 2405 // Look through bitcast operations, GEPs, and int2ptr instructions as they 2406 // do not alter the value, or at least not the nullness property of the 2407 // value, e.g., int2ptr is allowed to zero/sign extend the value. 2408 // 2409 // Note that we have to take special care to avoid looking through 2410 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well 2411 // as casts that can alter the value, e.g., AddrSpaceCasts. 2412 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) 2413 return isGEPKnownNonNull(GEP, Depth, Q); 2414 2415 if (auto *BCO = dyn_cast<BitCastOperator>(V)) 2416 return isKnownNonZero(BCO->getOperand(0), Depth, Q); 2417 2418 if (auto *I2P = dyn_cast<IntToPtrInst>(V)) 2419 if (Q.DL.getTypeSizeInBits(I2P->getSrcTy()).getFixedSize() <= 2420 Q.DL.getTypeSizeInBits(I2P->getDestTy()).getFixedSize()) 2421 return isKnownNonZero(I2P->getOperand(0), Depth, Q); 2422 } 2423 2424 // Similar to int2ptr above, we can look through ptr2int here if the cast 2425 // is a no-op or an extend and not a truncate. 2426 if (auto *P2I = dyn_cast<PtrToIntInst>(V)) 2427 if (Q.DL.getTypeSizeInBits(P2I->getSrcTy()).getFixedSize() <= 2428 Q.DL.getTypeSizeInBits(P2I->getDestTy()).getFixedSize()) 2429 return isKnownNonZero(P2I->getOperand(0), Depth, Q); 2430 2431 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL); 2432 2433 // X | Y != 0 if X != 0 or Y != 0. 2434 Value *X = nullptr, *Y = nullptr; 2435 if (match(V, m_Or(m_Value(X), m_Value(Y)))) 2436 return isKnownNonZero(X, DemandedElts, Depth, Q) || 2437 isKnownNonZero(Y, DemandedElts, Depth, Q); 2438 2439 // ext X != 0 if X != 0. 2440 if (isa<SExtInst>(V) || isa<ZExtInst>(V)) 2441 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q); 2442 2443 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined 2444 // if the lowest bit is shifted off the end. 2445 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) { 2446 // shl nuw can't remove any non-zero bits. 2447 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V); 2448 if (Q.IIQ.hasNoUnsignedWrap(BO)) 2449 return isKnownNonZero(X, Depth, Q); 2450 2451 KnownBits Known(BitWidth); 2452 computeKnownBits(X, DemandedElts, Known, Depth, Q); 2453 if (Known.One[0]) 2454 return true; 2455 } 2456 // shr X, Y != 0 if X is negative. Note that the value of the shift is not 2457 // defined if the sign bit is shifted off the end. 2458 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) { 2459 // shr exact can only shift out zero bits. 2460 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V); 2461 if (BO->isExact()) 2462 return isKnownNonZero(X, Depth, Q); 2463 2464 KnownBits Known = computeKnownBits(X, DemandedElts, Depth, Q); 2465 if (Known.isNegative()) 2466 return true; 2467 2468 // If the shifter operand is a constant, and all of the bits shifted 2469 // out are known to be zero, and X is known non-zero then at least one 2470 // non-zero bit must remain. 2471 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) { 2472 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1); 2473 // Is there a known one in the portion not shifted out? 2474 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal) 2475 return true; 2476 // Are all the bits to be shifted out known zero? 2477 if (Known.countMinTrailingZeros() >= ShiftVal) 2478 return isKnownNonZero(X, DemandedElts, Depth, Q); 2479 } 2480 } 2481 // div exact can only produce a zero if the dividend is zero. 2482 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) { 2483 return isKnownNonZero(X, DemandedElts, Depth, Q); 2484 } 2485 // X + Y. 2486 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) { 2487 KnownBits XKnown = computeKnownBits(X, DemandedElts, Depth, Q); 2488 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Depth, Q); 2489 2490 // If X and Y are both non-negative (as signed values) then their sum is not 2491 // zero unless both X and Y are zero. 2492 if (XKnown.isNonNegative() && YKnown.isNonNegative()) 2493 if (isKnownNonZero(X, DemandedElts, Depth, Q) || 2494 isKnownNonZero(Y, DemandedElts, Depth, Q)) 2495 return true; 2496 2497 // If X and Y are both negative (as signed values) then their sum is not 2498 // zero unless both X and Y equal INT_MIN. 2499 if (XKnown.isNegative() && YKnown.isNegative()) { 2500 APInt Mask = APInt::getSignedMaxValue(BitWidth); 2501 // The sign bit of X is set. If some other bit is set then X is not equal 2502 // to INT_MIN. 2503 if (XKnown.One.intersects(Mask)) 2504 return true; 2505 // The sign bit of Y is set. If some other bit is set then Y is not equal 2506 // to INT_MIN. 2507 if (YKnown.One.intersects(Mask)) 2508 return true; 2509 } 2510 2511 // The sum of a non-negative number and a power of two is not zero. 2512 if (XKnown.isNonNegative() && 2513 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q)) 2514 return true; 2515 if (YKnown.isNonNegative() && 2516 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q)) 2517 return true; 2518 } 2519 // X * Y. 2520 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) { 2521 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V); 2522 // If X and Y are non-zero then so is X * Y as long as the multiplication 2523 // does not overflow. 2524 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) && 2525 isKnownNonZero(X, DemandedElts, Depth, Q) && 2526 isKnownNonZero(Y, DemandedElts, Depth, Q)) 2527 return true; 2528 } 2529 // (C ? X : Y) != 0 if X != 0 and Y != 0. 2530 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 2531 if (isKnownNonZero(SI->getTrueValue(), DemandedElts, Depth, Q) && 2532 isKnownNonZero(SI->getFalseValue(), DemandedElts, Depth, Q)) 2533 return true; 2534 } 2535 // PHI 2536 else if (const PHINode *PN = dyn_cast<PHINode>(V)) { 2537 if (Q.IIQ.UseInstrInfo && isNonZeroRecurrence(PN)) 2538 return true; 2539 2540 // Check if all incoming values are non-zero using recursion. 2541 Query RecQ = Q; 2542 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1); 2543 return llvm::all_of(PN->operands(), [&](const Use &U) { 2544 if (U.get() == PN) 2545 return true; 2546 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator(); 2547 return isKnownNonZero(U.get(), DemandedElts, NewDepth, RecQ); 2548 }); 2549 } 2550 // ExtractElement 2551 else if (const auto *EEI = dyn_cast<ExtractElementInst>(V)) { 2552 const Value *Vec = EEI->getVectorOperand(); 2553 const Value *Idx = EEI->getIndexOperand(); 2554 auto *CIdx = dyn_cast<ConstantInt>(Idx); 2555 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) { 2556 unsigned NumElts = VecTy->getNumElements(); 2557 APInt DemandedVecElts = APInt::getAllOnes(NumElts); 2558 if (CIdx && CIdx->getValue().ult(NumElts)) 2559 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue()); 2560 return isKnownNonZero(Vec, DemandedVecElts, Depth, Q); 2561 } 2562 } 2563 // Freeze 2564 else if (const FreezeInst *FI = dyn_cast<FreezeInst>(V)) { 2565 auto *Op = FI->getOperand(0); 2566 if (isKnownNonZero(Op, Depth, Q) && 2567 isGuaranteedNotToBePoison(Op, Q.AC, Q.CxtI, Q.DT, Depth)) 2568 return true; 2569 } 2570 2571 KnownBits Known(BitWidth); 2572 computeKnownBits(V, DemandedElts, Known, Depth, Q); 2573 return Known.One != 0; 2574 } 2575 2576 bool isKnownNonZero(const Value* V, unsigned Depth, const Query& Q) { 2577 // FIXME: We currently have no way to represent the DemandedElts of a scalable 2578 // vector 2579 if (isa<ScalableVectorType>(V->getType())) 2580 return false; 2581 2582 auto *FVTy = dyn_cast<FixedVectorType>(V->getType()); 2583 APInt DemandedElts = 2584 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1); 2585 return isKnownNonZero(V, DemandedElts, Depth, Q); 2586 } 2587 2588 /// If the pair of operators are the same invertible function, return the 2589 /// the operands of the function corresponding to each input. Otherwise, 2590 /// return None. An invertible function is one that is 1-to-1 and maps 2591 /// every input value to exactly one output value. This is equivalent to 2592 /// saying that Op1 and Op2 are equal exactly when the specified pair of 2593 /// operands are equal, (except that Op1 and Op2 may be poison more often.) 2594 static Optional<std::pair<Value*, Value*>> 2595 getInvertibleOperands(const Operator *Op1, 2596 const Operator *Op2) { 2597 if (Op1->getOpcode() != Op2->getOpcode()) 2598 return None; 2599 2600 auto getOperands = [&](unsigned OpNum) -> auto { 2601 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum)); 2602 }; 2603 2604 switch (Op1->getOpcode()) { 2605 default: 2606 break; 2607 case Instruction::Add: 2608 case Instruction::Sub: 2609 if (Op1->getOperand(0) == Op2->getOperand(0)) 2610 return getOperands(1); 2611 if (Op1->getOperand(1) == Op2->getOperand(1)) 2612 return getOperands(0); 2613 break; 2614 case Instruction::Mul: { 2615 // invertible if A * B == (A * B) mod 2^N where A, and B are integers 2616 // and N is the bitwdith. The nsw case is non-obvious, but proven by 2617 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK 2618 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1); 2619 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2); 2620 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) && 2621 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap())) 2622 break; 2623 2624 // Assume operand order has been canonicalized 2625 if (Op1->getOperand(1) == Op2->getOperand(1) && 2626 isa<ConstantInt>(Op1->getOperand(1)) && 2627 !cast<ConstantInt>(Op1->getOperand(1))->isZero()) 2628 return getOperands(0); 2629 break; 2630 } 2631 case Instruction::Shl: { 2632 // Same as multiplies, with the difference that we don't need to check 2633 // for a non-zero multiply. Shifts always multiply by non-zero. 2634 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1); 2635 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2); 2636 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) && 2637 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap())) 2638 break; 2639 2640 if (Op1->getOperand(1) == Op2->getOperand(1)) 2641 return getOperands(0); 2642 break; 2643 } 2644 case Instruction::AShr: 2645 case Instruction::LShr: { 2646 auto *PEO1 = cast<PossiblyExactOperator>(Op1); 2647 auto *PEO2 = cast<PossiblyExactOperator>(Op2); 2648 if (!PEO1->isExact() || !PEO2->isExact()) 2649 break; 2650 2651 if (Op1->getOperand(1) == Op2->getOperand(1)) 2652 return getOperands(0); 2653 break; 2654 } 2655 case Instruction::SExt: 2656 case Instruction::ZExt: 2657 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType()) 2658 return getOperands(0); 2659 break; 2660 case Instruction::PHI: { 2661 const PHINode *PN1 = cast<PHINode>(Op1); 2662 const PHINode *PN2 = cast<PHINode>(Op2); 2663 2664 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences 2665 // are a single invertible function of the start values? Note that repeated 2666 // application of an invertible function is also invertible 2667 BinaryOperator *BO1 = nullptr; 2668 Value *Start1 = nullptr, *Step1 = nullptr; 2669 BinaryOperator *BO2 = nullptr; 2670 Value *Start2 = nullptr, *Step2 = nullptr; 2671 if (PN1->getParent() != PN2->getParent() || 2672 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) || 2673 !matchSimpleRecurrence(PN2, BO2, Start2, Step2)) 2674 break; 2675 2676 auto Values = getInvertibleOperands(cast<Operator>(BO1), 2677 cast<Operator>(BO2)); 2678 if (!Values) 2679 break; 2680 2681 // We have to be careful of mutually defined recurrences here. Ex: 2682 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V 2683 // * X_i = Y_i = X_(i-1) OP Y_(i-1) 2684 // The invertibility of these is complicated, and not worth reasoning 2685 // about (yet?). 2686 if (Values->first != PN1 || Values->second != PN2) 2687 break; 2688 2689 return std::make_pair(Start1, Start2); 2690 } 2691 } 2692 return None; 2693 } 2694 2695 /// Return true if V2 == V1 + X, where X is known non-zero. 2696 static bool isAddOfNonZero(const Value *V1, const Value *V2, unsigned Depth, 2697 const Query &Q) { 2698 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1); 2699 if (!BO || BO->getOpcode() != Instruction::Add) 2700 return false; 2701 Value *Op = nullptr; 2702 if (V2 == BO->getOperand(0)) 2703 Op = BO->getOperand(1); 2704 else if (V2 == BO->getOperand(1)) 2705 Op = BO->getOperand(0); 2706 else 2707 return false; 2708 return isKnownNonZero(Op, Depth + 1, Q); 2709 } 2710 2711 /// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and 2712 /// the multiplication is nuw or nsw. 2713 static bool isNonEqualMul(const Value *V1, const Value *V2, unsigned Depth, 2714 const Query &Q) { 2715 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) { 2716 const APInt *C; 2717 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) && 2718 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) && 2719 !C->isZero() && !C->isOne() && isKnownNonZero(V1, Depth + 1, Q); 2720 } 2721 return false; 2722 } 2723 2724 /// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and 2725 /// the shift is nuw or nsw. 2726 static bool isNonEqualShl(const Value *V1, const Value *V2, unsigned Depth, 2727 const Query &Q) { 2728 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) { 2729 const APInt *C; 2730 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) && 2731 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) && 2732 !C->isZero() && isKnownNonZero(V1, Depth + 1, Q); 2733 } 2734 return false; 2735 } 2736 2737 static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, 2738 unsigned Depth, const Query &Q) { 2739 // Check two PHIs are in same block. 2740 if (PN1->getParent() != PN2->getParent()) 2741 return false; 2742 2743 SmallPtrSet<const BasicBlock *, 8> VisitedBBs; 2744 bool UsedFullRecursion = false; 2745 for (const BasicBlock *IncomBB : PN1->blocks()) { 2746 if (!VisitedBBs.insert(IncomBB).second) 2747 continue; // Don't reprocess blocks that we have dealt with already. 2748 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB); 2749 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB); 2750 const APInt *C1, *C2; 2751 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2) 2752 continue; 2753 2754 // Only one pair of phi operands is allowed for full recursion. 2755 if (UsedFullRecursion) 2756 return false; 2757 2758 Query RecQ = Q; 2759 RecQ.CxtI = IncomBB->getTerminator(); 2760 if (!isKnownNonEqual(IV1, IV2, Depth + 1, RecQ)) 2761 return false; 2762 UsedFullRecursion = true; 2763 } 2764 return true; 2765 } 2766 2767 /// Return true if it is known that V1 != V2. 2768 static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth, 2769 const Query &Q) { 2770 if (V1 == V2) 2771 return false; 2772 if (V1->getType() != V2->getType()) 2773 // We can't look through casts yet. 2774 return false; 2775 2776 if (Depth >= MaxAnalysisRecursionDepth) 2777 return false; 2778 2779 // See if we can recurse through (exactly one of) our operands. This 2780 // requires our operation be 1-to-1 and map every input value to exactly 2781 // one output value. Such an operation is invertible. 2782 auto *O1 = dyn_cast<Operator>(V1); 2783 auto *O2 = dyn_cast<Operator>(V2); 2784 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) { 2785 if (auto Values = getInvertibleOperands(O1, O2)) 2786 return isKnownNonEqual(Values->first, Values->second, Depth + 1, Q); 2787 2788 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) { 2789 const PHINode *PN2 = cast<PHINode>(V2); 2790 // FIXME: This is missing a generalization to handle the case where one is 2791 // a PHI and another one isn't. 2792 if (isNonEqualPHIs(PN1, PN2, Depth, Q)) 2793 return true; 2794 }; 2795 } 2796 2797 if (isAddOfNonZero(V1, V2, Depth, Q) || isAddOfNonZero(V2, V1, Depth, Q)) 2798 return true; 2799 2800 if (isNonEqualMul(V1, V2, Depth, Q) || isNonEqualMul(V2, V1, Depth, Q)) 2801 return true; 2802 2803 if (isNonEqualShl(V1, V2, Depth, Q) || isNonEqualShl(V2, V1, Depth, Q)) 2804 return true; 2805 2806 if (V1->getType()->isIntOrIntVectorTy()) { 2807 // Are any known bits in V1 contradictory to known bits in V2? If V1 2808 // has a known zero where V2 has a known one, they must not be equal. 2809 KnownBits Known1 = computeKnownBits(V1, Depth, Q); 2810 KnownBits Known2 = computeKnownBits(V2, Depth, Q); 2811 2812 if (Known1.Zero.intersects(Known2.One) || 2813 Known2.Zero.intersects(Known1.One)) 2814 return true; 2815 } 2816 return false; 2817 } 2818 2819 /// Return true if 'V & Mask' is known to be zero. We use this predicate to 2820 /// simplify operations downstream. Mask is known to be zero for bits that V 2821 /// cannot have. 2822 /// 2823 /// This function is defined on values with integer type, values with pointer 2824 /// type, and vectors of integers. In the case 2825 /// where V is a vector, the mask, known zero, and known one values are the 2826 /// same width as the vector element, and the bit is set only if it is true 2827 /// for all of the elements in the vector. 2828 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth, 2829 const Query &Q) { 2830 KnownBits Known(Mask.getBitWidth()); 2831 computeKnownBits(V, Known, Depth, Q); 2832 return Mask.isSubsetOf(Known.Zero); 2833 } 2834 2835 // Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow). 2836 // Returns the input and lower/upper bounds. 2837 static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, 2838 const APInt *&CLow, const APInt *&CHigh) { 2839 assert(isa<Operator>(Select) && 2840 cast<Operator>(Select)->getOpcode() == Instruction::Select && 2841 "Input should be a Select!"); 2842 2843 const Value *LHS = nullptr, *RHS = nullptr; 2844 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor; 2845 if (SPF != SPF_SMAX && SPF != SPF_SMIN) 2846 return false; 2847 2848 if (!match(RHS, m_APInt(CLow))) 2849 return false; 2850 2851 const Value *LHS2 = nullptr, *RHS2 = nullptr; 2852 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor; 2853 if (getInverseMinMaxFlavor(SPF) != SPF2) 2854 return false; 2855 2856 if (!match(RHS2, m_APInt(CHigh))) 2857 return false; 2858 2859 if (SPF == SPF_SMIN) 2860 std::swap(CLow, CHigh); 2861 2862 In = LHS2; 2863 return CLow->sle(*CHigh); 2864 } 2865 2866 /// For vector constants, loop over the elements and find the constant with the 2867 /// minimum number of sign bits. Return 0 if the value is not a vector constant 2868 /// or if any element was not analyzed; otherwise, return the count for the 2869 /// element with the minimum number of sign bits. 2870 static unsigned computeNumSignBitsVectorConstant(const Value *V, 2871 const APInt &DemandedElts, 2872 unsigned TyBits) { 2873 const auto *CV = dyn_cast<Constant>(V); 2874 if (!CV || !isa<FixedVectorType>(CV->getType())) 2875 return 0; 2876 2877 unsigned MinSignBits = TyBits; 2878 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements(); 2879 for (unsigned i = 0; i != NumElts; ++i) { 2880 if (!DemandedElts[i]) 2881 continue; 2882 // If we find a non-ConstantInt, bail out. 2883 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i)); 2884 if (!Elt) 2885 return 0; 2886 2887 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits()); 2888 } 2889 2890 return MinSignBits; 2891 } 2892 2893 static unsigned ComputeNumSignBitsImpl(const Value *V, 2894 const APInt &DemandedElts, 2895 unsigned Depth, const Query &Q); 2896 2897 static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts, 2898 unsigned Depth, const Query &Q) { 2899 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Depth, Q); 2900 assert(Result > 0 && "At least one sign bit needs to be present!"); 2901 return Result; 2902 } 2903 2904 /// Return the number of times the sign bit of the register is replicated into 2905 /// the other bits. We know that at least 1 bit is always equal to the sign bit 2906 /// (itself), but other cases can give us information. For example, immediately 2907 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each 2908 /// other, so we return 3. For vectors, return the number of sign bits for the 2909 /// vector element with the minimum number of known sign bits of the demanded 2910 /// elements in the vector specified by DemandedElts. 2911 static unsigned ComputeNumSignBitsImpl(const Value *V, 2912 const APInt &DemandedElts, 2913 unsigned Depth, const Query &Q) { 2914 Type *Ty = V->getType(); 2915 2916 // FIXME: We currently have no way to represent the DemandedElts of a scalable 2917 // vector 2918 if (isa<ScalableVectorType>(Ty)) 2919 return 1; 2920 2921 #ifndef NDEBUG 2922 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth"); 2923 2924 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) { 2925 assert( 2926 FVTy->getNumElements() == DemandedElts.getBitWidth() && 2927 "DemandedElt width should equal the fixed vector number of elements"); 2928 } else { 2929 assert(DemandedElts == APInt(1, 1) && 2930 "DemandedElt width should be 1 for scalars"); 2931 } 2932 #endif 2933 2934 // We return the minimum number of sign bits that are guaranteed to be present 2935 // in V, so for undef we have to conservatively return 1. We don't have the 2936 // same behavior for poison though -- that's a FIXME today. 2937 2938 Type *ScalarTy = Ty->getScalarType(); 2939 unsigned TyBits = ScalarTy->isPointerTy() ? 2940 Q.DL.getPointerTypeSizeInBits(ScalarTy) : 2941 Q.DL.getTypeSizeInBits(ScalarTy); 2942 2943 unsigned Tmp, Tmp2; 2944 unsigned FirstAnswer = 1; 2945 2946 // Note that ConstantInt is handled by the general computeKnownBits case 2947 // below. 2948 2949 if (Depth == MaxAnalysisRecursionDepth) 2950 return 1; 2951 2952 if (auto *U = dyn_cast<Operator>(V)) { 2953 switch (Operator::getOpcode(V)) { 2954 default: break; 2955 case Instruction::SExt: 2956 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits(); 2957 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp; 2958 2959 case Instruction::SDiv: { 2960 const APInt *Denominator; 2961 // sdiv X, C -> adds log(C) sign bits. 2962 if (match(U->getOperand(1), m_APInt(Denominator))) { 2963 2964 // Ignore non-positive denominator. 2965 if (!Denominator->isStrictlyPositive()) 2966 break; 2967 2968 // Calculate the incoming numerator bits. 2969 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2970 2971 // Add floor(log(C)) bits to the numerator bits. 2972 return std::min(TyBits, NumBits + Denominator->logBase2()); 2973 } 2974 break; 2975 } 2976 2977 case Instruction::SRem: { 2978 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2979 2980 const APInt *Denominator; 2981 // srem X, C -> we know that the result is within [-C+1,C) when C is a 2982 // positive constant. This let us put a lower bound on the number of sign 2983 // bits. 2984 if (match(U->getOperand(1), m_APInt(Denominator))) { 2985 2986 // Ignore non-positive denominator. 2987 if (Denominator->isStrictlyPositive()) { 2988 // Calculate the leading sign bit constraints by examining the 2989 // denominator. Given that the denominator is positive, there are two 2990 // cases: 2991 // 2992 // 1. The numerator is positive. The result range is [0,C) and 2993 // [0,C) u< (1 << ceilLogBase2(C)). 2994 // 2995 // 2. The numerator is negative. Then the result range is (-C,0] and 2996 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)). 2997 // 2998 // Thus a lower bound on the number of sign bits is `TyBits - 2999 // ceilLogBase2(C)`. 3000 3001 unsigned ResBits = TyBits - Denominator->ceilLogBase2(); 3002 Tmp = std::max(Tmp, ResBits); 3003 } 3004 } 3005 return Tmp; 3006 } 3007 3008 case Instruction::AShr: { 3009 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3010 // ashr X, C -> adds C sign bits. Vectors too. 3011 const APInt *ShAmt; 3012 if (match(U->getOperand(1), m_APInt(ShAmt))) { 3013 if (ShAmt->uge(TyBits)) 3014 break; // Bad shift. 3015 unsigned ShAmtLimited = ShAmt->getZExtValue(); 3016 Tmp += ShAmtLimited; 3017 if (Tmp > TyBits) Tmp = TyBits; 3018 } 3019 return Tmp; 3020 } 3021 case Instruction::Shl: { 3022 const APInt *ShAmt; 3023 if (match(U->getOperand(1), m_APInt(ShAmt))) { 3024 // shl destroys sign bits. 3025 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3026 if (ShAmt->uge(TyBits) || // Bad shift. 3027 ShAmt->uge(Tmp)) break; // Shifted all sign bits out. 3028 Tmp2 = ShAmt->getZExtValue(); 3029 return Tmp - Tmp2; 3030 } 3031 break; 3032 } 3033 case Instruction::And: 3034 case Instruction::Or: 3035 case Instruction::Xor: // NOT is handled here. 3036 // Logical binary ops preserve the number of sign bits at the worst. 3037 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3038 if (Tmp != 1) { 3039 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 3040 FirstAnswer = std::min(Tmp, Tmp2); 3041 // We computed what we know about the sign bits as our first 3042 // answer. Now proceed to the generic code that uses 3043 // computeKnownBits, and pick whichever answer is better. 3044 } 3045 break; 3046 3047 case Instruction::Select: { 3048 // If we have a clamp pattern, we know that the number of sign bits will 3049 // be the minimum of the clamp min/max range. 3050 const Value *X; 3051 const APInt *CLow, *CHigh; 3052 if (isSignedMinMaxClamp(U, X, CLow, CHigh)) 3053 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits()); 3054 3055 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 3056 if (Tmp == 1) break; 3057 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q); 3058 return std::min(Tmp, Tmp2); 3059 } 3060 3061 case Instruction::Add: 3062 // Add can have at most one carry bit. Thus we know that the output 3063 // is, at worst, one more bit than the inputs. 3064 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3065 if (Tmp == 1) break; 3066 3067 // Special case decrementing a value (ADD X, -1): 3068 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1))) 3069 if (CRHS->isAllOnesValue()) { 3070 KnownBits Known(TyBits); 3071 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q); 3072 3073 // If the input is known to be 0 or 1, the output is 0/-1, which is 3074 // all sign bits set. 3075 if ((Known.Zero | 1).isAllOnes()) 3076 return TyBits; 3077 3078 // If we are subtracting one from a positive number, there is no carry 3079 // out of the result. 3080 if (Known.isNonNegative()) 3081 return Tmp; 3082 } 3083 3084 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 3085 if (Tmp2 == 1) break; 3086 return std::min(Tmp, Tmp2) - 1; 3087 3088 case Instruction::Sub: 3089 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 3090 if (Tmp2 == 1) break; 3091 3092 // Handle NEG. 3093 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0))) 3094 if (CLHS->isNullValue()) { 3095 KnownBits Known(TyBits); 3096 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q); 3097 // If the input is known to be 0 or 1, the output is 0/-1, which is 3098 // all sign bits set. 3099 if ((Known.Zero | 1).isAllOnes()) 3100 return TyBits; 3101 3102 // If the input is known to be positive (the sign bit is known clear), 3103 // the output of the NEG has the same number of sign bits as the 3104 // input. 3105 if (Known.isNonNegative()) 3106 return Tmp2; 3107 3108 // Otherwise, we treat this like a SUB. 3109 } 3110 3111 // Sub can have at most one carry bit. Thus we know that the output 3112 // is, at worst, one more bit than the inputs. 3113 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3114 if (Tmp == 1) break; 3115 return std::min(Tmp, Tmp2) - 1; 3116 3117 case Instruction::Mul: { 3118 // The output of the Mul can be at most twice the valid bits in the 3119 // inputs. 3120 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3121 if (SignBitsOp0 == 1) break; 3122 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 3123 if (SignBitsOp1 == 1) break; 3124 unsigned OutValidBits = 3125 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1); 3126 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1; 3127 } 3128 3129 case Instruction::PHI: { 3130 const PHINode *PN = cast<PHINode>(U); 3131 unsigned NumIncomingValues = PN->getNumIncomingValues(); 3132 // Don't analyze large in-degree PHIs. 3133 if (NumIncomingValues > 4) break; 3134 // Unreachable blocks may have zero-operand PHI nodes. 3135 if (NumIncomingValues == 0) break; 3136 3137 // Take the minimum of all incoming values. This can't infinitely loop 3138 // because of our depth threshold. 3139 Query RecQ = Q; 3140 Tmp = TyBits; 3141 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) { 3142 if (Tmp == 1) return Tmp; 3143 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator(); 3144 Tmp = std::min( 3145 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, RecQ)); 3146 } 3147 return Tmp; 3148 } 3149 3150 case Instruction::Trunc: 3151 // FIXME: it's tricky to do anything useful for this, but it is an 3152 // important case for targets like X86. 3153 break; 3154 3155 case Instruction::ExtractElement: 3156 // Look through extract element. At the moment we keep this simple and 3157 // skip tracking the specific element. But at least we might find 3158 // information valid for all elements of the vector (for example if vector 3159 // is sign extended, shifted, etc). 3160 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3161 3162 case Instruction::ShuffleVector: { 3163 // Collect the minimum number of sign bits that are shared by every vector 3164 // element referenced by the shuffle. 3165 auto *Shuf = dyn_cast<ShuffleVectorInst>(U); 3166 if (!Shuf) { 3167 // FIXME: Add support for shufflevector constant expressions. 3168 return 1; 3169 } 3170 APInt DemandedLHS, DemandedRHS; 3171 // For undef elements, we don't know anything about the common state of 3172 // the shuffle result. 3173 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) 3174 return 1; 3175 Tmp = std::numeric_limits<unsigned>::max(); 3176 if (!!DemandedLHS) { 3177 const Value *LHS = Shuf->getOperand(0); 3178 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Depth + 1, Q); 3179 } 3180 // If we don't know anything, early out and try computeKnownBits 3181 // fall-back. 3182 if (Tmp == 1) 3183 break; 3184 if (!!DemandedRHS) { 3185 const Value *RHS = Shuf->getOperand(1); 3186 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Depth + 1, Q); 3187 Tmp = std::min(Tmp, Tmp2); 3188 } 3189 // If we don't know anything, early out and try computeKnownBits 3190 // fall-back. 3191 if (Tmp == 1) 3192 break; 3193 assert(Tmp <= TyBits && "Failed to determine minimum sign bits"); 3194 return Tmp; 3195 } 3196 case Instruction::Call: { 3197 if (const auto *II = dyn_cast<IntrinsicInst>(U)) { 3198 switch (II->getIntrinsicID()) { 3199 default: break; 3200 case Intrinsic::abs: 3201 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 3202 if (Tmp == 1) break; 3203 3204 // Absolute value reduces number of sign bits by at most 1. 3205 return Tmp - 1; 3206 } 3207 } 3208 } 3209 } 3210 } 3211 3212 // Finally, if we can prove that the top bits of the result are 0's or 1's, 3213 // use this information. 3214 3215 // If we can examine all elements of a vector constant successfully, we're 3216 // done (we can't do any better than that). If not, keep trying. 3217 if (unsigned VecSignBits = 3218 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits)) 3219 return VecSignBits; 3220 3221 KnownBits Known(TyBits); 3222 computeKnownBits(V, DemandedElts, Known, Depth, Q); 3223 3224 // If we know that the sign bit is either zero or one, determine the number of 3225 // identical bits in the top of the input value. 3226 return std::max(FirstAnswer, Known.countMinSignBits()); 3227 } 3228 3229 /// This function computes the integer multiple of Base that equals V. 3230 /// If successful, it returns true and returns the multiple in 3231 /// Multiple. If unsuccessful, it returns false. It looks 3232 /// through SExt instructions only if LookThroughSExt is true. 3233 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple, 3234 bool LookThroughSExt, unsigned Depth) { 3235 assert(V && "No Value?"); 3236 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth"); 3237 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!"); 3238 3239 Type *T = V->getType(); 3240 3241 ConstantInt *CI = dyn_cast<ConstantInt>(V); 3242 3243 if (Base == 0) 3244 return false; 3245 3246 if (Base == 1) { 3247 Multiple = V; 3248 return true; 3249 } 3250 3251 ConstantExpr *CO = dyn_cast<ConstantExpr>(V); 3252 Constant *BaseVal = ConstantInt::get(T, Base); 3253 if (CO && CO == BaseVal) { 3254 // Multiple is 1. 3255 Multiple = ConstantInt::get(T, 1); 3256 return true; 3257 } 3258 3259 if (CI && CI->getZExtValue() % Base == 0) { 3260 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base); 3261 return true; 3262 } 3263 3264 if (Depth == MaxAnalysisRecursionDepth) return false; 3265 3266 Operator *I = dyn_cast<Operator>(V); 3267 if (!I) return false; 3268 3269 switch (I->getOpcode()) { 3270 default: break; 3271 case Instruction::SExt: 3272 if (!LookThroughSExt) return false; 3273 // otherwise fall through to ZExt 3274 LLVM_FALLTHROUGH; 3275 case Instruction::ZExt: 3276 return ComputeMultiple(I->getOperand(0), Base, Multiple, 3277 LookThroughSExt, Depth+1); 3278 case Instruction::Shl: 3279 case Instruction::Mul: { 3280 Value *Op0 = I->getOperand(0); 3281 Value *Op1 = I->getOperand(1); 3282 3283 if (I->getOpcode() == Instruction::Shl) { 3284 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1); 3285 if (!Op1CI) return false; 3286 // Turn Op0 << Op1 into Op0 * 2^Op1 3287 APInt Op1Int = Op1CI->getValue(); 3288 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1); 3289 APInt API(Op1Int.getBitWidth(), 0); 3290 API.setBit(BitToSet); 3291 Op1 = ConstantInt::get(V->getContext(), API); 3292 } 3293 3294 Value *Mul0 = nullptr; 3295 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) { 3296 if (Constant *Op1C = dyn_cast<Constant>(Op1)) 3297 if (Constant *MulC = dyn_cast<Constant>(Mul0)) { 3298 if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() < 3299 MulC->getType()->getPrimitiveSizeInBits().getFixedSize()) 3300 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType()); 3301 if (Op1C->getType()->getPrimitiveSizeInBits().getFixedSize() > 3302 MulC->getType()->getPrimitiveSizeInBits().getFixedSize()) 3303 MulC = ConstantExpr::getZExt(MulC, Op1C->getType()); 3304 3305 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1) 3306 Multiple = ConstantExpr::getMul(MulC, Op1C); 3307 return true; 3308 } 3309 3310 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0)) 3311 if (Mul0CI->getValue() == 1) { 3312 // V == Base * Op1, so return Op1 3313 Multiple = Op1; 3314 return true; 3315 } 3316 } 3317 3318 Value *Mul1 = nullptr; 3319 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) { 3320 if (Constant *Op0C = dyn_cast<Constant>(Op0)) 3321 if (Constant *MulC = dyn_cast<Constant>(Mul1)) { 3322 if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() < 3323 MulC->getType()->getPrimitiveSizeInBits().getFixedSize()) 3324 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType()); 3325 if (Op0C->getType()->getPrimitiveSizeInBits().getFixedSize() > 3326 MulC->getType()->getPrimitiveSizeInBits().getFixedSize()) 3327 MulC = ConstantExpr::getZExt(MulC, Op0C->getType()); 3328 3329 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0) 3330 Multiple = ConstantExpr::getMul(MulC, Op0C); 3331 return true; 3332 } 3333 3334 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1)) 3335 if (Mul1CI->getValue() == 1) { 3336 // V == Base * Op0, so return Op0 3337 Multiple = Op0; 3338 return true; 3339 } 3340 } 3341 } 3342 } 3343 3344 // We could not determine if V is a multiple of Base. 3345 return false; 3346 } 3347 3348 Intrinsic::ID llvm::getIntrinsicForCallSite(const CallBase &CB, 3349 const TargetLibraryInfo *TLI) { 3350 const Function *F = CB.getCalledFunction(); 3351 if (!F) 3352 return Intrinsic::not_intrinsic; 3353 3354 if (F->isIntrinsic()) 3355 return F->getIntrinsicID(); 3356 3357 // We are going to infer semantics of a library function based on mapping it 3358 // to an LLVM intrinsic. Check that the library function is available from 3359 // this callbase and in this environment. 3360 LibFunc Func; 3361 if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) || 3362 !CB.onlyReadsMemory()) 3363 return Intrinsic::not_intrinsic; 3364 3365 switch (Func) { 3366 default: 3367 break; 3368 case LibFunc_sin: 3369 case LibFunc_sinf: 3370 case LibFunc_sinl: 3371 return Intrinsic::sin; 3372 case LibFunc_cos: 3373 case LibFunc_cosf: 3374 case LibFunc_cosl: 3375 return Intrinsic::cos; 3376 case LibFunc_exp: 3377 case LibFunc_expf: 3378 case LibFunc_expl: 3379 return Intrinsic::exp; 3380 case LibFunc_exp2: 3381 case LibFunc_exp2f: 3382 case LibFunc_exp2l: 3383 return Intrinsic::exp2; 3384 case LibFunc_log: 3385 case LibFunc_logf: 3386 case LibFunc_logl: 3387 return Intrinsic::log; 3388 case LibFunc_log10: 3389 case LibFunc_log10f: 3390 case LibFunc_log10l: 3391 return Intrinsic::log10; 3392 case LibFunc_log2: 3393 case LibFunc_log2f: 3394 case LibFunc_log2l: 3395 return Intrinsic::log2; 3396 case LibFunc_fabs: 3397 case LibFunc_fabsf: 3398 case LibFunc_fabsl: 3399 return Intrinsic::fabs; 3400 case LibFunc_fmin: 3401 case LibFunc_fminf: 3402 case LibFunc_fminl: 3403 return Intrinsic::minnum; 3404 case LibFunc_fmax: 3405 case LibFunc_fmaxf: 3406 case LibFunc_fmaxl: 3407 return Intrinsic::maxnum; 3408 case LibFunc_copysign: 3409 case LibFunc_copysignf: 3410 case LibFunc_copysignl: 3411 return Intrinsic::copysign; 3412 case LibFunc_floor: 3413 case LibFunc_floorf: 3414 case LibFunc_floorl: 3415 return Intrinsic::floor; 3416 case LibFunc_ceil: 3417 case LibFunc_ceilf: 3418 case LibFunc_ceill: 3419 return Intrinsic::ceil; 3420 case LibFunc_trunc: 3421 case LibFunc_truncf: 3422 case LibFunc_truncl: 3423 return Intrinsic::trunc; 3424 case LibFunc_rint: 3425 case LibFunc_rintf: 3426 case LibFunc_rintl: 3427 return Intrinsic::rint; 3428 case LibFunc_nearbyint: 3429 case LibFunc_nearbyintf: 3430 case LibFunc_nearbyintl: 3431 return Intrinsic::nearbyint; 3432 case LibFunc_round: 3433 case LibFunc_roundf: 3434 case LibFunc_roundl: 3435 return Intrinsic::round; 3436 case LibFunc_roundeven: 3437 case LibFunc_roundevenf: 3438 case LibFunc_roundevenl: 3439 return Intrinsic::roundeven; 3440 case LibFunc_pow: 3441 case LibFunc_powf: 3442 case LibFunc_powl: 3443 return Intrinsic::pow; 3444 case LibFunc_sqrt: 3445 case LibFunc_sqrtf: 3446 case LibFunc_sqrtl: 3447 return Intrinsic::sqrt; 3448 } 3449 3450 return Intrinsic::not_intrinsic; 3451 } 3452 3453 /// Return true if we can prove that the specified FP value is never equal to 3454 /// -0.0. 3455 /// NOTE: Do not check 'nsz' here because that fast-math-flag does not guarantee 3456 /// that a value is not -0.0. It only guarantees that -0.0 may be treated 3457 /// the same as +0.0 in floating-point ops. 3458 /// 3459 /// NOTE: this function will need to be revisited when we support non-default 3460 /// rounding modes! 3461 bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI, 3462 unsigned Depth) { 3463 if (auto *CFP = dyn_cast<ConstantFP>(V)) 3464 return !CFP->getValueAPF().isNegZero(); 3465 3466 if (Depth == MaxAnalysisRecursionDepth) 3467 return false; 3468 3469 auto *Op = dyn_cast<Operator>(V); 3470 if (!Op) 3471 return false; 3472 3473 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0. 3474 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP()))) 3475 return true; 3476 3477 // sitofp and uitofp turn into +0.0 for zero. 3478 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op)) 3479 return true; 3480 3481 if (auto *Call = dyn_cast<CallInst>(Op)) { 3482 Intrinsic::ID IID = getIntrinsicForCallSite(*Call, TLI); 3483 switch (IID) { 3484 default: 3485 break; 3486 // sqrt(-0.0) = -0.0, no other negative results are possible. 3487 case Intrinsic::sqrt: 3488 case Intrinsic::canonicalize: 3489 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1); 3490 // fabs(x) != -0.0 3491 case Intrinsic::fabs: 3492 return true; 3493 } 3494 } 3495 3496 return false; 3497 } 3498 3499 /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a 3500 /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign 3501 /// bit despite comparing equal. 3502 static bool cannotBeOrderedLessThanZeroImpl(const Value *V, 3503 const TargetLibraryInfo *TLI, 3504 bool SignBitOnly, 3505 unsigned Depth) { 3506 // TODO: This function does not do the right thing when SignBitOnly is true 3507 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform 3508 // which flips the sign bits of NaNs. See 3509 // https://llvm.org/bugs/show_bug.cgi?id=31702. 3510 3511 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 3512 return !CFP->getValueAPF().isNegative() || 3513 (!SignBitOnly && CFP->getValueAPF().isZero()); 3514 } 3515 3516 // Handle vector of constants. 3517 if (auto *CV = dyn_cast<Constant>(V)) { 3518 if (auto *CVFVTy = dyn_cast<FixedVectorType>(CV->getType())) { 3519 unsigned NumElts = CVFVTy->getNumElements(); 3520 for (unsigned i = 0; i != NumElts; ++i) { 3521 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i)); 3522 if (!CFP) 3523 return false; 3524 if (CFP->getValueAPF().isNegative() && 3525 (SignBitOnly || !CFP->getValueAPF().isZero())) 3526 return false; 3527 } 3528 3529 // All non-negative ConstantFPs. 3530 return true; 3531 } 3532 } 3533 3534 if (Depth == MaxAnalysisRecursionDepth) 3535 return false; 3536 3537 const Operator *I = dyn_cast<Operator>(V); 3538 if (!I) 3539 return false; 3540 3541 switch (I->getOpcode()) { 3542 default: 3543 break; 3544 // Unsigned integers are always nonnegative. 3545 case Instruction::UIToFP: 3546 return true; 3547 case Instruction::FMul: 3548 case Instruction::FDiv: 3549 // X * X is always non-negative or a NaN. 3550 // X / X is always exactly 1.0 or a NaN. 3551 if (I->getOperand(0) == I->getOperand(1) && 3552 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs())) 3553 return true; 3554 3555 LLVM_FALLTHROUGH; 3556 case Instruction::FAdd: 3557 case Instruction::FRem: 3558 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 3559 Depth + 1) && 3560 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 3561 Depth + 1); 3562 case Instruction::Select: 3563 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 3564 Depth + 1) && 3565 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly, 3566 Depth + 1); 3567 case Instruction::FPExt: 3568 case Instruction::FPTrunc: 3569 // Widening/narrowing never change sign. 3570 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 3571 Depth + 1); 3572 case Instruction::ExtractElement: 3573 // Look through extract element. At the moment we keep this simple and skip 3574 // tracking the specific element. But at least we might find information 3575 // valid for all elements of the vector. 3576 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 3577 Depth + 1); 3578 case Instruction::Call: 3579 const auto *CI = cast<CallInst>(I); 3580 Intrinsic::ID IID = getIntrinsicForCallSite(*CI, TLI); 3581 switch (IID) { 3582 default: 3583 break; 3584 case Intrinsic::maxnum: { 3585 Value *V0 = I->getOperand(0), *V1 = I->getOperand(1); 3586 auto isPositiveNum = [&](Value *V) { 3587 if (SignBitOnly) { 3588 // With SignBitOnly, this is tricky because the result of 3589 // maxnum(+0.0, -0.0) is unspecified. Just check if the operand is 3590 // a constant strictly greater than 0.0. 3591 const APFloat *C; 3592 return match(V, m_APFloat(C)) && 3593 *C > APFloat::getZero(C->getSemantics()); 3594 } 3595 3596 // -0.0 compares equal to 0.0, so if this operand is at least -0.0, 3597 // maxnum can't be ordered-less-than-zero. 3598 return isKnownNeverNaN(V, TLI) && 3599 cannotBeOrderedLessThanZeroImpl(V, TLI, false, Depth + 1); 3600 }; 3601 3602 // TODO: This could be improved. We could also check that neither operand 3603 // has its sign bit set (and at least 1 is not-NAN?). 3604 return isPositiveNum(V0) || isPositiveNum(V1); 3605 } 3606 3607 case Intrinsic::maximum: 3608 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 3609 Depth + 1) || 3610 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 3611 Depth + 1); 3612 case Intrinsic::minnum: 3613 case Intrinsic::minimum: 3614 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 3615 Depth + 1) && 3616 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 3617 Depth + 1); 3618 case Intrinsic::exp: 3619 case Intrinsic::exp2: 3620 case Intrinsic::fabs: 3621 return true; 3622 3623 case Intrinsic::sqrt: 3624 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0. 3625 if (!SignBitOnly) 3626 return true; 3627 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() || 3628 CannotBeNegativeZero(CI->getOperand(0), TLI)); 3629 3630 case Intrinsic::powi: 3631 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) { 3632 // powi(x,n) is non-negative if n is even. 3633 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0) 3634 return true; 3635 } 3636 // TODO: This is not correct. Given that exp is an integer, here are the 3637 // ways that pow can return a negative value: 3638 // 3639 // pow(x, exp) --> negative if exp is odd and x is negative. 3640 // pow(-0, exp) --> -inf if exp is negative odd. 3641 // pow(-0, exp) --> -0 if exp is positive odd. 3642 // pow(-inf, exp) --> -0 if exp is negative odd. 3643 // pow(-inf, exp) --> -inf if exp is positive odd. 3644 // 3645 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN, 3646 // but we must return false if x == -0. Unfortunately we do not currently 3647 // have a way of expressing this constraint. See details in 3648 // https://llvm.org/bugs/show_bug.cgi?id=31702. 3649 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 3650 Depth + 1); 3651 3652 case Intrinsic::fma: 3653 case Intrinsic::fmuladd: 3654 // x*x+y is non-negative if y is non-negative. 3655 return I->getOperand(0) == I->getOperand(1) && 3656 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) && 3657 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly, 3658 Depth + 1); 3659 } 3660 break; 3661 } 3662 return false; 3663 } 3664 3665 bool llvm::CannotBeOrderedLessThanZero(const Value *V, 3666 const TargetLibraryInfo *TLI) { 3667 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0); 3668 } 3669 3670 bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) { 3671 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0); 3672 } 3673 3674 bool llvm::isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI, 3675 unsigned Depth) { 3676 assert(V->getType()->isFPOrFPVectorTy() && "Querying for Inf on non-FP type"); 3677 3678 // If we're told that infinities won't happen, assume they won't. 3679 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V)) 3680 if (FPMathOp->hasNoInfs()) 3681 return true; 3682 3683 // Handle scalar constants. 3684 if (auto *CFP = dyn_cast<ConstantFP>(V)) 3685 return !CFP->isInfinity(); 3686 3687 if (Depth == MaxAnalysisRecursionDepth) 3688 return false; 3689 3690 if (auto *Inst = dyn_cast<Instruction>(V)) { 3691 switch (Inst->getOpcode()) { 3692 case Instruction::Select: { 3693 return isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1) && 3694 isKnownNeverInfinity(Inst->getOperand(2), TLI, Depth + 1); 3695 } 3696 case Instruction::SIToFP: 3697 case Instruction::UIToFP: { 3698 // Get width of largest magnitude integer (remove a bit if signed). 3699 // This still works for a signed minimum value because the largest FP 3700 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx). 3701 int IntSize = Inst->getOperand(0)->getType()->getScalarSizeInBits(); 3702 if (Inst->getOpcode() == Instruction::SIToFP) 3703 --IntSize; 3704 3705 // If the exponent of the largest finite FP value can hold the largest 3706 // integer, the result of the cast must be finite. 3707 Type *FPTy = Inst->getType()->getScalarType(); 3708 return ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize; 3709 } 3710 default: 3711 break; 3712 } 3713 } 3714 3715 // try to handle fixed width vector constants 3716 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType()); 3717 if (VFVTy && isa<Constant>(V)) { 3718 // For vectors, verify that each element is not infinity. 3719 unsigned NumElts = VFVTy->getNumElements(); 3720 for (unsigned i = 0; i != NumElts; ++i) { 3721 Constant *Elt = cast<Constant>(V)->getAggregateElement(i); 3722 if (!Elt) 3723 return false; 3724 if (isa<UndefValue>(Elt)) 3725 continue; 3726 auto *CElt = dyn_cast<ConstantFP>(Elt); 3727 if (!CElt || CElt->isInfinity()) 3728 return false; 3729 } 3730 // All elements were confirmed non-infinity or undefined. 3731 return true; 3732 } 3733 3734 // was not able to prove that V never contains infinity 3735 return false; 3736 } 3737 3738 bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI, 3739 unsigned Depth) { 3740 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type"); 3741 3742 // If we're told that NaNs won't happen, assume they won't. 3743 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V)) 3744 if (FPMathOp->hasNoNaNs()) 3745 return true; 3746 3747 // Handle scalar constants. 3748 if (auto *CFP = dyn_cast<ConstantFP>(V)) 3749 return !CFP->isNaN(); 3750 3751 if (Depth == MaxAnalysisRecursionDepth) 3752 return false; 3753 3754 if (auto *Inst = dyn_cast<Instruction>(V)) { 3755 switch (Inst->getOpcode()) { 3756 case Instruction::FAdd: 3757 case Instruction::FSub: 3758 // Adding positive and negative infinity produces NaN. 3759 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) && 3760 isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) && 3761 (isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) || 3762 isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1)); 3763 3764 case Instruction::FMul: 3765 // Zero multiplied with infinity produces NaN. 3766 // FIXME: If neither side can be zero fmul never produces NaN. 3767 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) && 3768 isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) && 3769 isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) && 3770 isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1); 3771 3772 case Instruction::FDiv: 3773 case Instruction::FRem: 3774 // FIXME: Only 0/0, Inf/Inf, Inf REM x and x REM 0 produce NaN. 3775 return false; 3776 3777 case Instruction::Select: { 3778 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) && 3779 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1); 3780 } 3781 case Instruction::SIToFP: 3782 case Instruction::UIToFP: 3783 return true; 3784 case Instruction::FPTrunc: 3785 case Instruction::FPExt: 3786 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1); 3787 default: 3788 break; 3789 } 3790 } 3791 3792 if (const auto *II = dyn_cast<IntrinsicInst>(V)) { 3793 switch (II->getIntrinsicID()) { 3794 case Intrinsic::canonicalize: 3795 case Intrinsic::fabs: 3796 case Intrinsic::copysign: 3797 case Intrinsic::exp: 3798 case Intrinsic::exp2: 3799 case Intrinsic::floor: 3800 case Intrinsic::ceil: 3801 case Intrinsic::trunc: 3802 case Intrinsic::rint: 3803 case Intrinsic::nearbyint: 3804 case Intrinsic::round: 3805 case Intrinsic::roundeven: 3806 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1); 3807 case Intrinsic::sqrt: 3808 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) && 3809 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI); 3810 case Intrinsic::minnum: 3811 case Intrinsic::maxnum: 3812 // If either operand is not NaN, the result is not NaN. 3813 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) || 3814 isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1); 3815 default: 3816 return false; 3817 } 3818 } 3819 3820 // Try to handle fixed width vector constants 3821 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType()); 3822 if (VFVTy && isa<Constant>(V)) { 3823 // For vectors, verify that each element is not NaN. 3824 unsigned NumElts = VFVTy->getNumElements(); 3825 for (unsigned i = 0; i != NumElts; ++i) { 3826 Constant *Elt = cast<Constant>(V)->getAggregateElement(i); 3827 if (!Elt) 3828 return false; 3829 if (isa<UndefValue>(Elt)) 3830 continue; 3831 auto *CElt = dyn_cast<ConstantFP>(Elt); 3832 if (!CElt || CElt->isNaN()) 3833 return false; 3834 } 3835 // All elements were confirmed not-NaN or undefined. 3836 return true; 3837 } 3838 3839 // Was not able to prove that V never contains NaN 3840 return false; 3841 } 3842 3843 Value *llvm::isBytewiseValue(Value *V, const DataLayout &DL) { 3844 3845 // All byte-wide stores are splatable, even of arbitrary variables. 3846 if (V->getType()->isIntegerTy(8)) 3847 return V; 3848 3849 LLVMContext &Ctx = V->getContext(); 3850 3851 // Undef don't care. 3852 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx)); 3853 if (isa<UndefValue>(V)) 3854 return UndefInt8; 3855 3856 // Return Undef for zero-sized type. 3857 if (!DL.getTypeStoreSize(V->getType()).isNonZero()) 3858 return UndefInt8; 3859 3860 Constant *C = dyn_cast<Constant>(V); 3861 if (!C) { 3862 // Conceptually, we could handle things like: 3863 // %a = zext i8 %X to i16 3864 // %b = shl i16 %a, 8 3865 // %c = or i16 %a, %b 3866 // but until there is an example that actually needs this, it doesn't seem 3867 // worth worrying about. 3868 return nullptr; 3869 } 3870 3871 // Handle 'null' ConstantArrayZero etc. 3872 if (C->isNullValue()) 3873 return Constant::getNullValue(Type::getInt8Ty(Ctx)); 3874 3875 // Constant floating-point values can be handled as integer values if the 3876 // corresponding integer value is "byteable". An important case is 0.0. 3877 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 3878 Type *Ty = nullptr; 3879 if (CFP->getType()->isHalfTy()) 3880 Ty = Type::getInt16Ty(Ctx); 3881 else if (CFP->getType()->isFloatTy()) 3882 Ty = Type::getInt32Ty(Ctx); 3883 else if (CFP->getType()->isDoubleTy()) 3884 Ty = Type::getInt64Ty(Ctx); 3885 // Don't handle long double formats, which have strange constraints. 3886 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL) 3887 : nullptr; 3888 } 3889 3890 // We can handle constant integers that are multiple of 8 bits. 3891 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) { 3892 if (CI->getBitWidth() % 8 == 0) { 3893 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!"); 3894 if (!CI->getValue().isSplat(8)) 3895 return nullptr; 3896 return ConstantInt::get(Ctx, CI->getValue().trunc(8)); 3897 } 3898 } 3899 3900 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 3901 if (CE->getOpcode() == Instruction::IntToPtr) { 3902 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) { 3903 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace()); 3904 return isBytewiseValue( 3905 ConstantExpr::getIntegerCast(CE->getOperand(0), 3906 Type::getIntNTy(Ctx, BitWidth), false), 3907 DL); 3908 } 3909 } 3910 } 3911 3912 auto Merge = [&](Value *LHS, Value *RHS) -> Value * { 3913 if (LHS == RHS) 3914 return LHS; 3915 if (!LHS || !RHS) 3916 return nullptr; 3917 if (LHS == UndefInt8) 3918 return RHS; 3919 if (RHS == UndefInt8) 3920 return LHS; 3921 return nullptr; 3922 }; 3923 3924 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) { 3925 Value *Val = UndefInt8; 3926 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I) 3927 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL)))) 3928 return nullptr; 3929 return Val; 3930 } 3931 3932 if (isa<ConstantAggregate>(C)) { 3933 Value *Val = UndefInt8; 3934 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) 3935 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL)))) 3936 return nullptr; 3937 return Val; 3938 } 3939 3940 // Don't try to handle the handful of other constants. 3941 return nullptr; 3942 } 3943 3944 // This is the recursive version of BuildSubAggregate. It takes a few different 3945 // arguments. Idxs is the index within the nested struct From that we are 3946 // looking at now (which is of type IndexedType). IdxSkip is the number of 3947 // indices from Idxs that should be left out when inserting into the resulting 3948 // struct. To is the result struct built so far, new insertvalue instructions 3949 // build on that. 3950 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType, 3951 SmallVectorImpl<unsigned> &Idxs, 3952 unsigned IdxSkip, 3953 Instruction *InsertBefore) { 3954 StructType *STy = dyn_cast<StructType>(IndexedType); 3955 if (STy) { 3956 // Save the original To argument so we can modify it 3957 Value *OrigTo = To; 3958 // General case, the type indexed by Idxs is a struct 3959 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 3960 // Process each struct element recursively 3961 Idxs.push_back(i); 3962 Value *PrevTo = To; 3963 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, 3964 InsertBefore); 3965 Idxs.pop_back(); 3966 if (!To) { 3967 // Couldn't find any inserted value for this index? Cleanup 3968 while (PrevTo != OrigTo) { 3969 InsertValueInst* Del = cast<InsertValueInst>(PrevTo); 3970 PrevTo = Del->getAggregateOperand(); 3971 Del->eraseFromParent(); 3972 } 3973 // Stop processing elements 3974 break; 3975 } 3976 } 3977 // If we successfully found a value for each of our subaggregates 3978 if (To) 3979 return To; 3980 } 3981 // Base case, the type indexed by SourceIdxs is not a struct, or not all of 3982 // the struct's elements had a value that was inserted directly. In the latter 3983 // case, perhaps we can't determine each of the subelements individually, but 3984 // we might be able to find the complete struct somewhere. 3985 3986 // Find the value that is at that particular spot 3987 Value *V = FindInsertedValue(From, Idxs); 3988 3989 if (!V) 3990 return nullptr; 3991 3992 // Insert the value in the new (sub) aggregate 3993 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip), 3994 "tmp", InsertBefore); 3995 } 3996 3997 // This helper takes a nested struct and extracts a part of it (which is again a 3998 // struct) into a new value. For example, given the struct: 3999 // { a, { b, { c, d }, e } } 4000 // and the indices "1, 1" this returns 4001 // { c, d }. 4002 // 4003 // It does this by inserting an insertvalue for each element in the resulting 4004 // struct, as opposed to just inserting a single struct. This will only work if 4005 // each of the elements of the substruct are known (ie, inserted into From by an 4006 // insertvalue instruction somewhere). 4007 // 4008 // All inserted insertvalue instructions are inserted before InsertBefore 4009 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range, 4010 Instruction *InsertBefore) { 4011 assert(InsertBefore && "Must have someplace to insert!"); 4012 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), 4013 idx_range); 4014 Value *To = UndefValue::get(IndexedType); 4015 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end()); 4016 unsigned IdxSkip = Idxs.size(); 4017 4018 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore); 4019 } 4020 4021 /// Given an aggregate and a sequence of indices, see if the scalar value 4022 /// indexed is already around as a register, for example if it was inserted 4023 /// directly into the aggregate. 4024 /// 4025 /// If InsertBefore is not null, this function will duplicate (modified) 4026 /// insertvalues when a part of a nested struct is extracted. 4027 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range, 4028 Instruction *InsertBefore) { 4029 // Nothing to index? Just return V then (this is useful at the end of our 4030 // recursion). 4031 if (idx_range.empty()) 4032 return V; 4033 // We have indices, so V should have an indexable type. 4034 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) && 4035 "Not looking at a struct or array?"); 4036 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) && 4037 "Invalid indices for type?"); 4038 4039 if (Constant *C = dyn_cast<Constant>(V)) { 4040 C = C->getAggregateElement(idx_range[0]); 4041 if (!C) return nullptr; 4042 return FindInsertedValue(C, idx_range.slice(1), InsertBefore); 4043 } 4044 4045 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) { 4046 // Loop the indices for the insertvalue instruction in parallel with the 4047 // requested indices 4048 const unsigned *req_idx = idx_range.begin(); 4049 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); 4050 i != e; ++i, ++req_idx) { 4051 if (req_idx == idx_range.end()) { 4052 // We can't handle this without inserting insertvalues 4053 if (!InsertBefore) 4054 return nullptr; 4055 4056 // The requested index identifies a part of a nested aggregate. Handle 4057 // this specially. For example, 4058 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0 4059 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1 4060 // %C = extractvalue {i32, { i32, i32 } } %B, 1 4061 // This can be changed into 4062 // %A = insertvalue {i32, i32 } undef, i32 10, 0 4063 // %C = insertvalue {i32, i32 } %A, i32 11, 1 4064 // which allows the unused 0,0 element from the nested struct to be 4065 // removed. 4066 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx), 4067 InsertBefore); 4068 } 4069 4070 // This insert value inserts something else than what we are looking for. 4071 // See if the (aggregate) value inserted into has the value we are 4072 // looking for, then. 4073 if (*req_idx != *i) 4074 return FindInsertedValue(I->getAggregateOperand(), idx_range, 4075 InsertBefore); 4076 } 4077 // If we end up here, the indices of the insertvalue match with those 4078 // requested (though possibly only partially). Now we recursively look at 4079 // the inserted value, passing any remaining indices. 4080 return FindInsertedValue(I->getInsertedValueOperand(), 4081 makeArrayRef(req_idx, idx_range.end()), 4082 InsertBefore); 4083 } 4084 4085 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) { 4086 // If we're extracting a value from an aggregate that was extracted from 4087 // something else, we can extract from that something else directly instead. 4088 // However, we will need to chain I's indices with the requested indices. 4089 4090 // Calculate the number of indices required 4091 unsigned size = I->getNumIndices() + idx_range.size(); 4092 // Allocate some space to put the new indices in 4093 SmallVector<unsigned, 5> Idxs; 4094 Idxs.reserve(size); 4095 // Add indices from the extract value instruction 4096 Idxs.append(I->idx_begin(), I->idx_end()); 4097 4098 // Add requested indices 4099 Idxs.append(idx_range.begin(), idx_range.end()); 4100 4101 assert(Idxs.size() == size 4102 && "Number of indices added not correct?"); 4103 4104 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore); 4105 } 4106 // Otherwise, we don't know (such as, extracting from a function return value 4107 // or load instruction) 4108 return nullptr; 4109 } 4110 4111 bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP, 4112 unsigned CharSize) { 4113 // Make sure the GEP has exactly three arguments. 4114 if (GEP->getNumOperands() != 3) 4115 return false; 4116 4117 // Make sure the index-ee is a pointer to array of \p CharSize integers. 4118 // CharSize. 4119 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType()); 4120 if (!AT || !AT->getElementType()->isIntegerTy(CharSize)) 4121 return false; 4122 4123 // Check to make sure that the first operand of the GEP is an integer and 4124 // has value 0 so that we are sure we're indexing into the initializer. 4125 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1)); 4126 if (!FirstIdx || !FirstIdx->isZero()) 4127 return false; 4128 4129 return true; 4130 } 4131 4132 bool llvm::getConstantDataArrayInfo(const Value *V, 4133 ConstantDataArraySlice &Slice, 4134 unsigned ElementSize, uint64_t Offset) { 4135 assert(V); 4136 4137 // Look through bitcast instructions and geps. 4138 V = V->stripPointerCasts(); 4139 4140 // If the value is a GEP instruction or constant expression, treat it as an 4141 // offset. 4142 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 4143 // The GEP operator should be based on a pointer to string constant, and is 4144 // indexing into the string constant. 4145 if (!isGEPBasedOnPointerToString(GEP, ElementSize)) 4146 return false; 4147 4148 // If the second index isn't a ConstantInt, then this is a variable index 4149 // into the array. If this occurs, we can't say anything meaningful about 4150 // the string. 4151 uint64_t StartIdx = 0; 4152 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2))) 4153 StartIdx = CI->getZExtValue(); 4154 else 4155 return false; 4156 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize, 4157 StartIdx + Offset); 4158 } 4159 4160 // The GEP instruction, constant or instruction, must reference a global 4161 // variable that is a constant and is initialized. The referenced constant 4162 // initializer is the array that we'll use for optimization. 4163 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V); 4164 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer()) 4165 return false; 4166 4167 const ConstantDataArray *Array; 4168 ArrayType *ArrayTy; 4169 if (GV->getInitializer()->isNullValue()) { 4170 Type *GVTy = GV->getValueType(); 4171 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) { 4172 // A zeroinitializer for the array; there is no ConstantDataArray. 4173 Array = nullptr; 4174 } else { 4175 const DataLayout &DL = GV->getParent()->getDataLayout(); 4176 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedSize(); 4177 uint64_t Length = SizeInBytes / (ElementSize / 8); 4178 if (Length <= Offset) 4179 return false; 4180 4181 Slice.Array = nullptr; 4182 Slice.Offset = 0; 4183 Slice.Length = Length - Offset; 4184 return true; 4185 } 4186 } else { 4187 // This must be a ConstantDataArray. 4188 Array = dyn_cast<ConstantDataArray>(GV->getInitializer()); 4189 if (!Array) 4190 return false; 4191 ArrayTy = Array->getType(); 4192 } 4193 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize)) 4194 return false; 4195 4196 uint64_t NumElts = ArrayTy->getArrayNumElements(); 4197 if (Offset > NumElts) 4198 return false; 4199 4200 Slice.Array = Array; 4201 Slice.Offset = Offset; 4202 Slice.Length = NumElts - Offset; 4203 return true; 4204 } 4205 4206 /// This function computes the length of a null-terminated C string pointed to 4207 /// by V. If successful, it returns true and returns the string in Str. 4208 /// If unsuccessful, it returns false. 4209 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str, 4210 uint64_t Offset, bool TrimAtNul) { 4211 ConstantDataArraySlice Slice; 4212 if (!getConstantDataArrayInfo(V, Slice, 8, Offset)) 4213 return false; 4214 4215 if (Slice.Array == nullptr) { 4216 if (TrimAtNul) { 4217 Str = StringRef(); 4218 return true; 4219 } 4220 if (Slice.Length == 1) { 4221 Str = StringRef("", 1); 4222 return true; 4223 } 4224 // We cannot instantiate a StringRef as we do not have an appropriate string 4225 // of 0s at hand. 4226 return false; 4227 } 4228 4229 // Start out with the entire array in the StringRef. 4230 Str = Slice.Array->getAsString(); 4231 // Skip over 'offset' bytes. 4232 Str = Str.substr(Slice.Offset); 4233 4234 if (TrimAtNul) { 4235 // Trim off the \0 and anything after it. If the array is not nul 4236 // terminated, we just return the whole end of string. The client may know 4237 // some other way that the string is length-bound. 4238 Str = Str.substr(0, Str.find('\0')); 4239 } 4240 return true; 4241 } 4242 4243 // These next two are very similar to the above, but also look through PHI 4244 // nodes. 4245 // TODO: See if we can integrate these two together. 4246 4247 /// If we can compute the length of the string pointed to by 4248 /// the specified pointer, return 'len+1'. If we can't, return 0. 4249 static uint64_t GetStringLengthH(const Value *V, 4250 SmallPtrSetImpl<const PHINode*> &PHIs, 4251 unsigned CharSize) { 4252 // Look through noop bitcast instructions. 4253 V = V->stripPointerCasts(); 4254 4255 // If this is a PHI node, there are two cases: either we have already seen it 4256 // or we haven't. 4257 if (const PHINode *PN = dyn_cast<PHINode>(V)) { 4258 if (!PHIs.insert(PN).second) 4259 return ~0ULL; // already in the set. 4260 4261 // If it was new, see if all the input strings are the same length. 4262 uint64_t LenSoFar = ~0ULL; 4263 for (Value *IncValue : PN->incoming_values()) { 4264 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize); 4265 if (Len == 0) return 0; // Unknown length -> unknown. 4266 4267 if (Len == ~0ULL) continue; 4268 4269 if (Len != LenSoFar && LenSoFar != ~0ULL) 4270 return 0; // Disagree -> unknown. 4271 LenSoFar = Len; 4272 } 4273 4274 // Success, all agree. 4275 return LenSoFar; 4276 } 4277 4278 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y) 4279 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 4280 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize); 4281 if (Len1 == 0) return 0; 4282 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize); 4283 if (Len2 == 0) return 0; 4284 if (Len1 == ~0ULL) return Len2; 4285 if (Len2 == ~0ULL) return Len1; 4286 if (Len1 != Len2) return 0; 4287 return Len1; 4288 } 4289 4290 // Otherwise, see if we can read the string. 4291 ConstantDataArraySlice Slice; 4292 if (!getConstantDataArrayInfo(V, Slice, CharSize)) 4293 return 0; 4294 4295 if (Slice.Array == nullptr) 4296 return 1; 4297 4298 // Search for nul characters 4299 unsigned NullIndex = 0; 4300 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) { 4301 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0) 4302 break; 4303 } 4304 4305 return NullIndex + 1; 4306 } 4307 4308 /// If we can compute the length of the string pointed to by 4309 /// the specified pointer, return 'len+1'. If we can't, return 0. 4310 uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) { 4311 if (!V->getType()->isPointerTy()) 4312 return 0; 4313 4314 SmallPtrSet<const PHINode*, 32> PHIs; 4315 uint64_t Len = GetStringLengthH(V, PHIs, CharSize); 4316 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return 4317 // an empty string as a length. 4318 return Len == ~0ULL ? 1 : Len; 4319 } 4320 4321 const Value * 4322 llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call, 4323 bool MustPreserveNullness) { 4324 assert(Call && 4325 "getArgumentAliasingToReturnedPointer only works on nonnull calls"); 4326 if (const Value *RV = Call->getReturnedArgOperand()) 4327 return RV; 4328 // This can be used only as a aliasing property. 4329 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing( 4330 Call, MustPreserveNullness)) 4331 return Call->getArgOperand(0); 4332 return nullptr; 4333 } 4334 4335 bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing( 4336 const CallBase *Call, bool MustPreserveNullness) { 4337 switch (Call->getIntrinsicID()) { 4338 case Intrinsic::launder_invariant_group: 4339 case Intrinsic::strip_invariant_group: 4340 case Intrinsic::aarch64_irg: 4341 case Intrinsic::aarch64_tagp: 4342 return true; 4343 case Intrinsic::ptrmask: 4344 return !MustPreserveNullness; 4345 default: 4346 return false; 4347 } 4348 } 4349 4350 /// \p PN defines a loop-variant pointer to an object. Check if the 4351 /// previous iteration of the loop was referring to the same object as \p PN. 4352 static bool isSameUnderlyingObjectInLoop(const PHINode *PN, 4353 const LoopInfo *LI) { 4354 // Find the loop-defined value. 4355 Loop *L = LI->getLoopFor(PN->getParent()); 4356 if (PN->getNumIncomingValues() != 2) 4357 return true; 4358 4359 // Find the value from previous iteration. 4360 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0)); 4361 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L) 4362 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1)); 4363 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L) 4364 return true; 4365 4366 // If a new pointer is loaded in the loop, the pointer references a different 4367 // object in every iteration. E.g.: 4368 // for (i) 4369 // int *p = a[i]; 4370 // ... 4371 if (auto *Load = dyn_cast<LoadInst>(PrevValue)) 4372 if (!L->isLoopInvariant(Load->getPointerOperand())) 4373 return false; 4374 return true; 4375 } 4376 4377 const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) { 4378 if (!V->getType()->isPointerTy()) 4379 return V; 4380 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) { 4381 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 4382 V = GEP->getPointerOperand(); 4383 } else if (Operator::getOpcode(V) == Instruction::BitCast || 4384 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 4385 V = cast<Operator>(V)->getOperand(0); 4386 if (!V->getType()->isPointerTy()) 4387 return V; 4388 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) { 4389 if (GA->isInterposable()) 4390 return V; 4391 V = GA->getAliasee(); 4392 } else { 4393 if (auto *PHI = dyn_cast<PHINode>(V)) { 4394 // Look through single-arg phi nodes created by LCSSA. 4395 if (PHI->getNumIncomingValues() == 1) { 4396 V = PHI->getIncomingValue(0); 4397 continue; 4398 } 4399 } else if (auto *Call = dyn_cast<CallBase>(V)) { 4400 // CaptureTracking can know about special capturing properties of some 4401 // intrinsics like launder.invariant.group, that can't be expressed with 4402 // the attributes, but have properties like returning aliasing pointer. 4403 // Because some analysis may assume that nocaptured pointer is not 4404 // returned from some special intrinsic (because function would have to 4405 // be marked with returns attribute), it is crucial to use this function 4406 // because it should be in sync with CaptureTracking. Not using it may 4407 // cause weird miscompilations where 2 aliasing pointers are assumed to 4408 // noalias. 4409 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) { 4410 V = RP; 4411 continue; 4412 } 4413 } 4414 4415 return V; 4416 } 4417 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 4418 } 4419 return V; 4420 } 4421 4422 void llvm::getUnderlyingObjects(const Value *V, 4423 SmallVectorImpl<const Value *> &Objects, 4424 LoopInfo *LI, unsigned MaxLookup) { 4425 SmallPtrSet<const Value *, 4> Visited; 4426 SmallVector<const Value *, 4> Worklist; 4427 Worklist.push_back(V); 4428 do { 4429 const Value *P = Worklist.pop_back_val(); 4430 P = getUnderlyingObject(P, MaxLookup); 4431 4432 if (!Visited.insert(P).second) 4433 continue; 4434 4435 if (auto *SI = dyn_cast<SelectInst>(P)) { 4436 Worklist.push_back(SI->getTrueValue()); 4437 Worklist.push_back(SI->getFalseValue()); 4438 continue; 4439 } 4440 4441 if (auto *PN = dyn_cast<PHINode>(P)) { 4442 // If this PHI changes the underlying object in every iteration of the 4443 // loop, don't look through it. Consider: 4444 // int **A; 4445 // for (i) { 4446 // Prev = Curr; // Prev = PHI (Prev_0, Curr) 4447 // Curr = A[i]; 4448 // *Prev, *Curr; 4449 // 4450 // Prev is tracking Curr one iteration behind so they refer to different 4451 // underlying objects. 4452 if (!LI || !LI->isLoopHeader(PN->getParent()) || 4453 isSameUnderlyingObjectInLoop(PN, LI)) 4454 append_range(Worklist, PN->incoming_values()); 4455 continue; 4456 } 4457 4458 Objects.push_back(P); 4459 } while (!Worklist.empty()); 4460 } 4461 4462 /// This is the function that does the work of looking through basic 4463 /// ptrtoint+arithmetic+inttoptr sequences. 4464 static const Value *getUnderlyingObjectFromInt(const Value *V) { 4465 do { 4466 if (const Operator *U = dyn_cast<Operator>(V)) { 4467 // If we find a ptrtoint, we can transfer control back to the 4468 // regular getUnderlyingObjectFromInt. 4469 if (U->getOpcode() == Instruction::PtrToInt) 4470 return U->getOperand(0); 4471 // If we find an add of a constant, a multiplied value, or a phi, it's 4472 // likely that the other operand will lead us to the base 4473 // object. We don't have to worry about the case where the 4474 // object address is somehow being computed by the multiply, 4475 // because our callers only care when the result is an 4476 // identifiable object. 4477 if (U->getOpcode() != Instruction::Add || 4478 (!isa<ConstantInt>(U->getOperand(1)) && 4479 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul && 4480 !isa<PHINode>(U->getOperand(1)))) 4481 return V; 4482 V = U->getOperand(0); 4483 } else { 4484 return V; 4485 } 4486 assert(V->getType()->isIntegerTy() && "Unexpected operand type!"); 4487 } while (true); 4488 } 4489 4490 /// This is a wrapper around getUnderlyingObjects and adds support for basic 4491 /// ptrtoint+arithmetic+inttoptr sequences. 4492 /// It returns false if unidentified object is found in getUnderlyingObjects. 4493 bool llvm::getUnderlyingObjectsForCodeGen(const Value *V, 4494 SmallVectorImpl<Value *> &Objects) { 4495 SmallPtrSet<const Value *, 16> Visited; 4496 SmallVector<const Value *, 4> Working(1, V); 4497 do { 4498 V = Working.pop_back_val(); 4499 4500 SmallVector<const Value *, 4> Objs; 4501 getUnderlyingObjects(V, Objs); 4502 4503 for (const Value *V : Objs) { 4504 if (!Visited.insert(V).second) 4505 continue; 4506 if (Operator::getOpcode(V) == Instruction::IntToPtr) { 4507 const Value *O = 4508 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0)); 4509 if (O->getType()->isPointerTy()) { 4510 Working.push_back(O); 4511 continue; 4512 } 4513 } 4514 // If getUnderlyingObjects fails to find an identifiable object, 4515 // getUnderlyingObjectsForCodeGen also fails for safety. 4516 if (!isIdentifiedObject(V)) { 4517 Objects.clear(); 4518 return false; 4519 } 4520 Objects.push_back(const_cast<Value *>(V)); 4521 } 4522 } while (!Working.empty()); 4523 return true; 4524 } 4525 4526 AllocaInst *llvm::findAllocaForValue(Value *V, bool OffsetZero) { 4527 AllocaInst *Result = nullptr; 4528 SmallPtrSet<Value *, 4> Visited; 4529 SmallVector<Value *, 4> Worklist; 4530 4531 auto AddWork = [&](Value *V) { 4532 if (Visited.insert(V).second) 4533 Worklist.push_back(V); 4534 }; 4535 4536 AddWork(V); 4537 do { 4538 V = Worklist.pop_back_val(); 4539 assert(Visited.count(V)); 4540 4541 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 4542 if (Result && Result != AI) 4543 return nullptr; 4544 Result = AI; 4545 } else if (CastInst *CI = dyn_cast<CastInst>(V)) { 4546 AddWork(CI->getOperand(0)); 4547 } else if (PHINode *PN = dyn_cast<PHINode>(V)) { 4548 for (Value *IncValue : PN->incoming_values()) 4549 AddWork(IncValue); 4550 } else if (auto *SI = dyn_cast<SelectInst>(V)) { 4551 AddWork(SI->getTrueValue()); 4552 AddWork(SI->getFalseValue()); 4553 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) { 4554 if (OffsetZero && !GEP->hasAllZeroIndices()) 4555 return nullptr; 4556 AddWork(GEP->getPointerOperand()); 4557 } else if (CallBase *CB = dyn_cast<CallBase>(V)) { 4558 Value *Returned = CB->getReturnedArgOperand(); 4559 if (Returned) 4560 AddWork(Returned); 4561 else 4562 return nullptr; 4563 } else { 4564 return nullptr; 4565 } 4566 } while (!Worklist.empty()); 4567 4568 return Result; 4569 } 4570 4571 static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper( 4572 const Value *V, bool AllowLifetime, bool AllowDroppable) { 4573 for (const User *U : V->users()) { 4574 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 4575 if (!II) 4576 return false; 4577 4578 if (AllowLifetime && II->isLifetimeStartOrEnd()) 4579 continue; 4580 4581 if (AllowDroppable && II->isDroppable()) 4582 continue; 4583 4584 return false; 4585 } 4586 return true; 4587 } 4588 4589 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) { 4590 return onlyUsedByLifetimeMarkersOrDroppableInstsHelper( 4591 V, /* AllowLifetime */ true, /* AllowDroppable */ false); 4592 } 4593 bool llvm::onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V) { 4594 return onlyUsedByLifetimeMarkersOrDroppableInstsHelper( 4595 V, /* AllowLifetime */ true, /* AllowDroppable */ true); 4596 } 4597 4598 bool llvm::mustSuppressSpeculation(const LoadInst &LI) { 4599 if (!LI.isUnordered()) 4600 return true; 4601 const Function &F = *LI.getFunction(); 4602 // Speculative load may create a race that did not exist in the source. 4603 return F.hasFnAttribute(Attribute::SanitizeThread) || 4604 // Speculative load may load data from dirty regions. 4605 F.hasFnAttribute(Attribute::SanitizeAddress) || 4606 F.hasFnAttribute(Attribute::SanitizeHWAddress); 4607 } 4608 4609 4610 bool llvm::isSafeToSpeculativelyExecute(const Value *V, 4611 const Instruction *CtxI, 4612 const DominatorTree *DT, 4613 const TargetLibraryInfo *TLI) { 4614 const Operator *Inst = dyn_cast<Operator>(V); 4615 if (!Inst) 4616 return false; 4617 4618 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) 4619 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i))) 4620 if (C->canTrap()) 4621 return false; 4622 4623 switch (Inst->getOpcode()) { 4624 default: 4625 return true; 4626 case Instruction::UDiv: 4627 case Instruction::URem: { 4628 // x / y is undefined if y == 0. 4629 const APInt *V; 4630 if (match(Inst->getOperand(1), m_APInt(V))) 4631 return *V != 0; 4632 return false; 4633 } 4634 case Instruction::SDiv: 4635 case Instruction::SRem: { 4636 // x / y is undefined if y == 0 or x == INT_MIN and y == -1 4637 const APInt *Numerator, *Denominator; 4638 if (!match(Inst->getOperand(1), m_APInt(Denominator))) 4639 return false; 4640 // We cannot hoist this division if the denominator is 0. 4641 if (*Denominator == 0) 4642 return false; 4643 // It's safe to hoist if the denominator is not 0 or -1. 4644 if (!Denominator->isAllOnes()) 4645 return true; 4646 // At this point we know that the denominator is -1. It is safe to hoist as 4647 // long we know that the numerator is not INT_MIN. 4648 if (match(Inst->getOperand(0), m_APInt(Numerator))) 4649 return !Numerator->isMinSignedValue(); 4650 // The numerator *might* be MinSignedValue. 4651 return false; 4652 } 4653 case Instruction::Load: { 4654 const LoadInst *LI = cast<LoadInst>(Inst); 4655 if (mustSuppressSpeculation(*LI)) 4656 return false; 4657 const DataLayout &DL = LI->getModule()->getDataLayout(); 4658 return isDereferenceableAndAlignedPointer( 4659 LI->getPointerOperand(), LI->getType(), MaybeAlign(LI->getAlignment()), 4660 DL, CtxI, DT, TLI); 4661 } 4662 case Instruction::Call: { 4663 auto *CI = cast<const CallInst>(Inst); 4664 const Function *Callee = CI->getCalledFunction(); 4665 4666 // The called function could have undefined behavior or side-effects, even 4667 // if marked readnone nounwind. 4668 return Callee && Callee->isSpeculatable(); 4669 } 4670 case Instruction::VAArg: 4671 case Instruction::Alloca: 4672 case Instruction::Invoke: 4673 case Instruction::CallBr: 4674 case Instruction::PHI: 4675 case Instruction::Store: 4676 case Instruction::Ret: 4677 case Instruction::Br: 4678 case Instruction::IndirectBr: 4679 case Instruction::Switch: 4680 case Instruction::Unreachable: 4681 case Instruction::Fence: 4682 case Instruction::AtomicRMW: 4683 case Instruction::AtomicCmpXchg: 4684 case Instruction::LandingPad: 4685 case Instruction::Resume: 4686 case Instruction::CatchSwitch: 4687 case Instruction::CatchPad: 4688 case Instruction::CatchRet: 4689 case Instruction::CleanupPad: 4690 case Instruction::CleanupRet: 4691 return false; // Misc instructions which have effects 4692 } 4693 } 4694 4695 bool llvm::mayBeMemoryDependent(const Instruction &I) { 4696 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I); 4697 } 4698 4699 /// Convert ConstantRange OverflowResult into ValueTracking OverflowResult. 4700 static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) { 4701 switch (OR) { 4702 case ConstantRange::OverflowResult::MayOverflow: 4703 return OverflowResult::MayOverflow; 4704 case ConstantRange::OverflowResult::AlwaysOverflowsLow: 4705 return OverflowResult::AlwaysOverflowsLow; 4706 case ConstantRange::OverflowResult::AlwaysOverflowsHigh: 4707 return OverflowResult::AlwaysOverflowsHigh; 4708 case ConstantRange::OverflowResult::NeverOverflows: 4709 return OverflowResult::NeverOverflows; 4710 } 4711 llvm_unreachable("Unknown OverflowResult"); 4712 } 4713 4714 /// Combine constant ranges from computeConstantRange() and computeKnownBits(). 4715 static ConstantRange computeConstantRangeIncludingKnownBits( 4716 const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth, 4717 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, 4718 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) { 4719 KnownBits Known = computeKnownBits( 4720 V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo); 4721 ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned); 4722 ConstantRange CR2 = computeConstantRange(V, UseInstrInfo); 4723 ConstantRange::PreferredRangeType RangeType = 4724 ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned; 4725 return CR1.intersectWith(CR2, RangeType); 4726 } 4727 4728 OverflowResult llvm::computeOverflowForUnsignedMul( 4729 const Value *LHS, const Value *RHS, const DataLayout &DL, 4730 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, 4731 bool UseInstrInfo) { 4732 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT, 4733 nullptr, UseInstrInfo); 4734 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT, 4735 nullptr, UseInstrInfo); 4736 ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false); 4737 ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false); 4738 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange)); 4739 } 4740 4741 OverflowResult 4742 llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS, 4743 const DataLayout &DL, AssumptionCache *AC, 4744 const Instruction *CxtI, 4745 const DominatorTree *DT, bool UseInstrInfo) { 4746 // Multiplying n * m significant bits yields a result of n + m significant 4747 // bits. If the total number of significant bits does not exceed the 4748 // result bit width (minus 1), there is no overflow. 4749 // This means if we have enough leading sign bits in the operands 4750 // we can guarantee that the result does not overflow. 4751 // Ref: "Hacker's Delight" by Henry Warren 4752 unsigned BitWidth = LHS->getType()->getScalarSizeInBits(); 4753 4754 // Note that underestimating the number of sign bits gives a more 4755 // conservative answer. 4756 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) + 4757 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT); 4758 4759 // First handle the easy case: if we have enough sign bits there's 4760 // definitely no overflow. 4761 if (SignBits > BitWidth + 1) 4762 return OverflowResult::NeverOverflows; 4763 4764 // There are two ambiguous cases where there can be no overflow: 4765 // SignBits == BitWidth + 1 and 4766 // SignBits == BitWidth 4767 // The second case is difficult to check, therefore we only handle the 4768 // first case. 4769 if (SignBits == BitWidth + 1) { 4770 // It overflows only when both arguments are negative and the true 4771 // product is exactly the minimum negative number. 4772 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000 4773 // For simplicity we just check if at least one side is not negative. 4774 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT, 4775 nullptr, UseInstrInfo); 4776 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT, 4777 nullptr, UseInstrInfo); 4778 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) 4779 return OverflowResult::NeverOverflows; 4780 } 4781 return OverflowResult::MayOverflow; 4782 } 4783 4784 OverflowResult llvm::computeOverflowForUnsignedAdd( 4785 const Value *LHS, const Value *RHS, const DataLayout &DL, 4786 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, 4787 bool UseInstrInfo) { 4788 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits( 4789 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT, 4790 nullptr, UseInstrInfo); 4791 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits( 4792 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT, 4793 nullptr, UseInstrInfo); 4794 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange)); 4795 } 4796 4797 static OverflowResult computeOverflowForSignedAdd(const Value *LHS, 4798 const Value *RHS, 4799 const AddOperator *Add, 4800 const DataLayout &DL, 4801 AssumptionCache *AC, 4802 const Instruction *CxtI, 4803 const DominatorTree *DT) { 4804 if (Add && Add->hasNoSignedWrap()) { 4805 return OverflowResult::NeverOverflows; 4806 } 4807 4808 // If LHS and RHS each have at least two sign bits, the addition will look 4809 // like 4810 // 4811 // XX..... + 4812 // YY..... 4813 // 4814 // If the carry into the most significant position is 0, X and Y can't both 4815 // be 1 and therefore the carry out of the addition is also 0. 4816 // 4817 // If the carry into the most significant position is 1, X and Y can't both 4818 // be 0 and therefore the carry out of the addition is also 1. 4819 // 4820 // Since the carry into the most significant position is always equal to 4821 // the carry out of the addition, there is no signed overflow. 4822 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 && 4823 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1) 4824 return OverflowResult::NeverOverflows; 4825 4826 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits( 4827 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT); 4828 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits( 4829 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT); 4830 OverflowResult OR = 4831 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange)); 4832 if (OR != OverflowResult::MayOverflow) 4833 return OR; 4834 4835 // The remaining code needs Add to be available. Early returns if not so. 4836 if (!Add) 4837 return OverflowResult::MayOverflow; 4838 4839 // If the sign of Add is the same as at least one of the operands, this add 4840 // CANNOT overflow. If this can be determined from the known bits of the 4841 // operands the above signedAddMayOverflow() check will have already done so. 4842 // The only other way to improve on the known bits is from an assumption, so 4843 // call computeKnownBitsFromAssume() directly. 4844 bool LHSOrRHSKnownNonNegative = 4845 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative()); 4846 bool LHSOrRHSKnownNegative = 4847 (LHSRange.isAllNegative() || RHSRange.isAllNegative()); 4848 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) { 4849 KnownBits AddKnown(LHSRange.getBitWidth()); 4850 computeKnownBitsFromAssume( 4851 Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true)); 4852 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) || 4853 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) 4854 return OverflowResult::NeverOverflows; 4855 } 4856 4857 return OverflowResult::MayOverflow; 4858 } 4859 4860 OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS, 4861 const Value *RHS, 4862 const DataLayout &DL, 4863 AssumptionCache *AC, 4864 const Instruction *CxtI, 4865 const DominatorTree *DT) { 4866 // Checking for conditions implied by dominating conditions may be expensive. 4867 // Limit it to usub_with_overflow calls for now. 4868 if (match(CxtI, 4869 m_Intrinsic<Intrinsic::usub_with_overflow>(m_Value(), m_Value()))) 4870 if (auto C = 4871 isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, CxtI, DL)) { 4872 if (*C) 4873 return OverflowResult::NeverOverflows; 4874 return OverflowResult::AlwaysOverflowsLow; 4875 } 4876 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits( 4877 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT); 4878 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits( 4879 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT); 4880 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange)); 4881 } 4882 4883 OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS, 4884 const Value *RHS, 4885 const DataLayout &DL, 4886 AssumptionCache *AC, 4887 const Instruction *CxtI, 4888 const DominatorTree *DT) { 4889 // If LHS and RHS each have at least two sign bits, the subtraction 4890 // cannot overflow. 4891 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 && 4892 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1) 4893 return OverflowResult::NeverOverflows; 4894 4895 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits( 4896 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT); 4897 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits( 4898 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT); 4899 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange)); 4900 } 4901 4902 bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, 4903 const DominatorTree &DT) { 4904 SmallVector<const BranchInst *, 2> GuardingBranches; 4905 SmallVector<const ExtractValueInst *, 2> Results; 4906 4907 for (const User *U : WO->users()) { 4908 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) { 4909 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type"); 4910 4911 if (EVI->getIndices()[0] == 0) 4912 Results.push_back(EVI); 4913 else { 4914 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type"); 4915 4916 for (const auto *U : EVI->users()) 4917 if (const auto *B = dyn_cast<BranchInst>(U)) { 4918 assert(B->isConditional() && "How else is it using an i1?"); 4919 GuardingBranches.push_back(B); 4920 } 4921 } 4922 } else { 4923 // We are using the aggregate directly in a way we don't want to analyze 4924 // here (storing it to a global, say). 4925 return false; 4926 } 4927 } 4928 4929 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) { 4930 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1)); 4931 if (!NoWrapEdge.isSingleEdge()) 4932 return false; 4933 4934 // Check if all users of the add are provably no-wrap. 4935 for (const auto *Result : Results) { 4936 // If the extractvalue itself is not executed on overflow, the we don't 4937 // need to check each use separately, since domination is transitive. 4938 if (DT.dominates(NoWrapEdge, Result->getParent())) 4939 continue; 4940 4941 for (auto &RU : Result->uses()) 4942 if (!DT.dominates(NoWrapEdge, RU)) 4943 return false; 4944 } 4945 4946 return true; 4947 }; 4948 4949 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch); 4950 } 4951 4952 static bool canCreateUndefOrPoison(const Operator *Op, bool PoisonOnly) { 4953 // See whether I has flags that may create poison 4954 if (const auto *OvOp = dyn_cast<OverflowingBinaryOperator>(Op)) { 4955 if (OvOp->hasNoSignedWrap() || OvOp->hasNoUnsignedWrap()) 4956 return true; 4957 } 4958 if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(Op)) 4959 if (ExactOp->isExact()) 4960 return true; 4961 if (const auto *FP = dyn_cast<FPMathOperator>(Op)) { 4962 auto FMF = FP->getFastMathFlags(); 4963 if (FMF.noNaNs() || FMF.noInfs()) 4964 return true; 4965 } 4966 4967 unsigned Opcode = Op->getOpcode(); 4968 4969 // Check whether opcode is a poison/undef-generating operation 4970 switch (Opcode) { 4971 case Instruction::Shl: 4972 case Instruction::AShr: 4973 case Instruction::LShr: { 4974 // Shifts return poison if shiftwidth is larger than the bitwidth. 4975 if (auto *C = dyn_cast<Constant>(Op->getOperand(1))) { 4976 SmallVector<Constant *, 4> ShiftAmounts; 4977 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) { 4978 unsigned NumElts = FVTy->getNumElements(); 4979 for (unsigned i = 0; i < NumElts; ++i) 4980 ShiftAmounts.push_back(C->getAggregateElement(i)); 4981 } else if (isa<ScalableVectorType>(C->getType())) 4982 return true; // Can't tell, just return true to be safe 4983 else 4984 ShiftAmounts.push_back(C); 4985 4986 bool Safe = llvm::all_of(ShiftAmounts, [](Constant *C) { 4987 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4988 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth()); 4989 }); 4990 return !Safe; 4991 } 4992 return true; 4993 } 4994 case Instruction::FPToSI: 4995 case Instruction::FPToUI: 4996 // fptosi/ui yields poison if the resulting value does not fit in the 4997 // destination type. 4998 return true; 4999 case Instruction::Call: 5000 if (auto *II = dyn_cast<IntrinsicInst>(Op)) { 5001 switch (II->getIntrinsicID()) { 5002 // TODO: Add more intrinsics. 5003 case Intrinsic::ctpop: 5004 case Intrinsic::sadd_with_overflow: 5005 case Intrinsic::ssub_with_overflow: 5006 case Intrinsic::smul_with_overflow: 5007 case Intrinsic::uadd_with_overflow: 5008 case Intrinsic::usub_with_overflow: 5009 case Intrinsic::umul_with_overflow: 5010 return false; 5011 } 5012 } 5013 LLVM_FALLTHROUGH; 5014 case Instruction::CallBr: 5015 case Instruction::Invoke: { 5016 const auto *CB = cast<CallBase>(Op); 5017 return !CB->hasRetAttr(Attribute::NoUndef); 5018 } 5019 case Instruction::InsertElement: 5020 case Instruction::ExtractElement: { 5021 // If index exceeds the length of the vector, it returns poison 5022 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType()); 5023 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1; 5024 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp)); 5025 if (!Idx || Idx->getValue().uge(VTy->getElementCount().getKnownMinValue())) 5026 return true; 5027 return false; 5028 } 5029 case Instruction::ShuffleVector: { 5030 // shufflevector may return undef. 5031 if (PoisonOnly) 5032 return false; 5033 ArrayRef<int> Mask = isa<ConstantExpr>(Op) 5034 ? cast<ConstantExpr>(Op)->getShuffleMask() 5035 : cast<ShuffleVectorInst>(Op)->getShuffleMask(); 5036 return is_contained(Mask, UndefMaskElem); 5037 } 5038 case Instruction::FNeg: 5039 case Instruction::PHI: 5040 case Instruction::Select: 5041 case Instruction::URem: 5042 case Instruction::SRem: 5043 case Instruction::ExtractValue: 5044 case Instruction::InsertValue: 5045 case Instruction::Freeze: 5046 case Instruction::ICmp: 5047 case Instruction::FCmp: 5048 return false; 5049 case Instruction::GetElementPtr: { 5050 const auto *GEP = cast<GEPOperator>(Op); 5051 return GEP->isInBounds(); 5052 } 5053 default: { 5054 const auto *CE = dyn_cast<ConstantExpr>(Op); 5055 if (isa<CastInst>(Op) || (CE && CE->isCast())) 5056 return false; 5057 else if (Instruction::isBinaryOp(Opcode)) 5058 return false; 5059 // Be conservative and return true. 5060 return true; 5061 } 5062 } 5063 } 5064 5065 bool llvm::canCreateUndefOrPoison(const Operator *Op) { 5066 return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/false); 5067 } 5068 5069 bool llvm::canCreatePoison(const Operator *Op) { 5070 return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/true); 5071 } 5072 5073 static bool directlyImpliesPoison(const Value *ValAssumedPoison, 5074 const Value *V, unsigned Depth) { 5075 if (ValAssumedPoison == V) 5076 return true; 5077 5078 const unsigned MaxDepth = 2; 5079 if (Depth >= MaxDepth) 5080 return false; 5081 5082 if (const auto *I = dyn_cast<Instruction>(V)) { 5083 if (propagatesPoison(cast<Operator>(I))) 5084 return any_of(I->operands(), [=](const Value *Op) { 5085 return directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1); 5086 }); 5087 5088 // 'select ValAssumedPoison, _, _' is poison. 5089 if (const auto *SI = dyn_cast<SelectInst>(I)) 5090 return directlyImpliesPoison(ValAssumedPoison, SI->getCondition(), 5091 Depth + 1); 5092 // V = extractvalue V0, idx 5093 // V2 = extractvalue V0, idx2 5094 // V0's elements are all poison or not. (e.g., add_with_overflow) 5095 const WithOverflowInst *II; 5096 if (match(I, m_ExtractValue(m_WithOverflowInst(II))) && 5097 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) || 5098 llvm::is_contained(II->args(), ValAssumedPoison))) 5099 return true; 5100 } 5101 return false; 5102 } 5103 5104 static bool impliesPoison(const Value *ValAssumedPoison, const Value *V, 5105 unsigned Depth) { 5106 if (isGuaranteedNotToBeUndefOrPoison(ValAssumedPoison)) 5107 return true; 5108 5109 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0)) 5110 return true; 5111 5112 const unsigned MaxDepth = 2; 5113 if (Depth >= MaxDepth) 5114 return false; 5115 5116 const auto *I = dyn_cast<Instruction>(ValAssumedPoison); 5117 if (I && !canCreatePoison(cast<Operator>(I))) { 5118 return all_of(I->operands(), [=](const Value *Op) { 5119 return impliesPoison(Op, V, Depth + 1); 5120 }); 5121 } 5122 return false; 5123 } 5124 5125 bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) { 5126 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0); 5127 } 5128 5129 static bool programUndefinedIfUndefOrPoison(const Value *V, 5130 bool PoisonOnly); 5131 5132 static bool isGuaranteedNotToBeUndefOrPoison(const Value *V, 5133 AssumptionCache *AC, 5134 const Instruction *CtxI, 5135 const DominatorTree *DT, 5136 unsigned Depth, bool PoisonOnly) { 5137 if (Depth >= MaxAnalysisRecursionDepth) 5138 return false; 5139 5140 if (isa<MetadataAsValue>(V)) 5141 return false; 5142 5143 if (const auto *A = dyn_cast<Argument>(V)) { 5144 if (A->hasAttribute(Attribute::NoUndef)) 5145 return true; 5146 } 5147 5148 if (auto *C = dyn_cast<Constant>(V)) { 5149 if (isa<UndefValue>(C)) 5150 return PoisonOnly && !isa<PoisonValue>(C); 5151 5152 if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(V) || 5153 isa<ConstantPointerNull>(C) || isa<Function>(C)) 5154 return true; 5155 5156 if (C->getType()->isVectorTy() && !isa<ConstantExpr>(C)) 5157 return (PoisonOnly ? !C->containsPoisonElement() 5158 : !C->containsUndefOrPoisonElement()) && 5159 !C->containsConstantExpression(); 5160 } 5161 5162 // Strip cast operations from a pointer value. 5163 // Note that stripPointerCastsSameRepresentation can strip off getelementptr 5164 // inbounds with zero offset. To guarantee that the result isn't poison, the 5165 // stripped pointer is checked as it has to be pointing into an allocated 5166 // object or be null `null` to ensure `inbounds` getelement pointers with a 5167 // zero offset could not produce poison. 5168 // It can strip off addrspacecast that do not change bit representation as 5169 // well. We believe that such addrspacecast is equivalent to no-op. 5170 auto *StrippedV = V->stripPointerCastsSameRepresentation(); 5171 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) || 5172 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV)) 5173 return true; 5174 5175 auto OpCheck = [&](const Value *V) { 5176 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, 5177 PoisonOnly); 5178 }; 5179 5180 if (auto *Opr = dyn_cast<Operator>(V)) { 5181 // If the value is a freeze instruction, then it can never 5182 // be undef or poison. 5183 if (isa<FreezeInst>(V)) 5184 return true; 5185 5186 if (const auto *CB = dyn_cast<CallBase>(V)) { 5187 if (CB->hasRetAttr(Attribute::NoUndef)) 5188 return true; 5189 } 5190 5191 if (const auto *PN = dyn_cast<PHINode>(V)) { 5192 unsigned Num = PN->getNumIncomingValues(); 5193 bool IsWellDefined = true; 5194 for (unsigned i = 0; i < Num; ++i) { 5195 auto *TI = PN->getIncomingBlock(i)->getTerminator(); 5196 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI, 5197 DT, Depth + 1, PoisonOnly)) { 5198 IsWellDefined = false; 5199 break; 5200 } 5201 } 5202 if (IsWellDefined) 5203 return true; 5204 } else if (!canCreateUndefOrPoison(Opr) && all_of(Opr->operands(), OpCheck)) 5205 return true; 5206 } 5207 5208 if (auto *I = dyn_cast<LoadInst>(V)) 5209 if (I->getMetadata(LLVMContext::MD_noundef)) 5210 return true; 5211 5212 if (programUndefinedIfUndefOrPoison(V, PoisonOnly)) 5213 return true; 5214 5215 // CxtI may be null or a cloned instruction. 5216 if (!CtxI || !CtxI->getParent() || !DT) 5217 return false; 5218 5219 auto *DNode = DT->getNode(CtxI->getParent()); 5220 if (!DNode) 5221 // Unreachable block 5222 return false; 5223 5224 // If V is used as a branch condition before reaching CtxI, V cannot be 5225 // undef or poison. 5226 // br V, BB1, BB2 5227 // BB1: 5228 // CtxI ; V cannot be undef or poison here 5229 auto *Dominator = DNode->getIDom(); 5230 while (Dominator) { 5231 auto *TI = Dominator->getBlock()->getTerminator(); 5232 5233 Value *Cond = nullptr; 5234 if (auto BI = dyn_cast<BranchInst>(TI)) { 5235 if (BI->isConditional()) 5236 Cond = BI->getCondition(); 5237 } else if (auto SI = dyn_cast<SwitchInst>(TI)) { 5238 Cond = SI->getCondition(); 5239 } 5240 5241 if (Cond) { 5242 if (Cond == V) 5243 return true; 5244 else if (PoisonOnly && isa<Operator>(Cond)) { 5245 // For poison, we can analyze further 5246 auto *Opr = cast<Operator>(Cond); 5247 if (propagatesPoison(Opr) && is_contained(Opr->operand_values(), V)) 5248 return true; 5249 } 5250 } 5251 5252 Dominator = Dominator->getIDom(); 5253 } 5254 5255 SmallVector<Attribute::AttrKind, 2> AttrKinds{Attribute::NoUndef}; 5256 if (getKnowledgeValidInContext(V, AttrKinds, CtxI, DT, AC)) 5257 return true; 5258 5259 return false; 5260 } 5261 5262 bool llvm::isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC, 5263 const Instruction *CtxI, 5264 const DominatorTree *DT, 5265 unsigned Depth) { 5266 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, false); 5267 } 5268 5269 bool llvm::isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC, 5270 const Instruction *CtxI, 5271 const DominatorTree *DT, unsigned Depth) { 5272 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, true); 5273 } 5274 5275 OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add, 5276 const DataLayout &DL, 5277 AssumptionCache *AC, 5278 const Instruction *CxtI, 5279 const DominatorTree *DT) { 5280 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1), 5281 Add, DL, AC, CxtI, DT); 5282 } 5283 5284 OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS, 5285 const Value *RHS, 5286 const DataLayout &DL, 5287 AssumptionCache *AC, 5288 const Instruction *CxtI, 5289 const DominatorTree *DT) { 5290 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT); 5291 } 5292 5293 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) { 5294 // Note: An atomic operation isn't guaranteed to return in a reasonable amount 5295 // of time because it's possible for another thread to interfere with it for an 5296 // arbitrary length of time, but programs aren't allowed to rely on that. 5297 5298 // If there is no successor, then execution can't transfer to it. 5299 if (isa<ReturnInst>(I)) 5300 return false; 5301 if (isa<UnreachableInst>(I)) 5302 return false; 5303 5304 // Note: Do not add new checks here; instead, change Instruction::mayThrow or 5305 // Instruction::willReturn. 5306 // 5307 // FIXME: Move this check into Instruction::willReturn. 5308 if (isa<CatchPadInst>(I)) { 5309 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) { 5310 default: 5311 // A catchpad may invoke exception object constructors and such, which 5312 // in some languages can be arbitrary code, so be conservative by default. 5313 return false; 5314 case EHPersonality::CoreCLR: 5315 // For CoreCLR, it just involves a type test. 5316 return true; 5317 } 5318 } 5319 5320 // An instruction that returns without throwing must transfer control flow 5321 // to a successor. 5322 return !I->mayThrow() && I->willReturn(); 5323 } 5324 5325 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) { 5326 // TODO: This is slightly conservative for invoke instruction since exiting 5327 // via an exception *is* normal control for them. 5328 for (const Instruction &I : *BB) 5329 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5330 return false; 5331 return true; 5332 } 5333 5334 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I, 5335 const Loop *L) { 5336 // The loop header is guaranteed to be executed for every iteration. 5337 // 5338 // FIXME: Relax this constraint to cover all basic blocks that are 5339 // guaranteed to be executed at every iteration. 5340 if (I->getParent() != L->getHeader()) return false; 5341 5342 for (const Instruction &LI : *L->getHeader()) { 5343 if (&LI == I) return true; 5344 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false; 5345 } 5346 llvm_unreachable("Instruction not contained in its own parent basic block."); 5347 } 5348 5349 bool llvm::propagatesPoison(const Operator *I) { 5350 switch (I->getOpcode()) { 5351 case Instruction::Freeze: 5352 case Instruction::Select: 5353 case Instruction::PHI: 5354 case Instruction::Invoke: 5355 return false; 5356 case Instruction::Call: 5357 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 5358 switch (II->getIntrinsicID()) { 5359 // TODO: Add more intrinsics. 5360 case Intrinsic::sadd_with_overflow: 5361 case Intrinsic::ssub_with_overflow: 5362 case Intrinsic::smul_with_overflow: 5363 case Intrinsic::uadd_with_overflow: 5364 case Intrinsic::usub_with_overflow: 5365 case Intrinsic::umul_with_overflow: 5366 // If an input is a vector containing a poison element, the 5367 // two output vectors (calculated results, overflow bits)' 5368 // corresponding lanes are poison. 5369 return true; 5370 case Intrinsic::ctpop: 5371 return true; 5372 } 5373 } 5374 return false; 5375 case Instruction::ICmp: 5376 case Instruction::FCmp: 5377 case Instruction::GetElementPtr: 5378 return true; 5379 default: 5380 if (isa<BinaryOperator>(I) || isa<UnaryOperator>(I) || isa<CastInst>(I)) 5381 return true; 5382 5383 // Be conservative and return false. 5384 return false; 5385 } 5386 } 5387 5388 void llvm::getGuaranteedWellDefinedOps( 5389 const Instruction *I, SmallPtrSetImpl<const Value *> &Operands) { 5390 switch (I->getOpcode()) { 5391 case Instruction::Store: 5392 Operands.insert(cast<StoreInst>(I)->getPointerOperand()); 5393 break; 5394 5395 case Instruction::Load: 5396 Operands.insert(cast<LoadInst>(I)->getPointerOperand()); 5397 break; 5398 5399 // Since dereferenceable attribute imply noundef, atomic operations 5400 // also implicitly have noundef pointers too 5401 case Instruction::AtomicCmpXchg: 5402 Operands.insert(cast<AtomicCmpXchgInst>(I)->getPointerOperand()); 5403 break; 5404 5405 case Instruction::AtomicRMW: 5406 Operands.insert(cast<AtomicRMWInst>(I)->getPointerOperand()); 5407 break; 5408 5409 case Instruction::Call: 5410 case Instruction::Invoke: { 5411 const CallBase *CB = cast<CallBase>(I); 5412 if (CB->isIndirectCall()) 5413 Operands.insert(CB->getCalledOperand()); 5414 for (unsigned i = 0; i < CB->arg_size(); ++i) { 5415 if (CB->paramHasAttr(i, Attribute::NoUndef) || 5416 CB->paramHasAttr(i, Attribute::Dereferenceable)) 5417 Operands.insert(CB->getArgOperand(i)); 5418 } 5419 break; 5420 } 5421 5422 default: 5423 break; 5424 } 5425 } 5426 5427 void llvm::getGuaranteedNonPoisonOps(const Instruction *I, 5428 SmallPtrSetImpl<const Value *> &Operands) { 5429 getGuaranteedWellDefinedOps(I, Operands); 5430 switch (I->getOpcode()) { 5431 // Divisors of these operations are allowed to be partially undef. 5432 case Instruction::UDiv: 5433 case Instruction::SDiv: 5434 case Instruction::URem: 5435 case Instruction::SRem: 5436 Operands.insert(I->getOperand(1)); 5437 break; 5438 5439 default: 5440 break; 5441 } 5442 } 5443 5444 bool llvm::mustTriggerUB(const Instruction *I, 5445 const SmallSet<const Value *, 16>& KnownPoison) { 5446 SmallPtrSet<const Value *, 4> NonPoisonOps; 5447 getGuaranteedNonPoisonOps(I, NonPoisonOps); 5448 5449 for (const auto *V : NonPoisonOps) 5450 if (KnownPoison.count(V)) 5451 return true; 5452 5453 return false; 5454 } 5455 5456 static bool programUndefinedIfUndefOrPoison(const Value *V, 5457 bool PoisonOnly) { 5458 // We currently only look for uses of values within the same basic 5459 // block, as that makes it easier to guarantee that the uses will be 5460 // executed given that Inst is executed. 5461 // 5462 // FIXME: Expand this to consider uses beyond the same basic block. To do 5463 // this, look out for the distinction between post-dominance and strong 5464 // post-dominance. 5465 const BasicBlock *BB = nullptr; 5466 BasicBlock::const_iterator Begin; 5467 if (const auto *Inst = dyn_cast<Instruction>(V)) { 5468 BB = Inst->getParent(); 5469 Begin = Inst->getIterator(); 5470 Begin++; 5471 } else if (const auto *Arg = dyn_cast<Argument>(V)) { 5472 BB = &Arg->getParent()->getEntryBlock(); 5473 Begin = BB->begin(); 5474 } else { 5475 return false; 5476 } 5477 5478 // Limit number of instructions we look at, to avoid scanning through large 5479 // blocks. The current limit is chosen arbitrarily. 5480 unsigned ScanLimit = 32; 5481 BasicBlock::const_iterator End = BB->end(); 5482 5483 if (!PoisonOnly) { 5484 // Since undef does not propagate eagerly, be conservative & just check 5485 // whether a value is directly passed to an instruction that must take 5486 // well-defined operands. 5487 5488 for (auto &I : make_range(Begin, End)) { 5489 if (isa<DbgInfoIntrinsic>(I)) 5490 continue; 5491 if (--ScanLimit == 0) 5492 break; 5493 5494 SmallPtrSet<const Value *, 4> WellDefinedOps; 5495 getGuaranteedWellDefinedOps(&I, WellDefinedOps); 5496 if (WellDefinedOps.contains(V)) 5497 return true; 5498 5499 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5500 break; 5501 } 5502 return false; 5503 } 5504 5505 // Set of instructions that we have proved will yield poison if Inst 5506 // does. 5507 SmallSet<const Value *, 16> YieldsPoison; 5508 SmallSet<const BasicBlock *, 4> Visited; 5509 5510 YieldsPoison.insert(V); 5511 auto Propagate = [&](const User *User) { 5512 if (propagatesPoison(cast<Operator>(User))) 5513 YieldsPoison.insert(User); 5514 }; 5515 for_each(V->users(), Propagate); 5516 Visited.insert(BB); 5517 5518 while (true) { 5519 for (auto &I : make_range(Begin, End)) { 5520 if (isa<DbgInfoIntrinsic>(I)) 5521 continue; 5522 if (--ScanLimit == 0) 5523 return false; 5524 if (mustTriggerUB(&I, YieldsPoison)) 5525 return true; 5526 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5527 return false; 5528 5529 // Mark poison that propagates from I through uses of I. 5530 if (YieldsPoison.count(&I)) 5531 for_each(I.users(), Propagate); 5532 } 5533 5534 BB = BB->getSingleSuccessor(); 5535 if (!BB || !Visited.insert(BB).second) 5536 break; 5537 5538 Begin = BB->getFirstNonPHI()->getIterator(); 5539 End = BB->end(); 5540 } 5541 return false; 5542 } 5543 5544 bool llvm::programUndefinedIfUndefOrPoison(const Instruction *Inst) { 5545 return ::programUndefinedIfUndefOrPoison(Inst, false); 5546 } 5547 5548 bool llvm::programUndefinedIfPoison(const Instruction *Inst) { 5549 return ::programUndefinedIfUndefOrPoison(Inst, true); 5550 } 5551 5552 static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) { 5553 if (FMF.noNaNs()) 5554 return true; 5555 5556 if (auto *C = dyn_cast<ConstantFP>(V)) 5557 return !C->isNaN(); 5558 5559 if (auto *C = dyn_cast<ConstantDataVector>(V)) { 5560 if (!C->getElementType()->isFloatingPointTy()) 5561 return false; 5562 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) { 5563 if (C->getElementAsAPFloat(I).isNaN()) 5564 return false; 5565 } 5566 return true; 5567 } 5568 5569 if (isa<ConstantAggregateZero>(V)) 5570 return true; 5571 5572 return false; 5573 } 5574 5575 static bool isKnownNonZero(const Value *V) { 5576 if (auto *C = dyn_cast<ConstantFP>(V)) 5577 return !C->isZero(); 5578 5579 if (auto *C = dyn_cast<ConstantDataVector>(V)) { 5580 if (!C->getElementType()->isFloatingPointTy()) 5581 return false; 5582 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) { 5583 if (C->getElementAsAPFloat(I).isZero()) 5584 return false; 5585 } 5586 return true; 5587 } 5588 5589 return false; 5590 } 5591 5592 /// Match clamp pattern for float types without care about NaNs or signed zeros. 5593 /// Given non-min/max outer cmp/select from the clamp pattern this 5594 /// function recognizes if it can be substitued by a "canonical" min/max 5595 /// pattern. 5596 static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, 5597 Value *CmpLHS, Value *CmpRHS, 5598 Value *TrueVal, Value *FalseVal, 5599 Value *&LHS, Value *&RHS) { 5600 // Try to match 5601 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2)) 5602 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2)) 5603 // and return description of the outer Max/Min. 5604 5605 // First, check if select has inverse order: 5606 if (CmpRHS == FalseVal) { 5607 std::swap(TrueVal, FalseVal); 5608 Pred = CmpInst::getInversePredicate(Pred); 5609 } 5610 5611 // Assume success now. If there's no match, callers should not use these anyway. 5612 LHS = TrueVal; 5613 RHS = FalseVal; 5614 5615 const APFloat *FC1; 5616 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite()) 5617 return {SPF_UNKNOWN, SPNB_NA, false}; 5618 5619 const APFloat *FC2; 5620 switch (Pred) { 5621 case CmpInst::FCMP_OLT: 5622 case CmpInst::FCMP_OLE: 5623 case CmpInst::FCMP_ULT: 5624 case CmpInst::FCMP_ULE: 5625 if (match(FalseVal, 5626 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)), 5627 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) && 5628 *FC1 < *FC2) 5629 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false}; 5630 break; 5631 case CmpInst::FCMP_OGT: 5632 case CmpInst::FCMP_OGE: 5633 case CmpInst::FCMP_UGT: 5634 case CmpInst::FCMP_UGE: 5635 if (match(FalseVal, 5636 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)), 5637 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) && 5638 *FC1 > *FC2) 5639 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false}; 5640 break; 5641 default: 5642 break; 5643 } 5644 5645 return {SPF_UNKNOWN, SPNB_NA, false}; 5646 } 5647 5648 /// Recognize variations of: 5649 /// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v))) 5650 static SelectPatternResult matchClamp(CmpInst::Predicate Pred, 5651 Value *CmpLHS, Value *CmpRHS, 5652 Value *TrueVal, Value *FalseVal) { 5653 // Swap the select operands and predicate to match the patterns below. 5654 if (CmpRHS != TrueVal) { 5655 Pred = ICmpInst::getSwappedPredicate(Pred); 5656 std::swap(TrueVal, FalseVal); 5657 } 5658 const APInt *C1; 5659 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) { 5660 const APInt *C2; 5661 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1) 5662 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) && 5663 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT) 5664 return {SPF_SMAX, SPNB_NA, false}; 5665 5666 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1) 5667 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) && 5668 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT) 5669 return {SPF_SMIN, SPNB_NA, false}; 5670 5671 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1) 5672 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) && 5673 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT) 5674 return {SPF_UMAX, SPNB_NA, false}; 5675 5676 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1) 5677 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) && 5678 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT) 5679 return {SPF_UMIN, SPNB_NA, false}; 5680 } 5681 return {SPF_UNKNOWN, SPNB_NA, false}; 5682 } 5683 5684 /// Recognize variations of: 5685 /// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c)) 5686 static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, 5687 Value *CmpLHS, Value *CmpRHS, 5688 Value *TVal, Value *FVal, 5689 unsigned Depth) { 5690 // TODO: Allow FP min/max with nnan/nsz. 5691 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison"); 5692 5693 Value *A = nullptr, *B = nullptr; 5694 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1); 5695 if (!SelectPatternResult::isMinOrMax(L.Flavor)) 5696 return {SPF_UNKNOWN, SPNB_NA, false}; 5697 5698 Value *C = nullptr, *D = nullptr; 5699 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1); 5700 if (L.Flavor != R.Flavor) 5701 return {SPF_UNKNOWN, SPNB_NA, false}; 5702 5703 // We have something like: x Pred y ? min(a, b) : min(c, d). 5704 // Try to match the compare to the min/max operations of the select operands. 5705 // First, make sure we have the right compare predicate. 5706 switch (L.Flavor) { 5707 case SPF_SMIN: 5708 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) { 5709 Pred = ICmpInst::getSwappedPredicate(Pred); 5710 std::swap(CmpLHS, CmpRHS); 5711 } 5712 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 5713 break; 5714 return {SPF_UNKNOWN, SPNB_NA, false}; 5715 case SPF_SMAX: 5716 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) { 5717 Pred = ICmpInst::getSwappedPredicate(Pred); 5718 std::swap(CmpLHS, CmpRHS); 5719 } 5720 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) 5721 break; 5722 return {SPF_UNKNOWN, SPNB_NA, false}; 5723 case SPF_UMIN: 5724 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) { 5725 Pred = ICmpInst::getSwappedPredicate(Pred); 5726 std::swap(CmpLHS, CmpRHS); 5727 } 5728 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) 5729 break; 5730 return {SPF_UNKNOWN, SPNB_NA, false}; 5731 case SPF_UMAX: 5732 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 5733 Pred = ICmpInst::getSwappedPredicate(Pred); 5734 std::swap(CmpLHS, CmpRHS); 5735 } 5736 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) 5737 break; 5738 return {SPF_UNKNOWN, SPNB_NA, false}; 5739 default: 5740 return {SPF_UNKNOWN, SPNB_NA, false}; 5741 } 5742 5743 // If there is a common operand in the already matched min/max and the other 5744 // min/max operands match the compare operands (either directly or inverted), 5745 // then this is min/max of the same flavor. 5746 5747 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b)) 5748 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b)) 5749 if (D == B) { 5750 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) && 5751 match(A, m_Not(m_Specific(CmpRHS))))) 5752 return {L.Flavor, SPNB_NA, false}; 5753 } 5754 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d)) 5755 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d)) 5756 if (C == B) { 5757 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) && 5758 match(A, m_Not(m_Specific(CmpRHS))))) 5759 return {L.Flavor, SPNB_NA, false}; 5760 } 5761 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a)) 5762 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a)) 5763 if (D == A) { 5764 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) && 5765 match(B, m_Not(m_Specific(CmpRHS))))) 5766 return {L.Flavor, SPNB_NA, false}; 5767 } 5768 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d)) 5769 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d)) 5770 if (C == A) { 5771 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) && 5772 match(B, m_Not(m_Specific(CmpRHS))))) 5773 return {L.Flavor, SPNB_NA, false}; 5774 } 5775 5776 return {SPF_UNKNOWN, SPNB_NA, false}; 5777 } 5778 5779 /// If the input value is the result of a 'not' op, constant integer, or vector 5780 /// splat of a constant integer, return the bitwise-not source value. 5781 /// TODO: This could be extended to handle non-splat vector integer constants. 5782 static Value *getNotValue(Value *V) { 5783 Value *NotV; 5784 if (match(V, m_Not(m_Value(NotV)))) 5785 return NotV; 5786 5787 const APInt *C; 5788 if (match(V, m_APInt(C))) 5789 return ConstantInt::get(V->getType(), ~(*C)); 5790 5791 return nullptr; 5792 } 5793 5794 /// Match non-obvious integer minimum and maximum sequences. 5795 static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, 5796 Value *CmpLHS, Value *CmpRHS, 5797 Value *TrueVal, Value *FalseVal, 5798 Value *&LHS, Value *&RHS, 5799 unsigned Depth) { 5800 // Assume success. If there's no match, callers should not use these anyway. 5801 LHS = TrueVal; 5802 RHS = FalseVal; 5803 5804 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal); 5805 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN) 5806 return SPR; 5807 5808 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth); 5809 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN) 5810 return SPR; 5811 5812 // Look through 'not' ops to find disguised min/max. 5813 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y) 5814 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y) 5815 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) { 5816 switch (Pred) { 5817 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false}; 5818 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false}; 5819 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false}; 5820 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false}; 5821 default: break; 5822 } 5823 } 5824 5825 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X) 5826 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X) 5827 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) { 5828 switch (Pred) { 5829 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false}; 5830 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false}; 5831 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false}; 5832 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false}; 5833 default: break; 5834 } 5835 } 5836 5837 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT) 5838 return {SPF_UNKNOWN, SPNB_NA, false}; 5839 5840 // Z = X -nsw Y 5841 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0) 5842 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0) 5843 if (match(TrueVal, m_Zero()) && 5844 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS)))) 5845 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false}; 5846 5847 // Z = X -nsw Y 5848 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0) 5849 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0) 5850 if (match(FalseVal, m_Zero()) && 5851 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS)))) 5852 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false}; 5853 5854 const APInt *C1; 5855 if (!match(CmpRHS, m_APInt(C1))) 5856 return {SPF_UNKNOWN, SPNB_NA, false}; 5857 5858 // An unsigned min/max can be written with a signed compare. 5859 const APInt *C2; 5860 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) || 5861 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) { 5862 // Is the sign bit set? 5863 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX 5864 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN 5865 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue()) 5866 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false}; 5867 5868 // Is the sign bit clear? 5869 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX 5870 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN 5871 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue()) 5872 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false}; 5873 } 5874 5875 return {SPF_UNKNOWN, SPNB_NA, false}; 5876 } 5877 5878 bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW) { 5879 assert(X && Y && "Invalid operand"); 5880 5881 // X = sub (0, Y) || X = sub nsw (0, Y) 5882 if ((!NeedNSW && match(X, m_Sub(m_ZeroInt(), m_Specific(Y)))) || 5883 (NeedNSW && match(X, m_NSWSub(m_ZeroInt(), m_Specific(Y))))) 5884 return true; 5885 5886 // Y = sub (0, X) || Y = sub nsw (0, X) 5887 if ((!NeedNSW && match(Y, m_Sub(m_ZeroInt(), m_Specific(X)))) || 5888 (NeedNSW && match(Y, m_NSWSub(m_ZeroInt(), m_Specific(X))))) 5889 return true; 5890 5891 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A) 5892 Value *A, *B; 5893 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) && 5894 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) || 5895 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) && 5896 match(Y, m_NSWSub(m_Specific(B), m_Specific(A))))); 5897 } 5898 5899 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred, 5900 FastMathFlags FMF, 5901 Value *CmpLHS, Value *CmpRHS, 5902 Value *TrueVal, Value *FalseVal, 5903 Value *&LHS, Value *&RHS, 5904 unsigned Depth) { 5905 if (CmpInst::isFPPredicate(Pred)) { 5906 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one 5907 // 0.0 operand, set the compare's 0.0 operands to that same value for the 5908 // purpose of identifying min/max. Disregard vector constants with undefined 5909 // elements because those can not be back-propagated for analysis. 5910 Value *OutputZeroVal = nullptr; 5911 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) && 5912 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement()) 5913 OutputZeroVal = TrueVal; 5914 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) && 5915 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement()) 5916 OutputZeroVal = FalseVal; 5917 5918 if (OutputZeroVal) { 5919 if (match(CmpLHS, m_AnyZeroFP())) 5920 CmpLHS = OutputZeroVal; 5921 if (match(CmpRHS, m_AnyZeroFP())) 5922 CmpRHS = OutputZeroVal; 5923 } 5924 } 5925 5926 LHS = CmpLHS; 5927 RHS = CmpRHS; 5928 5929 // Signed zero may return inconsistent results between implementations. 5930 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0 5931 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1) 5932 // Therefore, we behave conservatively and only proceed if at least one of the 5933 // operands is known to not be zero or if we don't care about signed zero. 5934 switch (Pred) { 5935 default: break; 5936 // FIXME: Include OGT/OLT/UGT/ULT. 5937 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE: 5938 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE: 5939 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) && 5940 !isKnownNonZero(CmpRHS)) 5941 return {SPF_UNKNOWN, SPNB_NA, false}; 5942 } 5943 5944 SelectPatternNaNBehavior NaNBehavior = SPNB_NA; 5945 bool Ordered = false; 5946 5947 // When given one NaN and one non-NaN input: 5948 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input. 5949 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the 5950 // ordered comparison fails), which could be NaN or non-NaN. 5951 // so here we discover exactly what NaN behavior is required/accepted. 5952 if (CmpInst::isFPPredicate(Pred)) { 5953 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF); 5954 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF); 5955 5956 if (LHSSafe && RHSSafe) { 5957 // Both operands are known non-NaN. 5958 NaNBehavior = SPNB_RETURNS_ANY; 5959 } else if (CmpInst::isOrdered(Pred)) { 5960 // An ordered comparison will return false when given a NaN, so it 5961 // returns the RHS. 5962 Ordered = true; 5963 if (LHSSafe) 5964 // LHS is non-NaN, so if RHS is NaN then NaN will be returned. 5965 NaNBehavior = SPNB_RETURNS_NAN; 5966 else if (RHSSafe) 5967 NaNBehavior = SPNB_RETURNS_OTHER; 5968 else 5969 // Completely unsafe. 5970 return {SPF_UNKNOWN, SPNB_NA, false}; 5971 } else { 5972 Ordered = false; 5973 // An unordered comparison will return true when given a NaN, so it 5974 // returns the LHS. 5975 if (LHSSafe) 5976 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned. 5977 NaNBehavior = SPNB_RETURNS_OTHER; 5978 else if (RHSSafe) 5979 NaNBehavior = SPNB_RETURNS_NAN; 5980 else 5981 // Completely unsafe. 5982 return {SPF_UNKNOWN, SPNB_NA, false}; 5983 } 5984 } 5985 5986 if (TrueVal == CmpRHS && FalseVal == CmpLHS) { 5987 std::swap(CmpLHS, CmpRHS); 5988 Pred = CmpInst::getSwappedPredicate(Pred); 5989 if (NaNBehavior == SPNB_RETURNS_NAN) 5990 NaNBehavior = SPNB_RETURNS_OTHER; 5991 else if (NaNBehavior == SPNB_RETURNS_OTHER) 5992 NaNBehavior = SPNB_RETURNS_NAN; 5993 Ordered = !Ordered; 5994 } 5995 5996 // ([if]cmp X, Y) ? X : Y 5997 if (TrueVal == CmpLHS && FalseVal == CmpRHS) { 5998 switch (Pred) { 5999 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality. 6000 case ICmpInst::ICMP_UGT: 6001 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false}; 6002 case ICmpInst::ICMP_SGT: 6003 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false}; 6004 case ICmpInst::ICMP_ULT: 6005 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false}; 6006 case ICmpInst::ICMP_SLT: 6007 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false}; 6008 case FCmpInst::FCMP_UGT: 6009 case FCmpInst::FCMP_UGE: 6010 case FCmpInst::FCMP_OGT: 6011 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered}; 6012 case FCmpInst::FCMP_ULT: 6013 case FCmpInst::FCMP_ULE: 6014 case FCmpInst::FCMP_OLT: 6015 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered}; 6016 } 6017 } 6018 6019 if (isKnownNegation(TrueVal, FalseVal)) { 6020 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can 6021 // match against either LHS or sext(LHS). 6022 auto MaybeSExtCmpLHS = 6023 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS))); 6024 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes()); 6025 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One()); 6026 if (match(TrueVal, MaybeSExtCmpLHS)) { 6027 // Set the return values. If the compare uses the negated value (-X >s 0), 6028 // swap the return values because the negated value is always 'RHS'. 6029 LHS = TrueVal; 6030 RHS = FalseVal; 6031 if (match(CmpLHS, m_Neg(m_Specific(FalseVal)))) 6032 std::swap(LHS, RHS); 6033 6034 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X) 6035 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X) 6036 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes)) 6037 return {SPF_ABS, SPNB_NA, false}; 6038 6039 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X) 6040 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne)) 6041 return {SPF_ABS, SPNB_NA, false}; 6042 6043 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X) 6044 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X) 6045 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne)) 6046 return {SPF_NABS, SPNB_NA, false}; 6047 } 6048 else if (match(FalseVal, MaybeSExtCmpLHS)) { 6049 // Set the return values. If the compare uses the negated value (-X >s 0), 6050 // swap the return values because the negated value is always 'RHS'. 6051 LHS = FalseVal; 6052 RHS = TrueVal; 6053 if (match(CmpLHS, m_Neg(m_Specific(TrueVal)))) 6054 std::swap(LHS, RHS); 6055 6056 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X) 6057 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X) 6058 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes)) 6059 return {SPF_NABS, SPNB_NA, false}; 6060 6061 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X) 6062 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X) 6063 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne)) 6064 return {SPF_ABS, SPNB_NA, false}; 6065 } 6066 } 6067 6068 if (CmpInst::isIntPredicate(Pred)) 6069 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth); 6070 6071 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar 6072 // may return either -0.0 or 0.0, so fcmp/select pair has stricter 6073 // semantics than minNum. Be conservative in such case. 6074 if (NaNBehavior != SPNB_RETURNS_ANY || 6075 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) && 6076 !isKnownNonZero(CmpRHS))) 6077 return {SPF_UNKNOWN, SPNB_NA, false}; 6078 6079 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS); 6080 } 6081 6082 /// Helps to match a select pattern in case of a type mismatch. 6083 /// 6084 /// The function processes the case when type of true and false values of a 6085 /// select instruction differs from type of the cmp instruction operands because 6086 /// of a cast instruction. The function checks if it is legal to move the cast 6087 /// operation after "select". If yes, it returns the new second value of 6088 /// "select" (with the assumption that cast is moved): 6089 /// 1. As operand of cast instruction when both values of "select" are same cast 6090 /// instructions. 6091 /// 2. As restored constant (by applying reverse cast operation) when the first 6092 /// value of the "select" is a cast operation and the second value is a 6093 /// constant. 6094 /// NOTE: We return only the new second value because the first value could be 6095 /// accessed as operand of cast instruction. 6096 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, 6097 Instruction::CastOps *CastOp) { 6098 auto *Cast1 = dyn_cast<CastInst>(V1); 6099 if (!Cast1) 6100 return nullptr; 6101 6102 *CastOp = Cast1->getOpcode(); 6103 Type *SrcTy = Cast1->getSrcTy(); 6104 if (auto *Cast2 = dyn_cast<CastInst>(V2)) { 6105 // If V1 and V2 are both the same cast from the same type, look through V1. 6106 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy()) 6107 return Cast2->getOperand(0); 6108 return nullptr; 6109 } 6110 6111 auto *C = dyn_cast<Constant>(V2); 6112 if (!C) 6113 return nullptr; 6114 6115 Constant *CastedTo = nullptr; 6116 switch (*CastOp) { 6117 case Instruction::ZExt: 6118 if (CmpI->isUnsigned()) 6119 CastedTo = ConstantExpr::getTrunc(C, SrcTy); 6120 break; 6121 case Instruction::SExt: 6122 if (CmpI->isSigned()) 6123 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true); 6124 break; 6125 case Instruction::Trunc: 6126 Constant *CmpConst; 6127 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) && 6128 CmpConst->getType() == SrcTy) { 6129 // Here we have the following case: 6130 // 6131 // %cond = cmp iN %x, CmpConst 6132 // %tr = trunc iN %x to iK 6133 // %narrowsel = select i1 %cond, iK %t, iK C 6134 // 6135 // We can always move trunc after select operation: 6136 // 6137 // %cond = cmp iN %x, CmpConst 6138 // %widesel = select i1 %cond, iN %x, iN CmpConst 6139 // %tr = trunc iN %widesel to iK 6140 // 6141 // Note that C could be extended in any way because we don't care about 6142 // upper bits after truncation. It can't be abs pattern, because it would 6143 // look like: 6144 // 6145 // select i1 %cond, x, -x. 6146 // 6147 // So only min/max pattern could be matched. Such match requires widened C 6148 // == CmpConst. That is why set widened C = CmpConst, condition trunc 6149 // CmpConst == C is checked below. 6150 CastedTo = CmpConst; 6151 } else { 6152 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned()); 6153 } 6154 break; 6155 case Instruction::FPTrunc: 6156 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true); 6157 break; 6158 case Instruction::FPExt: 6159 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true); 6160 break; 6161 case Instruction::FPToUI: 6162 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true); 6163 break; 6164 case Instruction::FPToSI: 6165 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true); 6166 break; 6167 case Instruction::UIToFP: 6168 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true); 6169 break; 6170 case Instruction::SIToFP: 6171 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true); 6172 break; 6173 default: 6174 break; 6175 } 6176 6177 if (!CastedTo) 6178 return nullptr; 6179 6180 // Make sure the cast doesn't lose any information. 6181 Constant *CastedBack = 6182 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true); 6183 if (CastedBack != C) 6184 return nullptr; 6185 6186 return CastedTo; 6187 } 6188 6189 SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, 6190 Instruction::CastOps *CastOp, 6191 unsigned Depth) { 6192 if (Depth >= MaxAnalysisRecursionDepth) 6193 return {SPF_UNKNOWN, SPNB_NA, false}; 6194 6195 SelectInst *SI = dyn_cast<SelectInst>(V); 6196 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false}; 6197 6198 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition()); 6199 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false}; 6200 6201 Value *TrueVal = SI->getTrueValue(); 6202 Value *FalseVal = SI->getFalseValue(); 6203 6204 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS, 6205 CastOp, Depth); 6206 } 6207 6208 SelectPatternResult llvm::matchDecomposedSelectPattern( 6209 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, 6210 Instruction::CastOps *CastOp, unsigned Depth) { 6211 CmpInst::Predicate Pred = CmpI->getPredicate(); 6212 Value *CmpLHS = CmpI->getOperand(0); 6213 Value *CmpRHS = CmpI->getOperand(1); 6214 FastMathFlags FMF; 6215 if (isa<FPMathOperator>(CmpI)) 6216 FMF = CmpI->getFastMathFlags(); 6217 6218 // Bail out early. 6219 if (CmpI->isEquality()) 6220 return {SPF_UNKNOWN, SPNB_NA, false}; 6221 6222 // Deal with type mismatches. 6223 if (CastOp && CmpLHS->getType() != TrueVal->getType()) { 6224 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) { 6225 // If this is a potential fmin/fmax with a cast to integer, then ignore 6226 // -0.0 because there is no corresponding integer value. 6227 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI) 6228 FMF.setNoSignedZeros(); 6229 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, 6230 cast<CastInst>(TrueVal)->getOperand(0), C, 6231 LHS, RHS, Depth); 6232 } 6233 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) { 6234 // If this is a potential fmin/fmax with a cast to integer, then ignore 6235 // -0.0 because there is no corresponding integer value. 6236 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI) 6237 FMF.setNoSignedZeros(); 6238 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, 6239 C, cast<CastInst>(FalseVal)->getOperand(0), 6240 LHS, RHS, Depth); 6241 } 6242 } 6243 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, 6244 LHS, RHS, Depth); 6245 } 6246 6247 CmpInst::Predicate llvm::getMinMaxPred(SelectPatternFlavor SPF, bool Ordered) { 6248 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT; 6249 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT; 6250 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT; 6251 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT; 6252 if (SPF == SPF_FMINNUM) 6253 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; 6254 if (SPF == SPF_FMAXNUM) 6255 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; 6256 llvm_unreachable("unhandled!"); 6257 } 6258 6259 SelectPatternFlavor llvm::getInverseMinMaxFlavor(SelectPatternFlavor SPF) { 6260 if (SPF == SPF_SMIN) return SPF_SMAX; 6261 if (SPF == SPF_UMIN) return SPF_UMAX; 6262 if (SPF == SPF_SMAX) return SPF_SMIN; 6263 if (SPF == SPF_UMAX) return SPF_UMIN; 6264 llvm_unreachable("unhandled!"); 6265 } 6266 6267 Intrinsic::ID llvm::getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID) { 6268 switch (MinMaxID) { 6269 case Intrinsic::smax: return Intrinsic::smin; 6270 case Intrinsic::smin: return Intrinsic::smax; 6271 case Intrinsic::umax: return Intrinsic::umin; 6272 case Intrinsic::umin: return Intrinsic::umax; 6273 default: llvm_unreachable("Unexpected intrinsic"); 6274 } 6275 } 6276 6277 CmpInst::Predicate llvm::getInverseMinMaxPred(SelectPatternFlavor SPF) { 6278 return getMinMaxPred(getInverseMinMaxFlavor(SPF)); 6279 } 6280 6281 APInt llvm::getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth) { 6282 switch (SPF) { 6283 case SPF_SMAX: return APInt::getSignedMaxValue(BitWidth); 6284 case SPF_SMIN: return APInt::getSignedMinValue(BitWidth); 6285 case SPF_UMAX: return APInt::getMaxValue(BitWidth); 6286 case SPF_UMIN: return APInt::getMinValue(BitWidth); 6287 default: llvm_unreachable("Unexpected flavor"); 6288 } 6289 } 6290 6291 std::pair<Intrinsic::ID, bool> 6292 llvm::canConvertToMinOrMaxIntrinsic(ArrayRef<Value *> VL) { 6293 // Check if VL contains select instructions that can be folded into a min/max 6294 // vector intrinsic and return the intrinsic if it is possible. 6295 // TODO: Support floating point min/max. 6296 bool AllCmpSingleUse = true; 6297 SelectPatternResult SelectPattern; 6298 SelectPattern.Flavor = SPF_UNKNOWN; 6299 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) { 6300 Value *LHS, *RHS; 6301 auto CurrentPattern = matchSelectPattern(I, LHS, RHS); 6302 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor) || 6303 CurrentPattern.Flavor == SPF_FMINNUM || 6304 CurrentPattern.Flavor == SPF_FMAXNUM || 6305 !I->getType()->isIntOrIntVectorTy()) 6306 return false; 6307 if (SelectPattern.Flavor != SPF_UNKNOWN && 6308 SelectPattern.Flavor != CurrentPattern.Flavor) 6309 return false; 6310 SelectPattern = CurrentPattern; 6311 AllCmpSingleUse &= 6312 match(I, m_Select(m_OneUse(m_Value()), m_Value(), m_Value())); 6313 return true; 6314 })) { 6315 switch (SelectPattern.Flavor) { 6316 case SPF_SMIN: 6317 return {Intrinsic::smin, AllCmpSingleUse}; 6318 case SPF_UMIN: 6319 return {Intrinsic::umin, AllCmpSingleUse}; 6320 case SPF_SMAX: 6321 return {Intrinsic::smax, AllCmpSingleUse}; 6322 case SPF_UMAX: 6323 return {Intrinsic::umax, AllCmpSingleUse}; 6324 default: 6325 llvm_unreachable("unexpected select pattern flavor"); 6326 } 6327 } 6328 return {Intrinsic::not_intrinsic, false}; 6329 } 6330 6331 bool llvm::matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, 6332 Value *&Start, Value *&Step) { 6333 // Handle the case of a simple two-predecessor recurrence PHI. 6334 // There's a lot more that could theoretically be done here, but 6335 // this is sufficient to catch some interesting cases. 6336 if (P->getNumIncomingValues() != 2) 6337 return false; 6338 6339 for (unsigned i = 0; i != 2; ++i) { 6340 Value *L = P->getIncomingValue(i); 6341 Value *R = P->getIncomingValue(!i); 6342 Operator *LU = dyn_cast<Operator>(L); 6343 if (!LU) 6344 continue; 6345 unsigned Opcode = LU->getOpcode(); 6346 6347 switch (Opcode) { 6348 default: 6349 continue; 6350 // TODO: Expand list -- xor, div, gep, uaddo, etc.. 6351 case Instruction::LShr: 6352 case Instruction::AShr: 6353 case Instruction::Shl: 6354 case Instruction::Add: 6355 case Instruction::Sub: 6356 case Instruction::And: 6357 case Instruction::Or: 6358 case Instruction::Mul: { 6359 Value *LL = LU->getOperand(0); 6360 Value *LR = LU->getOperand(1); 6361 // Find a recurrence. 6362 if (LL == P) 6363 L = LR; 6364 else if (LR == P) 6365 L = LL; 6366 else 6367 continue; // Check for recurrence with L and R flipped. 6368 6369 break; // Match! 6370 } 6371 }; 6372 6373 // We have matched a recurrence of the form: 6374 // %iv = [R, %entry], [%iv.next, %backedge] 6375 // %iv.next = binop %iv, L 6376 // OR 6377 // %iv = [R, %entry], [%iv.next, %backedge] 6378 // %iv.next = binop L, %iv 6379 BO = cast<BinaryOperator>(LU); 6380 Start = R; 6381 Step = L; 6382 return true; 6383 } 6384 return false; 6385 } 6386 6387 bool llvm::matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P, 6388 Value *&Start, Value *&Step) { 6389 BinaryOperator *BO = nullptr; 6390 P = dyn_cast<PHINode>(I->getOperand(0)); 6391 if (!P) 6392 P = dyn_cast<PHINode>(I->getOperand(1)); 6393 return P && matchSimpleRecurrence(P, BO, Start, Step) && BO == I; 6394 } 6395 6396 /// Return true if "icmp Pred LHS RHS" is always true. 6397 static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, 6398 const Value *RHS, const DataLayout &DL, 6399 unsigned Depth) { 6400 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!"); 6401 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS) 6402 return true; 6403 6404 switch (Pred) { 6405 default: 6406 return false; 6407 6408 case CmpInst::ICMP_SLE: { 6409 const APInt *C; 6410 6411 // LHS s<= LHS +_{nsw} C if C >= 0 6412 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C)))) 6413 return !C->isNegative(); 6414 return false; 6415 } 6416 6417 case CmpInst::ICMP_ULE: { 6418 const APInt *C; 6419 6420 // LHS u<= LHS +_{nuw} C for any C 6421 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C)))) 6422 return true; 6423 6424 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB) 6425 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B, 6426 const Value *&X, 6427 const APInt *&CA, const APInt *&CB) { 6428 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) && 6429 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB)))) 6430 return true; 6431 6432 // If X & C == 0 then (X | C) == X +_{nuw} C 6433 if (match(A, m_Or(m_Value(X), m_APInt(CA))) && 6434 match(B, m_Or(m_Specific(X), m_APInt(CB)))) { 6435 KnownBits Known(CA->getBitWidth()); 6436 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr, 6437 /*CxtI*/ nullptr, /*DT*/ nullptr); 6438 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero)) 6439 return true; 6440 } 6441 6442 return false; 6443 }; 6444 6445 const Value *X; 6446 const APInt *CLHS, *CRHS; 6447 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS)) 6448 return CLHS->ule(*CRHS); 6449 6450 return false; 6451 } 6452 } 6453 } 6454 6455 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred 6456 /// ALHS ARHS" is true. Otherwise, return None. 6457 static Optional<bool> 6458 isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, 6459 const Value *ARHS, const Value *BLHS, const Value *BRHS, 6460 const DataLayout &DL, unsigned Depth) { 6461 switch (Pred) { 6462 default: 6463 return None; 6464 6465 case CmpInst::ICMP_SLT: 6466 case CmpInst::ICMP_SLE: 6467 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) && 6468 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth)) 6469 return true; 6470 return None; 6471 6472 case CmpInst::ICMP_ULT: 6473 case CmpInst::ICMP_ULE: 6474 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) && 6475 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth)) 6476 return true; 6477 return None; 6478 } 6479 } 6480 6481 /// Return true if the operands of the two compares match. IsSwappedOps is true 6482 /// when the operands match, but are swapped. 6483 static bool isMatchingOps(const Value *ALHS, const Value *ARHS, 6484 const Value *BLHS, const Value *BRHS, 6485 bool &IsSwappedOps) { 6486 6487 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS); 6488 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS); 6489 return IsMatchingOps || IsSwappedOps; 6490 } 6491 6492 /// Return true if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is true. 6493 /// Return false if "icmp1 APred X, Y" implies "icmp2 BPred X, Y" is false. 6494 /// Otherwise, return None if we can't infer anything. 6495 static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred, 6496 CmpInst::Predicate BPred, 6497 bool AreSwappedOps) { 6498 // Canonicalize the predicate as if the operands were not commuted. 6499 if (AreSwappedOps) 6500 BPred = ICmpInst::getSwappedPredicate(BPred); 6501 6502 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred)) 6503 return true; 6504 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred)) 6505 return false; 6506 6507 return None; 6508 } 6509 6510 /// Return true if "icmp APred X, C1" implies "icmp BPred X, C2" is true. 6511 /// Return false if "icmp APred X, C1" implies "icmp BPred X, C2" is false. 6512 /// Otherwise, return None if we can't infer anything. 6513 static Optional<bool> 6514 isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, 6515 const ConstantInt *C1, 6516 CmpInst::Predicate BPred, 6517 const ConstantInt *C2) { 6518 ConstantRange DomCR = 6519 ConstantRange::makeExactICmpRegion(APred, C1->getValue()); 6520 ConstantRange CR = ConstantRange::makeExactICmpRegion(BPred, C2->getValue()); 6521 ConstantRange Intersection = DomCR.intersectWith(CR); 6522 ConstantRange Difference = DomCR.difference(CR); 6523 if (Intersection.isEmptySet()) 6524 return false; 6525 if (Difference.isEmptySet()) 6526 return true; 6527 return None; 6528 } 6529 6530 /// Return true if LHS implies RHS is true. Return false if LHS implies RHS is 6531 /// false. Otherwise, return None if we can't infer anything. 6532 static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS, 6533 CmpInst::Predicate BPred, 6534 const Value *BLHS, const Value *BRHS, 6535 const DataLayout &DL, bool LHSIsTrue, 6536 unsigned Depth) { 6537 Value *ALHS = LHS->getOperand(0); 6538 Value *ARHS = LHS->getOperand(1); 6539 6540 // The rest of the logic assumes the LHS condition is true. If that's not the 6541 // case, invert the predicate to make it so. 6542 CmpInst::Predicate APred = 6543 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate(); 6544 6545 // Can we infer anything when the two compares have matching operands? 6546 bool AreSwappedOps; 6547 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, AreSwappedOps)) { 6548 if (Optional<bool> Implication = isImpliedCondMatchingOperands( 6549 APred, BPred, AreSwappedOps)) 6550 return Implication; 6551 // No amount of additional analysis will infer the second condition, so 6552 // early exit. 6553 return None; 6554 } 6555 6556 // Can we infer anything when the LHS operands match and the RHS operands are 6557 // constants (not necessarily matching)? 6558 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) { 6559 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands( 6560 APred, cast<ConstantInt>(ARHS), BPred, cast<ConstantInt>(BRHS))) 6561 return Implication; 6562 // No amount of additional analysis will infer the second condition, so 6563 // early exit. 6564 return None; 6565 } 6566 6567 if (APred == BPred) 6568 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth); 6569 return None; 6570 } 6571 6572 /// Return true if LHS implies RHS is true. Return false if LHS implies RHS is 6573 /// false. Otherwise, return None if we can't infer anything. We expect the 6574 /// RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select' instruction. 6575 static Optional<bool> 6576 isImpliedCondAndOr(const Instruction *LHS, CmpInst::Predicate RHSPred, 6577 const Value *RHSOp0, const Value *RHSOp1, 6578 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) { 6579 // The LHS must be an 'or', 'and', or a 'select' instruction. 6580 assert((LHS->getOpcode() == Instruction::And || 6581 LHS->getOpcode() == Instruction::Or || 6582 LHS->getOpcode() == Instruction::Select) && 6583 "Expected LHS to be 'and', 'or', or 'select'."); 6584 6585 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit"); 6586 6587 // If the result of an 'or' is false, then we know both legs of the 'or' are 6588 // false. Similarly, if the result of an 'and' is true, then we know both 6589 // legs of the 'and' are true. 6590 const Value *ALHS, *ARHS; 6591 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) || 6592 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) { 6593 // FIXME: Make this non-recursion. 6594 if (Optional<bool> Implication = isImpliedCondition( 6595 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1)) 6596 return Implication; 6597 if (Optional<bool> Implication = isImpliedCondition( 6598 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1)) 6599 return Implication; 6600 return None; 6601 } 6602 return None; 6603 } 6604 6605 Optional<bool> 6606 llvm::isImpliedCondition(const Value *LHS, CmpInst::Predicate RHSPred, 6607 const Value *RHSOp0, const Value *RHSOp1, 6608 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) { 6609 // Bail out when we hit the limit. 6610 if (Depth == MaxAnalysisRecursionDepth) 6611 return None; 6612 6613 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for 6614 // example. 6615 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy()) 6616 return None; 6617 6618 Type *OpTy = LHS->getType(); 6619 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!"); 6620 6621 // FIXME: Extending the code below to handle vectors. 6622 if (OpTy->isVectorTy()) 6623 return None; 6624 6625 assert(OpTy->isIntegerTy(1) && "implied by above"); 6626 6627 // Both LHS and RHS are icmps. 6628 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS); 6629 if (LHSCmp) 6630 return isImpliedCondICmps(LHSCmp, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, 6631 Depth); 6632 6633 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect 6634 /// the RHS to be an icmp. 6635 /// FIXME: Add support for and/or/select on the RHS. 6636 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) { 6637 if ((LHSI->getOpcode() == Instruction::And || 6638 LHSI->getOpcode() == Instruction::Or || 6639 LHSI->getOpcode() == Instruction::Select)) 6640 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, 6641 Depth); 6642 } 6643 return None; 6644 } 6645 6646 Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS, 6647 const DataLayout &DL, bool LHSIsTrue, 6648 unsigned Depth) { 6649 // LHS ==> RHS by definition 6650 if (LHS == RHS) 6651 return LHSIsTrue; 6652 6653 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS); 6654 if (RHSCmp) 6655 return isImpliedCondition(LHS, RHSCmp->getPredicate(), 6656 RHSCmp->getOperand(0), RHSCmp->getOperand(1), DL, 6657 LHSIsTrue, Depth); 6658 return None; 6659 } 6660 6661 // Returns a pair (Condition, ConditionIsTrue), where Condition is a branch 6662 // condition dominating ContextI or nullptr, if no condition is found. 6663 static std::pair<Value *, bool> 6664 getDomPredecessorCondition(const Instruction *ContextI) { 6665 if (!ContextI || !ContextI->getParent()) 6666 return {nullptr, false}; 6667 6668 // TODO: This is a poor/cheap way to determine dominance. Should we use a 6669 // dominator tree (eg, from a SimplifyQuery) instead? 6670 const BasicBlock *ContextBB = ContextI->getParent(); 6671 const BasicBlock *PredBB = ContextBB->getSinglePredecessor(); 6672 if (!PredBB) 6673 return {nullptr, false}; 6674 6675 // We need a conditional branch in the predecessor. 6676 Value *PredCond; 6677 BasicBlock *TrueBB, *FalseBB; 6678 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB))) 6679 return {nullptr, false}; 6680 6681 // The branch should get simplified. Don't bother simplifying this condition. 6682 if (TrueBB == FalseBB) 6683 return {nullptr, false}; 6684 6685 assert((TrueBB == ContextBB || FalseBB == ContextBB) && 6686 "Predecessor block does not point to successor?"); 6687 6688 // Is this condition implied by the predecessor condition? 6689 return {PredCond, TrueBB == ContextBB}; 6690 } 6691 6692 Optional<bool> llvm::isImpliedByDomCondition(const Value *Cond, 6693 const Instruction *ContextI, 6694 const DataLayout &DL) { 6695 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool"); 6696 auto PredCond = getDomPredecessorCondition(ContextI); 6697 if (PredCond.first) 6698 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second); 6699 return None; 6700 } 6701 6702 Optional<bool> llvm::isImpliedByDomCondition(CmpInst::Predicate Pred, 6703 const Value *LHS, const Value *RHS, 6704 const Instruction *ContextI, 6705 const DataLayout &DL) { 6706 auto PredCond = getDomPredecessorCondition(ContextI); 6707 if (PredCond.first) 6708 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL, 6709 PredCond.second); 6710 return None; 6711 } 6712 6713 static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, 6714 APInt &Upper, const InstrInfoQuery &IIQ) { 6715 unsigned Width = Lower.getBitWidth(); 6716 const APInt *C; 6717 switch (BO.getOpcode()) { 6718 case Instruction::Add: 6719 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) { 6720 // FIXME: If we have both nuw and nsw, we should reduce the range further. 6721 if (IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(&BO))) { 6722 // 'add nuw x, C' produces [C, UINT_MAX]. 6723 Lower = *C; 6724 } else if (IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(&BO))) { 6725 if (C->isNegative()) { 6726 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C]. 6727 Lower = APInt::getSignedMinValue(Width); 6728 Upper = APInt::getSignedMaxValue(Width) + *C + 1; 6729 } else { 6730 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX]. 6731 Lower = APInt::getSignedMinValue(Width) + *C; 6732 Upper = APInt::getSignedMaxValue(Width) + 1; 6733 } 6734 } 6735 } 6736 break; 6737 6738 case Instruction::And: 6739 if (match(BO.getOperand(1), m_APInt(C))) 6740 // 'and x, C' produces [0, C]. 6741 Upper = *C + 1; 6742 break; 6743 6744 case Instruction::Or: 6745 if (match(BO.getOperand(1), m_APInt(C))) 6746 // 'or x, C' produces [C, UINT_MAX]. 6747 Lower = *C; 6748 break; 6749 6750 case Instruction::AShr: 6751 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) { 6752 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C]. 6753 Lower = APInt::getSignedMinValue(Width).ashr(*C); 6754 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1; 6755 } else if (match(BO.getOperand(0), m_APInt(C))) { 6756 unsigned ShiftAmount = Width - 1; 6757 if (!C->isZero() && IIQ.isExact(&BO)) 6758 ShiftAmount = C->countTrailingZeros(); 6759 if (C->isNegative()) { 6760 // 'ashr C, x' produces [C, C >> (Width-1)] 6761 Lower = *C; 6762 Upper = C->ashr(ShiftAmount) + 1; 6763 } else { 6764 // 'ashr C, x' produces [C >> (Width-1), C] 6765 Lower = C->ashr(ShiftAmount); 6766 Upper = *C + 1; 6767 } 6768 } 6769 break; 6770 6771 case Instruction::LShr: 6772 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) { 6773 // 'lshr x, C' produces [0, UINT_MAX >> C]. 6774 Upper = APInt::getAllOnes(Width).lshr(*C) + 1; 6775 } else if (match(BO.getOperand(0), m_APInt(C))) { 6776 // 'lshr C, x' produces [C >> (Width-1), C]. 6777 unsigned ShiftAmount = Width - 1; 6778 if (!C->isZero() && IIQ.isExact(&BO)) 6779 ShiftAmount = C->countTrailingZeros(); 6780 Lower = C->lshr(ShiftAmount); 6781 Upper = *C + 1; 6782 } 6783 break; 6784 6785 case Instruction::Shl: 6786 if (match(BO.getOperand(0), m_APInt(C))) { 6787 if (IIQ.hasNoUnsignedWrap(&BO)) { 6788 // 'shl nuw C, x' produces [C, C << CLZ(C)] 6789 Lower = *C; 6790 Upper = Lower.shl(Lower.countLeadingZeros()) + 1; 6791 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw? 6792 if (C->isNegative()) { 6793 // 'shl nsw C, x' produces [C << CLO(C)-1, C] 6794 unsigned ShiftAmount = C->countLeadingOnes() - 1; 6795 Lower = C->shl(ShiftAmount); 6796 Upper = *C + 1; 6797 } else { 6798 // 'shl nsw C, x' produces [C, C << CLZ(C)-1] 6799 unsigned ShiftAmount = C->countLeadingZeros() - 1; 6800 Lower = *C; 6801 Upper = C->shl(ShiftAmount) + 1; 6802 } 6803 } 6804 } 6805 break; 6806 6807 case Instruction::SDiv: 6808 if (match(BO.getOperand(1), m_APInt(C))) { 6809 APInt IntMin = APInt::getSignedMinValue(Width); 6810 APInt IntMax = APInt::getSignedMaxValue(Width); 6811 if (C->isAllOnes()) { 6812 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX] 6813 // where C != -1 and C != 0 and C != 1 6814 Lower = IntMin + 1; 6815 Upper = IntMax + 1; 6816 } else if (C->countLeadingZeros() < Width - 1) { 6817 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C] 6818 // where C != -1 and C != 0 and C != 1 6819 Lower = IntMin.sdiv(*C); 6820 Upper = IntMax.sdiv(*C); 6821 if (Lower.sgt(Upper)) 6822 std::swap(Lower, Upper); 6823 Upper = Upper + 1; 6824 assert(Upper != Lower && "Upper part of range has wrapped!"); 6825 } 6826 } else if (match(BO.getOperand(0), m_APInt(C))) { 6827 if (C->isMinSignedValue()) { 6828 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2]. 6829 Lower = *C; 6830 Upper = Lower.lshr(1) + 1; 6831 } else { 6832 // 'sdiv C, x' produces [-|C|, |C|]. 6833 Upper = C->abs() + 1; 6834 Lower = (-Upper) + 1; 6835 } 6836 } 6837 break; 6838 6839 case Instruction::UDiv: 6840 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) { 6841 // 'udiv x, C' produces [0, UINT_MAX / C]. 6842 Upper = APInt::getMaxValue(Width).udiv(*C) + 1; 6843 } else if (match(BO.getOperand(0), m_APInt(C))) { 6844 // 'udiv C, x' produces [0, C]. 6845 Upper = *C + 1; 6846 } 6847 break; 6848 6849 case Instruction::SRem: 6850 if (match(BO.getOperand(1), m_APInt(C))) { 6851 // 'srem x, C' produces (-|C|, |C|). 6852 Upper = C->abs(); 6853 Lower = (-Upper) + 1; 6854 } 6855 break; 6856 6857 case Instruction::URem: 6858 if (match(BO.getOperand(1), m_APInt(C))) 6859 // 'urem x, C' produces [0, C). 6860 Upper = *C; 6861 break; 6862 6863 default: 6864 break; 6865 } 6866 } 6867 6868 static void setLimitsForIntrinsic(const IntrinsicInst &II, APInt &Lower, 6869 APInt &Upper) { 6870 unsigned Width = Lower.getBitWidth(); 6871 const APInt *C; 6872 switch (II.getIntrinsicID()) { 6873 case Intrinsic::ctpop: 6874 case Intrinsic::ctlz: 6875 case Intrinsic::cttz: 6876 // Maximum of set/clear bits is the bit width. 6877 assert(Lower == 0 && "Expected lower bound to be zero"); 6878 Upper = Width + 1; 6879 break; 6880 case Intrinsic::uadd_sat: 6881 // uadd.sat(x, C) produces [C, UINT_MAX]. 6882 if (match(II.getOperand(0), m_APInt(C)) || 6883 match(II.getOperand(1), m_APInt(C))) 6884 Lower = *C; 6885 break; 6886 case Intrinsic::sadd_sat: 6887 if (match(II.getOperand(0), m_APInt(C)) || 6888 match(II.getOperand(1), m_APInt(C))) { 6889 if (C->isNegative()) { 6890 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)]. 6891 Lower = APInt::getSignedMinValue(Width); 6892 Upper = APInt::getSignedMaxValue(Width) + *C + 1; 6893 } else { 6894 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX]. 6895 Lower = APInt::getSignedMinValue(Width) + *C; 6896 Upper = APInt::getSignedMaxValue(Width) + 1; 6897 } 6898 } 6899 break; 6900 case Intrinsic::usub_sat: 6901 // usub.sat(C, x) produces [0, C]. 6902 if (match(II.getOperand(0), m_APInt(C))) 6903 Upper = *C + 1; 6904 // usub.sat(x, C) produces [0, UINT_MAX - C]. 6905 else if (match(II.getOperand(1), m_APInt(C))) 6906 Upper = APInt::getMaxValue(Width) - *C + 1; 6907 break; 6908 case Intrinsic::ssub_sat: 6909 if (match(II.getOperand(0), m_APInt(C))) { 6910 if (C->isNegative()) { 6911 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)]. 6912 Lower = APInt::getSignedMinValue(Width); 6913 Upper = *C - APInt::getSignedMinValue(Width) + 1; 6914 } else { 6915 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX]. 6916 Lower = *C - APInt::getSignedMaxValue(Width); 6917 Upper = APInt::getSignedMaxValue(Width) + 1; 6918 } 6919 } else if (match(II.getOperand(1), m_APInt(C))) { 6920 if (C->isNegative()) { 6921 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]: 6922 Lower = APInt::getSignedMinValue(Width) - *C; 6923 Upper = APInt::getSignedMaxValue(Width) + 1; 6924 } else { 6925 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C]. 6926 Lower = APInt::getSignedMinValue(Width); 6927 Upper = APInt::getSignedMaxValue(Width) - *C + 1; 6928 } 6929 } 6930 break; 6931 case Intrinsic::umin: 6932 case Intrinsic::umax: 6933 case Intrinsic::smin: 6934 case Intrinsic::smax: 6935 if (!match(II.getOperand(0), m_APInt(C)) && 6936 !match(II.getOperand(1), m_APInt(C))) 6937 break; 6938 6939 switch (II.getIntrinsicID()) { 6940 case Intrinsic::umin: 6941 Upper = *C + 1; 6942 break; 6943 case Intrinsic::umax: 6944 Lower = *C; 6945 break; 6946 case Intrinsic::smin: 6947 Lower = APInt::getSignedMinValue(Width); 6948 Upper = *C + 1; 6949 break; 6950 case Intrinsic::smax: 6951 Lower = *C; 6952 Upper = APInt::getSignedMaxValue(Width) + 1; 6953 break; 6954 default: 6955 llvm_unreachable("Must be min/max intrinsic"); 6956 } 6957 break; 6958 case Intrinsic::abs: 6959 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX], 6960 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN. 6961 if (match(II.getOperand(1), m_One())) 6962 Upper = APInt::getSignedMaxValue(Width) + 1; 6963 else 6964 Upper = APInt::getSignedMinValue(Width) + 1; 6965 break; 6966 default: 6967 break; 6968 } 6969 } 6970 6971 static void setLimitsForSelectPattern(const SelectInst &SI, APInt &Lower, 6972 APInt &Upper, const InstrInfoQuery &IIQ) { 6973 const Value *LHS = nullptr, *RHS = nullptr; 6974 SelectPatternResult R = matchSelectPattern(&SI, LHS, RHS); 6975 if (R.Flavor == SPF_UNKNOWN) 6976 return; 6977 6978 unsigned BitWidth = SI.getType()->getScalarSizeInBits(); 6979 6980 if (R.Flavor == SelectPatternFlavor::SPF_ABS) { 6981 // If the negation part of the abs (in RHS) has the NSW flag, 6982 // then the result of abs(X) is [0..SIGNED_MAX], 6983 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN. 6984 Lower = APInt::getZero(BitWidth); 6985 if (match(RHS, m_Neg(m_Specific(LHS))) && 6986 IIQ.hasNoSignedWrap(cast<Instruction>(RHS))) 6987 Upper = APInt::getSignedMaxValue(BitWidth) + 1; 6988 else 6989 Upper = APInt::getSignedMinValue(BitWidth) + 1; 6990 return; 6991 } 6992 6993 if (R.Flavor == SelectPatternFlavor::SPF_NABS) { 6994 // The result of -abs(X) is <= 0. 6995 Lower = APInt::getSignedMinValue(BitWidth); 6996 Upper = APInt(BitWidth, 1); 6997 return; 6998 } 6999 7000 const APInt *C; 7001 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C))) 7002 return; 7003 7004 switch (R.Flavor) { 7005 case SPF_UMIN: 7006 Upper = *C + 1; 7007 break; 7008 case SPF_UMAX: 7009 Lower = *C; 7010 break; 7011 case SPF_SMIN: 7012 Lower = APInt::getSignedMinValue(BitWidth); 7013 Upper = *C + 1; 7014 break; 7015 case SPF_SMAX: 7016 Lower = *C; 7017 Upper = APInt::getSignedMaxValue(BitWidth) + 1; 7018 break; 7019 default: 7020 break; 7021 } 7022 } 7023 7024 ConstantRange llvm::computeConstantRange(const Value *V, bool UseInstrInfo, 7025 AssumptionCache *AC, 7026 const Instruction *CtxI, 7027 const DominatorTree *DT, 7028 unsigned Depth) { 7029 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction"); 7030 7031 if (Depth == MaxAnalysisRecursionDepth) 7032 return ConstantRange::getFull(V->getType()->getScalarSizeInBits()); 7033 7034 const APInt *C; 7035 if (match(V, m_APInt(C))) 7036 return ConstantRange(*C); 7037 7038 InstrInfoQuery IIQ(UseInstrInfo); 7039 unsigned BitWidth = V->getType()->getScalarSizeInBits(); 7040 APInt Lower = APInt(BitWidth, 0); 7041 APInt Upper = APInt(BitWidth, 0); 7042 if (auto *BO = dyn_cast<BinaryOperator>(V)) 7043 setLimitsForBinOp(*BO, Lower, Upper, IIQ); 7044 else if (auto *II = dyn_cast<IntrinsicInst>(V)) 7045 setLimitsForIntrinsic(*II, Lower, Upper); 7046 else if (auto *SI = dyn_cast<SelectInst>(V)) 7047 setLimitsForSelectPattern(*SI, Lower, Upper, IIQ); 7048 7049 ConstantRange CR = ConstantRange::getNonEmpty(Lower, Upper); 7050 7051 if (auto *I = dyn_cast<Instruction>(V)) 7052 if (auto *Range = IIQ.getMetadata(I, LLVMContext::MD_range)) 7053 CR = CR.intersectWith(getConstantRangeFromMetadata(*Range)); 7054 7055 if (CtxI && AC) { 7056 // Try to restrict the range based on information from assumptions. 7057 for (auto &AssumeVH : AC->assumptionsFor(V)) { 7058 if (!AssumeVH) 7059 continue; 7060 CallInst *I = cast<CallInst>(AssumeVH); 7061 assert(I->getParent()->getParent() == CtxI->getParent()->getParent() && 7062 "Got assumption for the wrong function!"); 7063 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && 7064 "must be an assume intrinsic"); 7065 7066 if (!isValidAssumeForContext(I, CtxI, DT)) 7067 continue; 7068 Value *Arg = I->getArgOperand(0); 7069 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg); 7070 // Currently we just use information from comparisons. 7071 if (!Cmp || Cmp->getOperand(0) != V) 7072 continue; 7073 ConstantRange RHS = computeConstantRange(Cmp->getOperand(1), UseInstrInfo, 7074 AC, I, DT, Depth + 1); 7075 CR = CR.intersectWith( 7076 ConstantRange::makeAllowedICmpRegion(Cmp->getPredicate(), RHS)); 7077 } 7078 } 7079 7080 return CR; 7081 } 7082 7083 static Optional<int64_t> 7084 getOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, const DataLayout &DL) { 7085 // Skip over the first indices. 7086 gep_type_iterator GTI = gep_type_begin(GEP); 7087 for (unsigned i = 1; i != Idx; ++i, ++GTI) 7088 /*skip along*/; 7089 7090 // Compute the offset implied by the rest of the indices. 7091 int64_t Offset = 0; 7092 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) { 7093 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i)); 7094 if (!OpC) 7095 return None; 7096 if (OpC->isZero()) 7097 continue; // No offset. 7098 7099 // Handle struct indices, which add their field offset to the pointer. 7100 if (StructType *STy = GTI.getStructTypeOrNull()) { 7101 Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue()); 7102 continue; 7103 } 7104 7105 // Otherwise, we have a sequential type like an array or fixed-length 7106 // vector. Multiply the index by the ElementSize. 7107 TypeSize Size = DL.getTypeAllocSize(GTI.getIndexedType()); 7108 if (Size.isScalable()) 7109 return None; 7110 Offset += Size.getFixedSize() * OpC->getSExtValue(); 7111 } 7112 7113 return Offset; 7114 } 7115 7116 Optional<int64_t> llvm::isPointerOffset(const Value *Ptr1, const Value *Ptr2, 7117 const DataLayout &DL) { 7118 Ptr1 = Ptr1->stripPointerCasts(); 7119 Ptr2 = Ptr2->stripPointerCasts(); 7120 7121 // Handle the trivial case first. 7122 if (Ptr1 == Ptr2) { 7123 return 0; 7124 } 7125 7126 const GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1); 7127 const GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2); 7128 7129 // If one pointer is a GEP see if the GEP is a constant offset from the base, 7130 // as in "P" and "gep P, 1". 7131 // Also do this iteratively to handle the the following case: 7132 // Ptr_t1 = GEP Ptr1, c1 7133 // Ptr_t2 = GEP Ptr_t1, c2 7134 // Ptr2 = GEP Ptr_t2, c3 7135 // where we will return c1+c2+c3. 7136 // TODO: Handle the case when both Ptr1 and Ptr2 are GEPs of some common base 7137 // -- replace getOffsetFromBase with getOffsetAndBase, check that the bases 7138 // are the same, and return the difference between offsets. 7139 auto getOffsetFromBase = [&DL](const GEPOperator *GEP, 7140 const Value *Ptr) -> Optional<int64_t> { 7141 const GEPOperator *GEP_T = GEP; 7142 int64_t OffsetVal = 0; 7143 bool HasSameBase = false; 7144 while (GEP_T) { 7145 auto Offset = getOffsetFromIndex(GEP_T, 1, DL); 7146 if (!Offset) 7147 return None; 7148 OffsetVal += *Offset; 7149 auto Op0 = GEP_T->getOperand(0)->stripPointerCasts(); 7150 if (Op0 == Ptr) { 7151 HasSameBase = true; 7152 break; 7153 } 7154 GEP_T = dyn_cast<GEPOperator>(Op0); 7155 } 7156 if (!HasSameBase) 7157 return None; 7158 return OffsetVal; 7159 }; 7160 7161 if (GEP1) { 7162 auto Offset = getOffsetFromBase(GEP1, Ptr2); 7163 if (Offset) 7164 return -*Offset; 7165 } 7166 if (GEP2) { 7167 auto Offset = getOffsetFromBase(GEP2, Ptr1); 7168 if (Offset) 7169 return Offset; 7170 } 7171 7172 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical 7173 // base. After that base, they may have some number of common (and 7174 // potentially variable) indices. After that they handle some constant 7175 // offset, which determines their offset from each other. At this point, we 7176 // handle no other case. 7177 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0)) 7178 return None; 7179 7180 // Skip any common indices and track the GEP types. 7181 unsigned Idx = 1; 7182 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx) 7183 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx)) 7184 break; 7185 7186 auto Offset1 = getOffsetFromIndex(GEP1, Idx, DL); 7187 auto Offset2 = getOffsetFromIndex(GEP2, Idx, DL); 7188 if (!Offset1 || !Offset2) 7189 return None; 7190 return *Offset2 - *Offset1; 7191 } 7192