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