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