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