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