1 //===- ValueTracking.cpp - Walk computations to compute properties --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains routines that help analyze properties that chains of 11 // computations have. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Analysis/ValueTracking.h" 16 #include "llvm/ADT/Optional.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/MemoryBuiltins.h" 21 #include "llvm/Analysis/Loads.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/VectorUtils.h" 24 #include "llvm/IR/CallSite.h" 25 #include "llvm/IR/ConstantRange.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/GetElementPtrTypeIterator.h" 30 #include "llvm/IR/GlobalAlias.h" 31 #include "llvm/IR/GlobalVariable.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/LLVMContext.h" 35 #include "llvm/IR/Metadata.h" 36 #include "llvm/IR/Operator.h" 37 #include "llvm/IR/PatternMatch.h" 38 #include "llvm/IR/Statepoint.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/MathExtras.h" 41 #include <algorithm> 42 #include <array> 43 #include <cstring> 44 using namespace llvm; 45 using namespace llvm::PatternMatch; 46 47 const unsigned MaxDepth = 6; 48 49 // Controls the number of uses of the value searched for possible 50 // dominating comparisons. 51 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses", 52 cl::Hidden, cl::init(20)); 53 54 // This optimization is known to cause performance regressions is some cases, 55 // keep it under a temporary flag for now. 56 static cl::opt<bool> 57 DontImproveNonNegativePhiBits("dont-improve-non-negative-phi-bits", 58 cl::Hidden, cl::init(true)); 59 60 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns 61 /// 0). For vector types, returns the element type's bitwidth. 62 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) { 63 if (unsigned BitWidth = Ty->getScalarSizeInBits()) 64 return BitWidth; 65 66 return DL.getPointerTypeSizeInBits(Ty); 67 } 68 69 namespace { 70 // Simplifying using an assume can only be done in a particular control-flow 71 // context (the context instruction provides that context). If an assume and 72 // the context instruction are not in the same block then the DT helps in 73 // figuring out if we can use it. 74 struct Query { 75 const DataLayout &DL; 76 AssumptionCache *AC; 77 const Instruction *CxtI; 78 const DominatorTree *DT; 79 80 /// Set of assumptions that should be excluded from further queries. 81 /// This is because of the potential for mutual recursion to cause 82 /// computeKnownBits to repeatedly visit the same assume intrinsic. The 83 /// classic case of this is assume(x = y), which will attempt to determine 84 /// bits in x from bits in y, which will attempt to determine bits in y from 85 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call 86 /// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and 87 /// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so 88 /// on. 89 std::array<const Value *, MaxDepth> Excluded; 90 unsigned NumExcluded; 91 92 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, 93 const DominatorTree *DT) 94 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), NumExcluded(0) {} 95 96 Query(const Query &Q, const Value *NewExcl) 97 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), NumExcluded(Q.NumExcluded) { 98 Excluded = Q.Excluded; 99 Excluded[NumExcluded++] = NewExcl; 100 assert(NumExcluded <= Excluded.size()); 101 } 102 103 bool isExcluded(const Value *Value) const { 104 if (NumExcluded == 0) 105 return false; 106 auto End = Excluded.begin() + NumExcluded; 107 return std::find(Excluded.begin(), End, Value) != End; 108 } 109 }; 110 } // end anonymous namespace 111 112 // Given the provided Value and, potentially, a context instruction, return 113 // the preferred context instruction (if any). 114 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) { 115 // If we've been provided with a context instruction, then use that (provided 116 // it has been inserted). 117 if (CxtI && CxtI->getParent()) 118 return CxtI; 119 120 // If the value is really an already-inserted instruction, then use that. 121 CxtI = dyn_cast<Instruction>(V); 122 if (CxtI && CxtI->getParent()) 123 return CxtI; 124 125 return nullptr; 126 } 127 128 static void computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne, 129 unsigned Depth, const Query &Q); 130 131 void llvm::computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne, 132 const DataLayout &DL, unsigned Depth, 133 AssumptionCache *AC, const Instruction *CxtI, 134 const DominatorTree *DT) { 135 ::computeKnownBits(V, KnownZero, KnownOne, Depth, 136 Query(DL, AC, safeCxtI(V, CxtI), DT)); 137 } 138 139 bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS, 140 const DataLayout &DL, 141 AssumptionCache *AC, const Instruction *CxtI, 142 const DominatorTree *DT) { 143 assert(LHS->getType() == RHS->getType() && 144 "LHS and RHS should have the same type"); 145 assert(LHS->getType()->isIntOrIntVectorTy() && 146 "LHS and RHS should be integers"); 147 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType()); 148 APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0); 149 APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0); 150 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT); 151 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT); 152 return (LHSKnownZero | RHSKnownZero).isAllOnesValue(); 153 } 154 155 static void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne, 156 unsigned Depth, const Query &Q); 157 158 void llvm::ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne, 159 const DataLayout &DL, unsigned Depth, 160 AssumptionCache *AC, const Instruction *CxtI, 161 const DominatorTree *DT) { 162 ::ComputeSignBit(V, KnownZero, KnownOne, Depth, 163 Query(DL, AC, safeCxtI(V, CxtI), DT)); 164 } 165 166 static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth, 167 const Query &Q); 168 169 bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, 170 bool OrZero, 171 unsigned Depth, AssumptionCache *AC, 172 const Instruction *CxtI, 173 const DominatorTree *DT) { 174 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth, 175 Query(DL, AC, safeCxtI(V, CxtI), DT)); 176 } 177 178 static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q); 179 180 bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth, 181 AssumptionCache *AC, const Instruction *CxtI, 182 const DominatorTree *DT) { 183 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT)); 184 } 185 186 bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL, 187 unsigned Depth, 188 AssumptionCache *AC, const Instruction *CxtI, 189 const DominatorTree *DT) { 190 bool NonNegative, Negative; 191 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT); 192 return NonNegative; 193 } 194 195 bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth, 196 AssumptionCache *AC, const Instruction *CxtI, 197 const DominatorTree *DT) { 198 if (auto *CI = dyn_cast<ConstantInt>(V)) 199 return CI->getValue().isStrictlyPositive(); 200 201 // TODO: We'd doing two recursive queries here. We should factor this such 202 // that only a single query is needed. 203 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) && 204 isKnownNonZero(V, DL, Depth, AC, CxtI, DT); 205 } 206 207 bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth, 208 AssumptionCache *AC, const Instruction *CxtI, 209 const DominatorTree *DT) { 210 bool NonNegative, Negative; 211 ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT); 212 return Negative; 213 } 214 215 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q); 216 217 bool llvm::isKnownNonEqual(const Value *V1, const Value *V2, 218 const DataLayout &DL, 219 AssumptionCache *AC, const Instruction *CxtI, 220 const DominatorTree *DT) { 221 return ::isKnownNonEqual(V1, V2, Query(DL, AC, 222 safeCxtI(V1, safeCxtI(V2, CxtI)), 223 DT)); 224 } 225 226 static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth, 227 const Query &Q); 228 229 bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask, 230 const DataLayout &DL, 231 unsigned Depth, AssumptionCache *AC, 232 const Instruction *CxtI, const DominatorTree *DT) { 233 return ::MaskedValueIsZero(V, Mask, Depth, 234 Query(DL, AC, safeCxtI(V, CxtI), DT)); 235 } 236 237 static unsigned ComputeNumSignBits(const Value *V, unsigned Depth, 238 const Query &Q); 239 240 unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL, 241 unsigned Depth, AssumptionCache *AC, 242 const Instruction *CxtI, 243 const DominatorTree *DT) { 244 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT)); 245 } 246 247 static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, 248 bool NSW, 249 APInt &KnownZero, APInt &KnownOne, 250 APInt &KnownZero2, APInt &KnownOne2, 251 unsigned Depth, const Query &Q) { 252 if (!Add) { 253 if (const ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) { 254 // We know that the top bits of C-X are clear if X contains less bits 255 // than C (i.e. no wrap-around can happen). For example, 20-X is 256 // positive if we can prove that X is >= 0 and < 16. 257 if (!CLHS->getValue().isNegative()) { 258 unsigned BitWidth = KnownZero.getBitWidth(); 259 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros(); 260 // NLZ can't be BitWidth with no sign bit 261 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 262 computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q); 263 264 // If all of the MaskV bits are known to be zero, then we know the 265 // output top bits are zero, because we now know that the output is 266 // from [0-C]. 267 if ((KnownZero2 & MaskV) == MaskV) { 268 unsigned NLZ2 = CLHS->getValue().countLeadingZeros(); 269 // Top bits known zero. 270 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2); 271 } 272 } 273 } 274 } 275 276 unsigned BitWidth = KnownZero.getBitWidth(); 277 278 // If an initial sequence of bits in the result is not needed, the 279 // corresponding bits in the operands are not needed. 280 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0); 281 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, Depth + 1, Q); 282 computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q); 283 284 // Carry in a 1 for a subtract, rather than a 0. 285 APInt CarryIn(BitWidth, 0); 286 if (!Add) { 287 // Sum = LHS + ~RHS + 1 288 std::swap(KnownZero2, KnownOne2); 289 CarryIn.setBit(0); 290 } 291 292 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn; 293 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn; 294 295 // Compute known bits of the carry. 296 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2); 297 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2; 298 299 // Compute set of known bits (where all three relevant bits are known). 300 APInt LHSKnown = LHSKnownZero | LHSKnownOne; 301 APInt RHSKnown = KnownZero2 | KnownOne2; 302 APInt CarryKnown = CarryKnownZero | CarryKnownOne; 303 APInt Known = LHSKnown & RHSKnown & CarryKnown; 304 305 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) && 306 "known bits of sum differ"); 307 308 // Compute known bits of the result. 309 KnownZero = ~PossibleSumOne & Known; 310 KnownOne = PossibleSumOne & Known; 311 312 // Are we still trying to solve for the sign bit? 313 if (!Known.isNegative()) { 314 if (NSW) { 315 // Adding two non-negative numbers, or subtracting a negative number from 316 // a non-negative one, can't wrap into negative. 317 if (LHSKnownZero.isNegative() && KnownZero2.isNegative()) 318 KnownZero |= APInt::getSignBit(BitWidth); 319 // Adding two negative numbers, or subtracting a non-negative number from 320 // a negative one, can't wrap into non-negative. 321 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative()) 322 KnownOne |= APInt::getSignBit(BitWidth); 323 } 324 } 325 } 326 327 static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, 328 APInt &KnownZero, APInt &KnownOne, 329 APInt &KnownZero2, APInt &KnownOne2, 330 unsigned Depth, const Query &Q) { 331 unsigned BitWidth = KnownZero.getBitWidth(); 332 computeKnownBits(Op1, KnownZero, KnownOne, Depth + 1, Q); 333 computeKnownBits(Op0, KnownZero2, KnownOne2, Depth + 1, Q); 334 335 bool isKnownNegative = false; 336 bool isKnownNonNegative = false; 337 // If the multiplication is known not to overflow, compute the sign bit. 338 if (NSW) { 339 if (Op0 == Op1) { 340 // The product of a number with itself is non-negative. 341 isKnownNonNegative = true; 342 } else { 343 bool isKnownNonNegativeOp1 = KnownZero.isNegative(); 344 bool isKnownNonNegativeOp0 = KnownZero2.isNegative(); 345 bool isKnownNegativeOp1 = KnownOne.isNegative(); 346 bool isKnownNegativeOp0 = KnownOne2.isNegative(); 347 // The product of two numbers with the same sign is non-negative. 348 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) || 349 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0); 350 // The product of a negative number and a non-negative number is either 351 // negative or zero. 352 if (!isKnownNonNegative) 353 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 && 354 isKnownNonZero(Op0, Depth, Q)) || 355 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && 356 isKnownNonZero(Op1, Depth, Q)); 357 } 358 } 359 360 // If low bits are zero in either operand, output low known-0 bits. 361 // Also compute a conservative estimate for high known-0 bits. 362 // More trickiness is possible, but this is sufficient for the 363 // interesting case of alignment computation. 364 KnownOne.clearAllBits(); 365 unsigned TrailZ = KnownZero.countTrailingOnes() + 366 KnownZero2.countTrailingOnes(); 367 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 368 KnownZero2.countLeadingOnes(), 369 BitWidth) - BitWidth; 370 371 TrailZ = std::min(TrailZ, BitWidth); 372 LeadZ = std::min(LeadZ, BitWidth); 373 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 374 APInt::getHighBitsSet(BitWidth, LeadZ); 375 376 // Only make use of no-wrap flags if we failed to compute the sign bit 377 // directly. This matters if the multiplication always overflows, in 378 // which case we prefer to follow the result of the direct computation, 379 // though as the program is invoking undefined behaviour we can choose 380 // whatever we like here. 381 if (isKnownNonNegative && !KnownOne.isNegative()) 382 KnownZero.setBit(BitWidth - 1); 383 else if (isKnownNegative && !KnownZero.isNegative()) 384 KnownOne.setBit(BitWidth - 1); 385 } 386 387 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges, 388 APInt &KnownZero, 389 APInt &KnownOne) { 390 unsigned BitWidth = KnownZero.getBitWidth(); 391 unsigned NumRanges = Ranges.getNumOperands() / 2; 392 assert(NumRanges >= 1); 393 394 KnownZero.setAllBits(); 395 KnownOne.setAllBits(); 396 397 for (unsigned i = 0; i < NumRanges; ++i) { 398 ConstantInt *Lower = 399 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0)); 400 ConstantInt *Upper = 401 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1)); 402 ConstantRange Range(Lower->getValue(), Upper->getValue()); 403 404 // The first CommonPrefixBits of all values in Range are equal. 405 unsigned CommonPrefixBits = 406 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros(); 407 408 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits); 409 KnownOne &= Range.getUnsignedMax() & Mask; 410 KnownZero &= ~Range.getUnsignedMax() & Mask; 411 } 412 } 413 414 static bool isEphemeralValueOf(const Instruction *I, const Value *E) { 415 SmallVector<const Value *, 16> WorkSet(1, I); 416 SmallPtrSet<const Value *, 32> Visited; 417 SmallPtrSet<const Value *, 16> EphValues; 418 419 // The instruction defining an assumption's condition itself is always 420 // considered ephemeral to that assumption (even if it has other 421 // non-ephemeral users). See r246696's test case for an example. 422 if (is_contained(I->operands(), E)) 423 return true; 424 425 while (!WorkSet.empty()) { 426 const Value *V = WorkSet.pop_back_val(); 427 if (!Visited.insert(V).second) 428 continue; 429 430 // If all uses of this value are ephemeral, then so is this value. 431 if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) { 432 if (V == E) 433 return true; 434 435 EphValues.insert(V); 436 if (const User *U = dyn_cast<User>(V)) 437 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end(); 438 J != JE; ++J) { 439 if (isSafeToSpeculativelyExecute(*J)) 440 WorkSet.push_back(*J); 441 } 442 } 443 } 444 445 return false; 446 } 447 448 // Is this an intrinsic that cannot be speculated but also cannot trap? 449 static bool isAssumeLikeIntrinsic(const Instruction *I) { 450 if (const CallInst *CI = dyn_cast<CallInst>(I)) 451 if (Function *F = CI->getCalledFunction()) 452 switch (F->getIntrinsicID()) { 453 default: break; 454 // FIXME: This list is repeated from NoTTI::getIntrinsicCost. 455 case Intrinsic::assume: 456 case Intrinsic::dbg_declare: 457 case Intrinsic::dbg_value: 458 case Intrinsic::invariant_start: 459 case Intrinsic::invariant_end: 460 case Intrinsic::lifetime_start: 461 case Intrinsic::lifetime_end: 462 case Intrinsic::objectsize: 463 case Intrinsic::ptr_annotation: 464 case Intrinsic::var_annotation: 465 return true; 466 } 467 468 return false; 469 } 470 471 bool llvm::isValidAssumeForContext(const Instruction *Inv, 472 const Instruction *CxtI, 473 const DominatorTree *DT) { 474 475 // There are two restrictions on the use of an assume: 476 // 1. The assume must dominate the context (or the control flow must 477 // reach the assume whenever it reaches the context). 478 // 2. The context must not be in the assume's set of ephemeral values 479 // (otherwise we will use the assume to prove that the condition 480 // feeding the assume is trivially true, thus causing the removal of 481 // the assume). 482 483 if (DT) { 484 if (DT->dominates(Inv, CxtI)) 485 return true; 486 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) { 487 // We don't have a DT, but this trivially dominates. 488 return true; 489 } 490 491 // With or without a DT, the only remaining case we will check is if the 492 // instructions are in the same BB. Give up if that is not the case. 493 if (Inv->getParent() != CxtI->getParent()) 494 return false; 495 496 // If we have a dom tree, then we now know that the assume doens't dominate 497 // the other instruction. If we don't have a dom tree then we can check if 498 // the assume is first in the BB. 499 if (!DT) { 500 // Search forward from the assume until we reach the context (or the end 501 // of the block); the common case is that the assume will come first. 502 for (auto I = std::next(BasicBlock::const_iterator(Inv)), 503 IE = Inv->getParent()->end(); I != IE; ++I) 504 if (&*I == CxtI) 505 return true; 506 } 507 508 // The context comes first, but they're both in the same block. Make sure 509 // there is nothing in between that might interrupt the control flow. 510 for (BasicBlock::const_iterator I = 511 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv); 512 I != IE; ++I) 513 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I)) 514 return false; 515 516 return !isEphemeralValueOf(Inv, CxtI); 517 } 518 519 static void computeKnownBitsFromAssume(const Value *V, APInt &KnownZero, 520 APInt &KnownOne, unsigned Depth, 521 const Query &Q) { 522 // Use of assumptions is context-sensitive. If we don't have a context, we 523 // cannot use them! 524 if (!Q.AC || !Q.CxtI) 525 return; 526 527 unsigned BitWidth = KnownZero.getBitWidth(); 528 529 for (auto &AssumeVH : Q.AC->assumptions()) { 530 if (!AssumeVH) 531 continue; 532 CallInst *I = cast<CallInst>(AssumeVH); 533 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() && 534 "Got assumption for the wrong function!"); 535 if (Q.isExcluded(I)) 536 continue; 537 538 // Warning: This loop can end up being somewhat performance sensetive. 539 // We're running this loop for once for each value queried resulting in a 540 // runtime of ~O(#assumes * #values). 541 542 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && 543 "must be an assume intrinsic"); 544 545 Value *Arg = I->getArgOperand(0); 546 547 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 548 assert(BitWidth == 1 && "assume operand is not i1?"); 549 KnownZero.clearAllBits(); 550 KnownOne.setAllBits(); 551 return; 552 } 553 554 // The remaining tests are all recursive, so bail out if we hit the limit. 555 if (Depth == MaxDepth) 556 continue; 557 558 Value *A, *B; 559 auto m_V = m_CombineOr(m_Specific(V), 560 m_CombineOr(m_PtrToInt(m_Specific(V)), 561 m_BitCast(m_Specific(V)))); 562 563 CmpInst::Predicate Pred; 564 ConstantInt *C; 565 // assume(v = a) 566 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) && 567 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 568 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 569 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 570 KnownZero |= RHSKnownZero; 571 KnownOne |= RHSKnownOne; 572 // assume(v & b = a) 573 } else if (match(Arg, 574 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) && 575 Pred == ICmpInst::ICMP_EQ && 576 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 577 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 578 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 579 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0); 580 computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I)); 581 582 // For those bits in the mask that are known to be one, we can propagate 583 // known bits from the RHS to V. 584 KnownZero |= RHSKnownZero & MaskKnownOne; 585 KnownOne |= RHSKnownOne & MaskKnownOne; 586 // assume(~(v & b) = a) 587 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))), 588 m_Value(A))) && 589 Pred == ICmpInst::ICMP_EQ && 590 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 591 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 592 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 593 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0); 594 computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I)); 595 596 // For those bits in the mask that are known to be one, we can propagate 597 // inverted known bits from the RHS to V. 598 KnownZero |= RHSKnownOne & MaskKnownOne; 599 KnownOne |= RHSKnownZero & MaskKnownOne; 600 // assume(v | b = a) 601 } else if (match(Arg, 602 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) && 603 Pred == ICmpInst::ICMP_EQ && 604 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 605 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 606 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 607 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0); 608 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I)); 609 610 // For those bits in B that are known to be zero, we can propagate known 611 // bits from the RHS to V. 612 KnownZero |= RHSKnownZero & BKnownZero; 613 KnownOne |= RHSKnownOne & BKnownZero; 614 // assume(~(v | b) = a) 615 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))), 616 m_Value(A))) && 617 Pred == ICmpInst::ICMP_EQ && 618 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 619 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 620 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 621 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0); 622 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I)); 623 624 // For those bits in B that are known to be zero, we can propagate 625 // inverted known bits from the RHS to V. 626 KnownZero |= RHSKnownOne & BKnownZero; 627 KnownOne |= RHSKnownZero & BKnownZero; 628 // assume(v ^ b = a) 629 } else if (match(Arg, 630 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) && 631 Pred == ICmpInst::ICMP_EQ && 632 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 633 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 634 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 635 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0); 636 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I)); 637 638 // For those bits in B that are known to be zero, we can propagate known 639 // bits from the RHS to V. For those bits in B that are known to be one, 640 // we can propagate inverted known bits from the RHS to V. 641 KnownZero |= RHSKnownZero & BKnownZero; 642 KnownOne |= RHSKnownOne & BKnownZero; 643 KnownZero |= RHSKnownOne & BKnownOne; 644 KnownOne |= RHSKnownZero & BKnownOne; 645 // assume(~(v ^ b) = a) 646 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))), 647 m_Value(A))) && 648 Pred == ICmpInst::ICMP_EQ && 649 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 650 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 651 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 652 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0); 653 computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I)); 654 655 // For those bits in B that are known to be zero, we can propagate 656 // inverted known bits from the RHS to V. For those bits in B that are 657 // known to be one, we can propagate known bits from the RHS to V. 658 KnownZero |= RHSKnownOne & BKnownZero; 659 KnownOne |= RHSKnownZero & BKnownZero; 660 KnownZero |= RHSKnownZero & BKnownOne; 661 KnownOne |= RHSKnownOne & BKnownOne; 662 // assume(v << c = a) 663 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)), 664 m_Value(A))) && 665 Pred == ICmpInst::ICMP_EQ && 666 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 667 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 668 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 669 // For those bits in RHS that are known, we can propagate them to known 670 // bits in V shifted to the right by C. 671 KnownZero |= RHSKnownZero.lshr(C->getZExtValue()); 672 KnownOne |= RHSKnownOne.lshr(C->getZExtValue()); 673 // assume(~(v << c) = a) 674 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))), 675 m_Value(A))) && 676 Pred == ICmpInst::ICMP_EQ && 677 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 678 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 679 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 680 // For those bits in RHS that are known, we can propagate them inverted 681 // to known bits in V shifted to the right by C. 682 KnownZero |= RHSKnownOne.lshr(C->getZExtValue()); 683 KnownOne |= RHSKnownZero.lshr(C->getZExtValue()); 684 // assume(v >> c = a) 685 } else if (match(Arg, 686 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)), 687 m_AShr(m_V, m_ConstantInt(C))), 688 m_Value(A))) && 689 Pred == ICmpInst::ICMP_EQ && 690 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 691 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 692 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 693 // For those bits in RHS that are known, we can propagate them to known 694 // bits in V shifted to the right by C. 695 KnownZero |= RHSKnownZero << C->getZExtValue(); 696 KnownOne |= RHSKnownOne << C->getZExtValue(); 697 // assume(~(v >> c) = a) 698 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr( 699 m_LShr(m_V, m_ConstantInt(C)), 700 m_AShr(m_V, m_ConstantInt(C)))), 701 m_Value(A))) && 702 Pred == ICmpInst::ICMP_EQ && 703 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 704 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 705 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 706 // For those bits in RHS that are known, we can propagate them inverted 707 // to known bits in V shifted to the right by C. 708 KnownZero |= RHSKnownOne << C->getZExtValue(); 709 KnownOne |= RHSKnownZero << C->getZExtValue(); 710 // assume(v >=_s c) where c is non-negative 711 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) && 712 Pred == ICmpInst::ICMP_SGE && 713 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 714 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 715 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 716 717 if (RHSKnownZero.isNegative()) { 718 // We know that the sign bit is zero. 719 KnownZero |= APInt::getSignBit(BitWidth); 720 } 721 // assume(v >_s c) where c is at least -1. 722 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) && 723 Pred == ICmpInst::ICMP_SGT && 724 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 725 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 726 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 727 728 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) { 729 // We know that the sign bit is zero. 730 KnownZero |= APInt::getSignBit(BitWidth); 731 } 732 // assume(v <=_s c) where c is negative 733 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) && 734 Pred == ICmpInst::ICMP_SLE && 735 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 736 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 737 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 738 739 if (RHSKnownOne.isNegative()) { 740 // We know that the sign bit is one. 741 KnownOne |= APInt::getSignBit(BitWidth); 742 } 743 // assume(v <_s c) where c is non-positive 744 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) && 745 Pred == ICmpInst::ICMP_SLT && 746 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 747 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 748 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 749 750 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) { 751 // We know that the sign bit is one. 752 KnownOne |= APInt::getSignBit(BitWidth); 753 } 754 // assume(v <=_u c) 755 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) && 756 Pred == ICmpInst::ICMP_ULE && 757 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 758 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 759 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 760 761 // Whatever high bits in c are zero are known to be zero. 762 KnownZero |= 763 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()); 764 // assume(v <_u c) 765 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) && 766 Pred == ICmpInst::ICMP_ULT && 767 isValidAssumeForContext(I, Q.CxtI, Q.DT)) { 768 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0); 769 computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I)); 770 771 // Whatever high bits in c are zero are known to be zero (if c is a power 772 // of 2, then one more). 773 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I))) 774 KnownZero |= 775 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1); 776 else 777 KnownZero |= 778 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()); 779 } 780 } 781 } 782 783 // Compute known bits from a shift operator, including those with a 784 // non-constant shift amount. KnownZero and KnownOne are the outputs of this 785 // function. KnownZero2 and KnownOne2 are pre-allocated temporaries with the 786 // same bit width as KnownZero and KnownOne. KZF and KOF are operator-specific 787 // functors that, given the known-zero or known-one bits respectively, and a 788 // shift amount, compute the implied known-zero or known-one bits of the shift 789 // operator's result respectively for that shift amount. The results from calling 790 // KZF and KOF are conservatively combined for all permitted shift amounts. 791 static void computeKnownBitsFromShiftOperator( 792 const Operator *I, APInt &KnownZero, APInt &KnownOne, APInt &KnownZero2, 793 APInt &KnownOne2, unsigned Depth, const Query &Q, 794 function_ref<APInt(const APInt &, unsigned)> KZF, 795 function_ref<APInt(const APInt &, unsigned)> KOF) { 796 unsigned BitWidth = KnownZero.getBitWidth(); 797 798 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 799 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1); 800 801 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 802 KnownZero = KZF(KnownZero, ShiftAmt); 803 KnownOne = KOF(KnownOne, ShiftAmt); 804 // If there is conflict between KnownZero and KnownOne, this must be an 805 // overflowing left shift, so the shift result is undefined. Clear KnownZero 806 // and KnownOne bits so that other code could propagate this undef. 807 if ((KnownZero & KnownOne) != 0) { 808 KnownZero.clearAllBits(); 809 KnownOne.clearAllBits(); 810 } 811 812 return; 813 } 814 815 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q); 816 817 // Note: We cannot use KnownZero.getLimitedValue() here, because if 818 // BitWidth > 64 and any upper bits are known, we'll end up returning the 819 // limit value (which implies all bits are known). 820 uint64_t ShiftAmtKZ = KnownZero.zextOrTrunc(64).getZExtValue(); 821 uint64_t ShiftAmtKO = KnownOne.zextOrTrunc(64).getZExtValue(); 822 823 // It would be more-clearly correct to use the two temporaries for this 824 // calculation. Reusing the APInts here to prevent unnecessary allocations. 825 KnownZero.clearAllBits(); 826 KnownOne.clearAllBits(); 827 828 // If we know the shifter operand is nonzero, we can sometimes infer more 829 // known bits. However this is expensive to compute, so be lazy about it and 830 // only compute it when absolutely necessary. 831 Optional<bool> ShifterOperandIsNonZero; 832 833 // Early exit if we can't constrain any well-defined shift amount. 834 if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) { 835 ShifterOperandIsNonZero = 836 isKnownNonZero(I->getOperand(1), Depth + 1, Q); 837 if (!*ShifterOperandIsNonZero) 838 return; 839 } 840 841 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q); 842 843 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth); 844 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) { 845 // Combine the shifted known input bits only for those shift amounts 846 // compatible with its known constraints. 847 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt) 848 continue; 849 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt) 850 continue; 851 // If we know the shifter is nonzero, we may be able to infer more known 852 // bits. This check is sunk down as far as possible to avoid the expensive 853 // call to isKnownNonZero if the cheaper checks above fail. 854 if (ShiftAmt == 0) { 855 if (!ShifterOperandIsNonZero.hasValue()) 856 ShifterOperandIsNonZero = 857 isKnownNonZero(I->getOperand(1), Depth + 1, Q); 858 if (*ShifterOperandIsNonZero) 859 continue; 860 } 861 862 KnownZero &= KZF(KnownZero2, ShiftAmt); 863 KnownOne &= KOF(KnownOne2, ShiftAmt); 864 } 865 866 // If there are no compatible shift amounts, then we've proven that the shift 867 // amount must be >= the BitWidth, and the result is undefined. We could 868 // return anything we'd like, but we need to make sure the sets of known bits 869 // stay disjoint (it should be better for some other code to actually 870 // propagate the undef than to pick a value here using known bits). 871 if ((KnownZero & KnownOne) != 0) { 872 KnownZero.clearAllBits(); 873 KnownOne.clearAllBits(); 874 } 875 } 876 877 static void computeKnownBitsFromOperator(const Operator *I, APInt &KnownZero, 878 APInt &KnownOne, unsigned Depth, 879 const Query &Q) { 880 unsigned BitWidth = KnownZero.getBitWidth(); 881 882 APInt KnownZero2(KnownZero), KnownOne2(KnownOne); 883 switch (I->getOpcode()) { 884 default: break; 885 case Instruction::Load: 886 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range)) 887 computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne); 888 break; 889 case Instruction::And: { 890 // If either the LHS or the RHS are Zero, the result is zero. 891 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q); 892 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q); 893 894 // Output known-1 bits are only known if set in both the LHS & RHS. 895 KnownOne &= KnownOne2; 896 // Output known-0 are known to be clear if zero in either the LHS | RHS. 897 KnownZero |= KnownZero2; 898 899 // and(x, add (x, -1)) is a common idiom that always clears the low bit; 900 // here we handle the more general case of adding any odd number by 901 // matching the form add(x, add(x, y)) where y is odd. 902 // TODO: This could be generalized to clearing any bit set in y where the 903 // following bit is known to be unset in y. 904 Value *Y = nullptr; 905 if (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)), 906 m_Value(Y))) || 907 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)), 908 m_Value(Y)))) { 909 APInt KnownZero3(BitWidth, 0), KnownOne3(BitWidth, 0); 910 computeKnownBits(Y, KnownZero3, KnownOne3, Depth + 1, Q); 911 if (KnownOne3.countTrailingOnes() > 0) 912 KnownZero |= APInt::getLowBitsSet(BitWidth, 1); 913 } 914 break; 915 } 916 case Instruction::Or: { 917 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q); 918 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q); 919 920 // Output known-0 bits are only known if clear in both the LHS & RHS. 921 KnownZero &= KnownZero2; 922 // Output known-1 are known to be set if set in either the LHS | RHS. 923 KnownOne |= KnownOne2; 924 break; 925 } 926 case Instruction::Xor: { 927 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q); 928 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q); 929 930 // Output known-0 bits are known if clear or set in both the LHS & RHS. 931 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 932 // Output known-1 are known to be set if set in only one of the LHS, RHS. 933 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 934 KnownZero = KnownZeroOut; 935 break; 936 } 937 case Instruction::Mul: { 938 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap(); 939 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero, 940 KnownOne, KnownZero2, KnownOne2, Depth, Q); 941 break; 942 } 943 case Instruction::UDiv: { 944 // For the purposes of computing leading zeros we can conservatively 945 // treat a udiv as a logical right shift by the power of 2 known to 946 // be less than the denominator. 947 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q); 948 unsigned LeadZ = KnownZero2.countLeadingOnes(); 949 950 KnownOne2.clearAllBits(); 951 KnownZero2.clearAllBits(); 952 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q); 953 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 954 if (RHSUnknownLeadingOnes != BitWidth) 955 LeadZ = std::min(BitWidth, 956 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 957 958 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ); 959 break; 960 } 961 case Instruction::Select: { 962 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, Depth + 1, Q); 963 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q); 964 965 const Value *LHS; 966 const Value *RHS; 967 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor; 968 if (SelectPatternResult::isMinOrMax(SPF)) { 969 computeKnownBits(RHS, KnownZero, KnownOne, Depth + 1, Q); 970 computeKnownBits(LHS, KnownZero2, KnownOne2, Depth + 1, Q); 971 } else { 972 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, Depth + 1, Q); 973 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q); 974 } 975 976 unsigned MaxHighOnes = 0; 977 unsigned MaxHighZeros = 0; 978 if (SPF == SPF_SMAX) { 979 // If both sides are negative, the result is negative. 980 if (KnownOne[BitWidth - 1] && KnownOne2[BitWidth - 1]) 981 // We can derive a lower bound on the result by taking the max of the 982 // leading one bits. 983 MaxHighOnes = 984 std::max(KnownOne.countLeadingOnes(), KnownOne2.countLeadingOnes()); 985 // If either side is non-negative, the result is non-negative. 986 else if (KnownZero[BitWidth - 1] || KnownZero2[BitWidth - 1]) 987 MaxHighZeros = 1; 988 } else if (SPF == SPF_SMIN) { 989 // If both sides are non-negative, the result is non-negative. 990 if (KnownZero[BitWidth - 1] && KnownZero2[BitWidth - 1]) 991 // We can derive an upper bound on the result by taking the max of the 992 // leading zero bits. 993 MaxHighZeros = std::max(KnownZero.countLeadingOnes(), 994 KnownZero2.countLeadingOnes()); 995 // If either side is negative, the result is negative. 996 else if (KnownOne[BitWidth - 1] || KnownOne2[BitWidth - 1]) 997 MaxHighOnes = 1; 998 } else if (SPF == SPF_UMAX) { 999 // We can derive a lower bound on the result by taking the max of the 1000 // leading one bits. 1001 MaxHighOnes = 1002 std::max(KnownOne.countLeadingOnes(), KnownOne2.countLeadingOnes()); 1003 } else if (SPF == SPF_UMIN) { 1004 // We can derive an upper bound on the result by taking the max of the 1005 // leading zero bits. 1006 MaxHighZeros = 1007 std::max(KnownZero.countLeadingOnes(), KnownZero2.countLeadingOnes()); 1008 } 1009 1010 // Only known if known in both the LHS and RHS. 1011 KnownOne &= KnownOne2; 1012 KnownZero &= KnownZero2; 1013 if (MaxHighOnes > 0) 1014 KnownOne |= APInt::getHighBitsSet(BitWidth, MaxHighOnes); 1015 if (MaxHighZeros > 0) 1016 KnownZero |= APInt::getHighBitsSet(BitWidth, MaxHighZeros); 1017 break; 1018 } 1019 case Instruction::FPTrunc: 1020 case Instruction::FPExt: 1021 case Instruction::FPToUI: 1022 case Instruction::FPToSI: 1023 case Instruction::SIToFP: 1024 case Instruction::UIToFP: 1025 break; // Can't work with floating point. 1026 case Instruction::PtrToInt: 1027 case Instruction::IntToPtr: 1028 // Fall through and handle them the same as zext/trunc. 1029 LLVM_FALLTHROUGH; 1030 case Instruction::ZExt: 1031 case Instruction::Trunc: { 1032 Type *SrcTy = I->getOperand(0)->getType(); 1033 1034 unsigned SrcBitWidth; 1035 // Note that we handle pointer operands here because of inttoptr/ptrtoint 1036 // which fall through here. 1037 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType()); 1038 1039 assert(SrcBitWidth && "SrcBitWidth can't be zero"); 1040 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth); 1041 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth); 1042 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 1043 KnownZero = KnownZero.zextOrTrunc(BitWidth); 1044 KnownOne = KnownOne.zextOrTrunc(BitWidth); 1045 // Any top bits are known to be zero. 1046 if (BitWidth > SrcBitWidth) 1047 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 1048 break; 1049 } 1050 case Instruction::BitCast: { 1051 Type *SrcTy = I->getOperand(0)->getType(); 1052 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) && 1053 // TODO: For now, not handling conversions like: 1054 // (bitcast i64 %x to <2 x i32>) 1055 !I->getType()->isVectorTy()) { 1056 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 1057 break; 1058 } 1059 break; 1060 } 1061 case Instruction::SExt: { 1062 // Compute the bits in the result that are not present in the input. 1063 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 1064 1065 KnownZero = KnownZero.trunc(SrcBitWidth); 1066 KnownOne = KnownOne.trunc(SrcBitWidth); 1067 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 1068 KnownZero = KnownZero.zext(BitWidth); 1069 KnownOne = KnownOne.zext(BitWidth); 1070 1071 // If the sign bit of the input is known set or clear, then we know the 1072 // top bits of the result. 1073 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero 1074 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 1075 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set 1076 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 1077 break; 1078 } 1079 case Instruction::Shl: { 1080 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 1081 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap(); 1082 auto KZF = [BitWidth, NSW](const APInt &KnownZero, unsigned ShiftAmt) { 1083 APInt KZResult = 1084 (KnownZero << ShiftAmt) | 1085 APInt::getLowBitsSet(BitWidth, ShiftAmt); // Low bits known 0. 1086 // If this shift has "nsw" keyword, then the result is either a poison 1087 // value or has the same sign bit as the first operand. 1088 if (NSW && KnownZero.isNegative()) 1089 KZResult.setBit(BitWidth - 1); 1090 return KZResult; 1091 }; 1092 1093 auto KOF = [BitWidth, NSW](const APInt &KnownOne, unsigned ShiftAmt) { 1094 APInt KOResult = KnownOne << ShiftAmt; 1095 if (NSW && KnownOne.isNegative()) 1096 KOResult.setBit(BitWidth - 1); 1097 return KOResult; 1098 }; 1099 1100 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne, 1101 KnownZero2, KnownOne2, Depth, Q, KZF, 1102 KOF); 1103 break; 1104 } 1105 case Instruction::LShr: { 1106 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 1107 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) { 1108 return APIntOps::lshr(KnownZero, ShiftAmt) | 1109 // High bits known zero. 1110 APInt::getHighBitsSet(BitWidth, ShiftAmt); 1111 }; 1112 1113 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) { 1114 return APIntOps::lshr(KnownOne, ShiftAmt); 1115 }; 1116 1117 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne, 1118 KnownZero2, KnownOne2, Depth, Q, KZF, 1119 KOF); 1120 break; 1121 } 1122 case Instruction::AShr: { 1123 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 1124 auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) { 1125 return APIntOps::ashr(KnownZero, ShiftAmt); 1126 }; 1127 1128 auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) { 1129 return APIntOps::ashr(KnownOne, ShiftAmt); 1130 }; 1131 1132 computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne, 1133 KnownZero2, KnownOne2, Depth, Q, KZF, 1134 KOF); 1135 break; 1136 } 1137 case Instruction::Sub: { 1138 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap(); 1139 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, 1140 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth, 1141 Q); 1142 break; 1143 } 1144 case Instruction::Add: { 1145 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap(); 1146 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, 1147 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth, 1148 Q); 1149 break; 1150 } 1151 case Instruction::SRem: 1152 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 1153 APInt RA = Rem->getValue().abs(); 1154 if (RA.isPowerOf2()) { 1155 APInt LowBits = RA - 1; 1156 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, 1157 Q); 1158 1159 // The low bits of the first operand are unchanged by the srem. 1160 KnownZero = KnownZero2 & LowBits; 1161 KnownOne = KnownOne2 & LowBits; 1162 1163 // If the first operand is non-negative or has all low bits zero, then 1164 // the upper bits are all zero. 1165 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 1166 KnownZero |= ~LowBits; 1167 1168 // If the first operand is negative and not all low bits are zero, then 1169 // the upper bits are all one. 1170 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0)) 1171 KnownOne |= ~LowBits; 1172 1173 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1174 } 1175 } 1176 1177 // The sign bit is the LHS's sign bit, except when the result of the 1178 // remainder is zero. 1179 if (KnownZero.isNonNegative()) { 1180 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0); 1181 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1, 1182 Q); 1183 // If it's known zero, our sign bit is also zero. 1184 if (LHSKnownZero.isNegative()) 1185 KnownZero.setBit(BitWidth - 1); 1186 } 1187 1188 break; 1189 case Instruction::URem: { 1190 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 1191 const APInt &RA = Rem->getValue(); 1192 if (RA.isPowerOf2()) { 1193 APInt LowBits = (RA - 1); 1194 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 1195 KnownZero |= ~LowBits; 1196 KnownOne &= LowBits; 1197 break; 1198 } 1199 } 1200 1201 // Since the result is less than or equal to either operand, any leading 1202 // zero bits in either operand must also exist in the result. 1203 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 1204 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q); 1205 1206 unsigned Leaders = std::max(KnownZero.countLeadingOnes(), 1207 KnownZero2.countLeadingOnes()); 1208 KnownOne.clearAllBits(); 1209 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders); 1210 break; 1211 } 1212 1213 case Instruction::Alloca: { 1214 const AllocaInst *AI = cast<AllocaInst>(I); 1215 unsigned Align = AI->getAlignment(); 1216 if (Align == 0) 1217 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType()); 1218 1219 if (Align > 0) 1220 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align)); 1221 break; 1222 } 1223 case Instruction::GetElementPtr: { 1224 // Analyze all of the subscripts of this getelementptr instruction 1225 // to determine if we can prove known low zero bits. 1226 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0); 1227 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, Depth + 1, 1228 Q); 1229 unsigned TrailZ = LocalKnownZero.countTrailingOnes(); 1230 1231 gep_type_iterator GTI = gep_type_begin(I); 1232 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) { 1233 Value *Index = I->getOperand(i); 1234 if (StructType *STy = GTI.getStructTypeOrNull()) { 1235 // Handle struct member offset arithmetic. 1236 1237 // Handle case when index is vector zeroinitializer 1238 Constant *CIndex = cast<Constant>(Index); 1239 if (CIndex->isZeroValue()) 1240 continue; 1241 1242 if (CIndex->getType()->isVectorTy()) 1243 Index = CIndex->getSplatValue(); 1244 1245 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue(); 1246 const StructLayout *SL = Q.DL.getStructLayout(STy); 1247 uint64_t Offset = SL->getElementOffset(Idx); 1248 TrailZ = std::min<unsigned>(TrailZ, 1249 countTrailingZeros(Offset)); 1250 } else { 1251 // Handle array index arithmetic. 1252 Type *IndexedTy = GTI.getIndexedType(); 1253 if (!IndexedTy->isSized()) { 1254 TrailZ = 0; 1255 break; 1256 } 1257 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits(); 1258 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy); 1259 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0); 1260 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, Depth + 1, Q); 1261 TrailZ = std::min(TrailZ, 1262 unsigned(countTrailingZeros(TypeSize) + 1263 LocalKnownZero.countTrailingOnes())); 1264 } 1265 } 1266 1267 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ); 1268 break; 1269 } 1270 case Instruction::PHI: { 1271 const PHINode *P = cast<PHINode>(I); 1272 // Handle the case of a simple two-predecessor recurrence PHI. 1273 // There's a lot more that could theoretically be done here, but 1274 // this is sufficient to catch some interesting cases. 1275 if (P->getNumIncomingValues() == 2) { 1276 for (unsigned i = 0; i != 2; ++i) { 1277 Value *L = P->getIncomingValue(i); 1278 Value *R = P->getIncomingValue(!i); 1279 Operator *LU = dyn_cast<Operator>(L); 1280 if (!LU) 1281 continue; 1282 unsigned Opcode = LU->getOpcode(); 1283 // Check for operations that have the property that if 1284 // both their operands have low zero bits, the result 1285 // will have low zero bits. 1286 if (Opcode == Instruction::Add || 1287 Opcode == Instruction::Sub || 1288 Opcode == Instruction::And || 1289 Opcode == Instruction::Or || 1290 Opcode == Instruction::Mul) { 1291 Value *LL = LU->getOperand(0); 1292 Value *LR = LU->getOperand(1); 1293 // Find a recurrence. 1294 if (LL == I) 1295 L = LR; 1296 else if (LR == I) 1297 L = LL; 1298 else 1299 break; 1300 // Ok, we have a PHI of the form L op= R. Check for low 1301 // zero bits. 1302 computeKnownBits(R, KnownZero2, KnownOne2, Depth + 1, Q); 1303 1304 // We need to take the minimum number of known bits 1305 APInt KnownZero3(KnownZero), KnownOne3(KnownOne); 1306 computeKnownBits(L, KnownZero3, KnownOne3, Depth + 1, Q); 1307 1308 KnownZero = APInt::getLowBitsSet( 1309 BitWidth, std::min(KnownZero2.countTrailingOnes(), 1310 KnownZero3.countTrailingOnes())); 1311 1312 if (DontImproveNonNegativePhiBits) 1313 break; 1314 1315 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU); 1316 if (OverflowOp && OverflowOp->hasNoSignedWrap()) { 1317 // If initial value of recurrence is nonnegative, and we are adding 1318 // a nonnegative number with nsw, the result can only be nonnegative 1319 // or poison value regardless of the number of times we execute the 1320 // add in phi recurrence. If initial value is negative and we are 1321 // adding a negative number with nsw, the result can only be 1322 // negative or poison value. Similar arguments apply to sub and mul. 1323 // 1324 // (add non-negative, non-negative) --> non-negative 1325 // (add negative, negative) --> negative 1326 if (Opcode == Instruction::Add) { 1327 if (KnownZero2.isNegative() && KnownZero3.isNegative()) 1328 KnownZero.setBit(BitWidth - 1); 1329 else if (KnownOne2.isNegative() && KnownOne3.isNegative()) 1330 KnownOne.setBit(BitWidth - 1); 1331 } 1332 1333 // (sub nsw non-negative, negative) --> non-negative 1334 // (sub nsw negative, non-negative) --> negative 1335 else if (Opcode == Instruction::Sub && LL == I) { 1336 if (KnownZero2.isNegative() && KnownOne3.isNegative()) 1337 KnownZero.setBit(BitWidth - 1); 1338 else if (KnownOne2.isNegative() && KnownZero3.isNegative()) 1339 KnownOne.setBit(BitWidth - 1); 1340 } 1341 1342 // (mul nsw non-negative, non-negative) --> non-negative 1343 else if (Opcode == Instruction::Mul && KnownZero2.isNegative() && 1344 KnownZero3.isNegative()) 1345 KnownZero.setBit(BitWidth - 1); 1346 } 1347 1348 break; 1349 } 1350 } 1351 } 1352 1353 // Unreachable blocks may have zero-operand PHI nodes. 1354 if (P->getNumIncomingValues() == 0) 1355 break; 1356 1357 // Otherwise take the unions of the known bit sets of the operands, 1358 // taking conservative care to avoid excessive recursion. 1359 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) { 1360 // Skip if every incoming value references to ourself. 1361 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue())) 1362 break; 1363 1364 KnownZero = APInt::getAllOnesValue(BitWidth); 1365 KnownOne = APInt::getAllOnesValue(BitWidth); 1366 for (Value *IncValue : P->incoming_values()) { 1367 // Skip direct self references. 1368 if (IncValue == P) continue; 1369 1370 KnownZero2 = APInt(BitWidth, 0); 1371 KnownOne2 = APInt(BitWidth, 0); 1372 // Recurse, but cap the recursion to one level, because we don't 1373 // want to waste time spinning around in loops. 1374 computeKnownBits(IncValue, KnownZero2, KnownOne2, MaxDepth - 1, Q); 1375 KnownZero &= KnownZero2; 1376 KnownOne &= KnownOne2; 1377 // If all bits have been ruled out, there's no need to check 1378 // more operands. 1379 if (!KnownZero && !KnownOne) 1380 break; 1381 } 1382 } 1383 break; 1384 } 1385 case Instruction::Call: 1386 case Instruction::Invoke: 1387 // If range metadata is attached to this call, set known bits from that, 1388 // and then intersect with known bits based on other properties of the 1389 // function. 1390 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range)) 1391 computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne); 1392 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) { 1393 computeKnownBits(RV, KnownZero2, KnownOne2, Depth + 1, Q); 1394 KnownZero |= KnownZero2; 1395 KnownOne |= KnownOne2; 1396 } 1397 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 1398 switch (II->getIntrinsicID()) { 1399 default: break; 1400 case Intrinsic::bswap: 1401 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q); 1402 KnownZero |= KnownZero2.byteSwap(); 1403 KnownOne |= KnownOne2.byteSwap(); 1404 break; 1405 case Intrinsic::ctlz: 1406 case Intrinsic::cttz: { 1407 unsigned LowBits = Log2_32(BitWidth)+1; 1408 // If this call is undefined for 0, the result will be less than 2^n. 1409 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext())) 1410 LowBits -= 1; 1411 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 1412 break; 1413 } 1414 case Intrinsic::ctpop: { 1415 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q); 1416 // We can bound the space the count needs. Also, bits known to be zero 1417 // can't contribute to the population. 1418 unsigned BitsPossiblySet = BitWidth - KnownZero2.countPopulation(); 1419 unsigned LeadingZeros = 1420 APInt(BitWidth, BitsPossiblySet).countLeadingZeros(); 1421 assert(LeadingZeros <= BitWidth); 1422 KnownZero |= APInt::getHighBitsSet(BitWidth, LeadingZeros); 1423 KnownOne &= ~KnownZero; 1424 // TODO: we could bound KnownOne using the lower bound on the number 1425 // of bits which might be set provided by popcnt KnownOne2. 1426 break; 1427 } 1428 case Intrinsic::x86_sse42_crc32_64_64: 1429 KnownZero |= APInt::getHighBitsSet(64, 32); 1430 break; 1431 } 1432 } 1433 break; 1434 case Instruction::ExtractElement: 1435 // Look through extract element. At the moment we keep this simple and skip 1436 // tracking the specific element. But at least we might find information 1437 // valid for all elements of the vector (for example if vector is sign 1438 // extended, shifted, etc). 1439 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 1440 break; 1441 case Instruction::ExtractValue: 1442 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) { 1443 const ExtractValueInst *EVI = cast<ExtractValueInst>(I); 1444 if (EVI->getNumIndices() != 1) break; 1445 if (EVI->getIndices()[0] == 0) { 1446 switch (II->getIntrinsicID()) { 1447 default: break; 1448 case Intrinsic::uadd_with_overflow: 1449 case Intrinsic::sadd_with_overflow: 1450 computeKnownBitsAddSub(true, II->getArgOperand(0), 1451 II->getArgOperand(1), false, KnownZero, 1452 KnownOne, KnownZero2, KnownOne2, Depth, Q); 1453 break; 1454 case Intrinsic::usub_with_overflow: 1455 case Intrinsic::ssub_with_overflow: 1456 computeKnownBitsAddSub(false, II->getArgOperand(0), 1457 II->getArgOperand(1), false, KnownZero, 1458 KnownOne, KnownZero2, KnownOne2, Depth, Q); 1459 break; 1460 case Intrinsic::umul_with_overflow: 1461 case Intrinsic::smul_with_overflow: 1462 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false, 1463 KnownZero, KnownOne, KnownZero2, KnownOne2, Depth, 1464 Q); 1465 break; 1466 } 1467 } 1468 } 1469 } 1470 } 1471 1472 /// Determine which bits of V are known to be either zero or one and return 1473 /// them in the KnownZero/KnownOne bit sets. 1474 /// 1475 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that 1476 /// we cannot optimize based on the assumption that it is zero without changing 1477 /// it to be an explicit zero. If we don't change it to zero, other code could 1478 /// optimized based on the contradictory assumption that it is non-zero. 1479 /// Because instcombine aggressively folds operations with undef args anyway, 1480 /// this won't lose us code quality. 1481 /// 1482 /// This function is defined on values with integer type, values with pointer 1483 /// type, and vectors of integers. In the case 1484 /// where V is a vector, known zero, and known one values are the 1485 /// same width as the vector element, and the bit is set only if it is true 1486 /// for all of the elements in the vector. 1487 void computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne, 1488 unsigned Depth, const Query &Q) { 1489 assert(V && "No Value?"); 1490 assert(Depth <= MaxDepth && "Limit Search Depth"); 1491 unsigned BitWidth = KnownZero.getBitWidth(); 1492 1493 assert((V->getType()->isIntOrIntVectorTy() || 1494 V->getType()->getScalarType()->isPointerTy()) && 1495 "Not integer or pointer type!"); 1496 assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) && 1497 (!V->getType()->isIntOrIntVectorTy() || 1498 V->getType()->getScalarSizeInBits() == BitWidth) && 1499 KnownZero.getBitWidth() == BitWidth && 1500 KnownOne.getBitWidth() == BitWidth && 1501 "V, KnownOne and KnownZero should have same BitWidth"); 1502 1503 const APInt *C; 1504 if (match(V, m_APInt(C))) { 1505 // We know all of the bits for a scalar constant or a splat vector constant! 1506 KnownOne = *C; 1507 KnownZero = ~KnownOne; 1508 return; 1509 } 1510 // Null and aggregate-zero are all-zeros. 1511 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) { 1512 KnownOne.clearAllBits(); 1513 KnownZero = APInt::getAllOnesValue(BitWidth); 1514 return; 1515 } 1516 // Handle a constant vector by taking the intersection of the known bits of 1517 // each element. 1518 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) { 1519 // We know that CDS must be a vector of integers. Take the intersection of 1520 // each element. 1521 KnownZero.setAllBits(); KnownOne.setAllBits(); 1522 APInt Elt(KnownZero.getBitWidth(), 0); 1523 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1524 Elt = CDS->getElementAsInteger(i); 1525 KnownZero &= ~Elt; 1526 KnownOne &= Elt; 1527 } 1528 return; 1529 } 1530 1531 if (const auto *CV = dyn_cast<ConstantVector>(V)) { 1532 // We know that CV must be a vector of integers. Take the intersection of 1533 // each element. 1534 KnownZero.setAllBits(); KnownOne.setAllBits(); 1535 APInt Elt(KnownZero.getBitWidth(), 0); 1536 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 1537 Constant *Element = CV->getAggregateElement(i); 1538 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element); 1539 if (!ElementCI) { 1540 KnownZero.clearAllBits(); 1541 KnownOne.clearAllBits(); 1542 return; 1543 } 1544 Elt = ElementCI->getValue(); 1545 KnownZero &= ~Elt; 1546 KnownOne &= Elt; 1547 } 1548 return; 1549 } 1550 1551 // Start out not knowing anything. 1552 KnownZero.clearAllBits(); KnownOne.clearAllBits(); 1553 1554 // We can't imply anything about undefs. 1555 if (isa<UndefValue>(V)) 1556 return; 1557 1558 // There's no point in looking through other users of ConstantData for 1559 // assumptions. Confirm that we've handled them all. 1560 assert(!isa<ConstantData>(V) && "Unhandled constant data!"); 1561 1562 // Limit search depth. 1563 // All recursive calls that increase depth must come after this. 1564 if (Depth == MaxDepth) 1565 return; 1566 1567 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has 1568 // the bits of its aliasee. 1569 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 1570 if (!GA->isInterposable()) 1571 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, Depth + 1, Q); 1572 return; 1573 } 1574 1575 if (const Operator *I = dyn_cast<Operator>(V)) 1576 computeKnownBitsFromOperator(I, KnownZero, KnownOne, Depth, Q); 1577 1578 // Aligned pointers have trailing zeros - refine KnownZero set 1579 if (V->getType()->isPointerTy()) { 1580 unsigned Align = V->getPointerAlignment(Q.DL); 1581 if (Align) 1582 KnownZero |= APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align)); 1583 } 1584 1585 // computeKnownBitsFromAssume strictly refines KnownZero and 1586 // KnownOne. Therefore, we run them after computeKnownBitsFromOperator. 1587 1588 // Check whether a nearby assume intrinsic can determine some known bits. 1589 computeKnownBitsFromAssume(V, KnownZero, KnownOne, Depth, Q); 1590 1591 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1592 } 1593 1594 /// Determine whether the sign bit is known to be zero or one. 1595 /// Convenience wrapper around computeKnownBits. 1596 void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne, 1597 unsigned Depth, const Query &Q) { 1598 unsigned BitWidth = getBitWidth(V->getType(), Q.DL); 1599 if (!BitWidth) { 1600 KnownZero = false; 1601 KnownOne = false; 1602 return; 1603 } 1604 APInt ZeroBits(BitWidth, 0); 1605 APInt OneBits(BitWidth, 0); 1606 computeKnownBits(V, ZeroBits, OneBits, Depth, Q); 1607 KnownOne = OneBits[BitWidth - 1]; 1608 KnownZero = ZeroBits[BitWidth - 1]; 1609 } 1610 1611 /// Return true if the given value is known to have exactly one 1612 /// bit set when defined. For vectors return true if every element is known to 1613 /// be a power of two when defined. Supports values with integer or pointer 1614 /// types and vectors of integers. 1615 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth, 1616 const Query &Q) { 1617 if (const Constant *C = dyn_cast<Constant>(V)) { 1618 if (C->isNullValue()) 1619 return OrZero; 1620 1621 const APInt *ConstIntOrConstSplatInt; 1622 if (match(C, m_APInt(ConstIntOrConstSplatInt))) 1623 return ConstIntOrConstSplatInt->isPowerOf2(); 1624 } 1625 1626 // 1 << X is clearly a power of two if the one is not shifted off the end. If 1627 // it is shifted off the end then the result is undefined. 1628 if (match(V, m_Shl(m_One(), m_Value()))) 1629 return true; 1630 1631 // (signbit) >>l X is clearly a power of two if the one is not shifted off the 1632 // bottom. If it is shifted off the bottom then the result is undefined. 1633 if (match(V, m_LShr(m_SignBit(), m_Value()))) 1634 return true; 1635 1636 // The remaining tests are all recursive, so bail out if we hit the limit. 1637 if (Depth++ == MaxDepth) 1638 return false; 1639 1640 Value *X = nullptr, *Y = nullptr; 1641 // A shift left or a logical shift right of a power of two is a power of two 1642 // or zero. 1643 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) || 1644 match(V, m_LShr(m_Value(X), m_Value())))) 1645 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q); 1646 1647 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V)) 1648 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q); 1649 1650 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) 1651 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) && 1652 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q); 1653 1654 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) { 1655 // A power of two and'd with anything is a power of two or zero. 1656 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) || 1657 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q)) 1658 return true; 1659 // X & (-X) is always a power of two or zero. 1660 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X)))) 1661 return true; 1662 return false; 1663 } 1664 1665 // Adding a power-of-two or zero to the same power-of-two or zero yields 1666 // either the original power-of-two, a larger power-of-two or zero. 1667 if (match(V, m_Add(m_Value(X), m_Value(Y)))) { 1668 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V); 1669 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) { 1670 if (match(X, m_And(m_Specific(Y), m_Value())) || 1671 match(X, m_And(m_Value(), m_Specific(Y)))) 1672 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q)) 1673 return true; 1674 if (match(Y, m_And(m_Specific(X), m_Value())) || 1675 match(Y, m_And(m_Value(), m_Specific(X)))) 1676 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q)) 1677 return true; 1678 1679 unsigned BitWidth = V->getType()->getScalarSizeInBits(); 1680 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0); 1681 computeKnownBits(X, LHSZeroBits, LHSOneBits, Depth, Q); 1682 1683 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0); 1684 computeKnownBits(Y, RHSZeroBits, RHSOneBits, Depth, Q); 1685 // If i8 V is a power of two or zero: 1686 // ZeroBits: 1 1 1 0 1 1 1 1 1687 // ~ZeroBits: 0 0 0 1 0 0 0 0 1688 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2()) 1689 // If OrZero isn't set, we cannot give back a zero result. 1690 // Make sure either the LHS or RHS has a bit set. 1691 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue()) 1692 return true; 1693 } 1694 } 1695 1696 // An exact divide or right shift can only shift off zero bits, so the result 1697 // is a power of two only if the first operand is a power of two and not 1698 // copying a sign bit (sdiv int_min, 2). 1699 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) || 1700 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) { 1701 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero, 1702 Depth, Q); 1703 } 1704 1705 return false; 1706 } 1707 1708 /// \brief Test whether a GEP's result is known to be non-null. 1709 /// 1710 /// Uses properties inherent in a GEP to try to determine whether it is known 1711 /// to be non-null. 1712 /// 1713 /// Currently this routine does not support vector GEPs. 1714 static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth, 1715 const Query &Q) { 1716 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0) 1717 return false; 1718 1719 // FIXME: Support vector-GEPs. 1720 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP"); 1721 1722 // If the base pointer is non-null, we cannot walk to a null address with an 1723 // inbounds GEP in address space zero. 1724 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q)) 1725 return true; 1726 1727 // Walk the GEP operands and see if any operand introduces a non-zero offset. 1728 // If so, then the GEP cannot produce a null pointer, as doing so would 1729 // inherently violate the inbounds contract within address space zero. 1730 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 1731 GTI != GTE; ++GTI) { 1732 // Struct types are easy -- they must always be indexed by a constant. 1733 if (StructType *STy = GTI.getStructTypeOrNull()) { 1734 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand()); 1735 unsigned ElementIdx = OpC->getZExtValue(); 1736 const StructLayout *SL = Q.DL.getStructLayout(STy); 1737 uint64_t ElementOffset = SL->getElementOffset(ElementIdx); 1738 if (ElementOffset > 0) 1739 return true; 1740 continue; 1741 } 1742 1743 // If we have a zero-sized type, the index doesn't matter. Keep looping. 1744 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0) 1745 continue; 1746 1747 // Fast path the constant operand case both for efficiency and so we don't 1748 // increment Depth when just zipping down an all-constant GEP. 1749 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) { 1750 if (!OpC->isZero()) 1751 return true; 1752 continue; 1753 } 1754 1755 // We post-increment Depth here because while isKnownNonZero increments it 1756 // as well, when we pop back up that increment won't persist. We don't want 1757 // to recurse 10k times just because we have 10k GEP operands. We don't 1758 // bail completely out because we want to handle constant GEPs regardless 1759 // of depth. 1760 if (Depth++ >= MaxDepth) 1761 continue; 1762 1763 if (isKnownNonZero(GTI.getOperand(), Depth, Q)) 1764 return true; 1765 } 1766 1767 return false; 1768 } 1769 1770 /// Does the 'Range' metadata (which must be a valid MD_range operand list) 1771 /// ensure that the value it's attached to is never Value? 'RangeType' is 1772 /// is the type of the value described by the range. 1773 static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) { 1774 const unsigned NumRanges = Ranges->getNumOperands() / 2; 1775 assert(NumRanges >= 1); 1776 for (unsigned i = 0; i < NumRanges; ++i) { 1777 ConstantInt *Lower = 1778 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0)); 1779 ConstantInt *Upper = 1780 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1)); 1781 ConstantRange Range(Lower->getValue(), Upper->getValue()); 1782 if (Range.contains(Value)) 1783 return false; 1784 } 1785 return true; 1786 } 1787 1788 /// Return true if the given value is known to be non-zero when defined. 1789 /// For vectors return true if every element is known to be non-zero when 1790 /// defined. Supports values with integer or pointer type and vectors of 1791 /// integers. 1792 bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) { 1793 if (auto *C = dyn_cast<Constant>(V)) { 1794 if (C->isNullValue()) 1795 return false; 1796 if (isa<ConstantInt>(C)) 1797 // Must be non-zero due to null test above. 1798 return true; 1799 1800 // For constant vectors, check that all elements are undefined or known 1801 // non-zero to determine that the whole vector is known non-zero. 1802 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) { 1803 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) { 1804 Constant *Elt = C->getAggregateElement(i); 1805 if (!Elt || Elt->isNullValue()) 1806 return false; 1807 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt)) 1808 return false; 1809 } 1810 return true; 1811 } 1812 1813 return false; 1814 } 1815 1816 if (auto *I = dyn_cast<Instruction>(V)) { 1817 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) { 1818 // If the possible ranges don't contain zero, then the value is 1819 // definitely non-zero. 1820 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) { 1821 const APInt ZeroValue(Ty->getBitWidth(), 0); 1822 if (rangeMetadataExcludesValue(Ranges, ZeroValue)) 1823 return true; 1824 } 1825 } 1826 } 1827 1828 // The remaining tests are all recursive, so bail out if we hit the limit. 1829 if (Depth++ >= MaxDepth) 1830 return false; 1831 1832 // Check for pointer simplifications. 1833 if (V->getType()->isPointerTy()) { 1834 if (isKnownNonNull(V)) 1835 return true; 1836 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) 1837 if (isGEPKnownNonNull(GEP, Depth, Q)) 1838 return true; 1839 } 1840 1841 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL); 1842 1843 // X | Y != 0 if X != 0 or Y != 0. 1844 Value *X = nullptr, *Y = nullptr; 1845 if (match(V, m_Or(m_Value(X), m_Value(Y)))) 1846 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q); 1847 1848 // ext X != 0 if X != 0. 1849 if (isa<SExtInst>(V) || isa<ZExtInst>(V)) 1850 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q); 1851 1852 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined 1853 // if the lowest bit is shifted off the end. 1854 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) { 1855 // shl nuw can't remove any non-zero bits. 1856 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V); 1857 if (BO->hasNoUnsignedWrap()) 1858 return isKnownNonZero(X, Depth, Q); 1859 1860 APInt KnownZero(BitWidth, 0); 1861 APInt KnownOne(BitWidth, 0); 1862 computeKnownBits(X, KnownZero, KnownOne, Depth, Q); 1863 if (KnownOne[0]) 1864 return true; 1865 } 1866 // shr X, Y != 0 if X is negative. Note that the value of the shift is not 1867 // defined if the sign bit is shifted off the end. 1868 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) { 1869 // shr exact can only shift out zero bits. 1870 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V); 1871 if (BO->isExact()) 1872 return isKnownNonZero(X, Depth, Q); 1873 1874 bool XKnownNonNegative, XKnownNegative; 1875 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q); 1876 if (XKnownNegative) 1877 return true; 1878 1879 // If the shifter operand is a constant, and all of the bits shifted 1880 // out are known to be zero, and X is known non-zero then at least one 1881 // non-zero bit must remain. 1882 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) { 1883 APInt KnownZero(BitWidth, 0); 1884 APInt KnownOne(BitWidth, 0); 1885 computeKnownBits(X, KnownZero, KnownOne, Depth, Q); 1886 1887 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1); 1888 // Is there a known one in the portion not shifted out? 1889 if (KnownOne.countLeadingZeros() < BitWidth - ShiftVal) 1890 return true; 1891 // Are all the bits to be shifted out known zero? 1892 if (KnownZero.countTrailingOnes() >= ShiftVal) 1893 return isKnownNonZero(X, Depth, Q); 1894 } 1895 } 1896 // div exact can only produce a zero if the dividend is zero. 1897 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) { 1898 return isKnownNonZero(X, Depth, Q); 1899 } 1900 // X + Y. 1901 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) { 1902 bool XKnownNonNegative, XKnownNegative; 1903 bool YKnownNonNegative, YKnownNegative; 1904 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q); 1905 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Depth, Q); 1906 1907 // If X and Y are both non-negative (as signed values) then their sum is not 1908 // zero unless both X and Y are zero. 1909 if (XKnownNonNegative && YKnownNonNegative) 1910 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q)) 1911 return true; 1912 1913 // If X and Y are both negative (as signed values) then their sum is not 1914 // zero unless both X and Y equal INT_MIN. 1915 if (BitWidth && XKnownNegative && YKnownNegative) { 1916 APInt KnownZero(BitWidth, 0); 1917 APInt KnownOne(BitWidth, 0); 1918 APInt Mask = APInt::getSignedMaxValue(BitWidth); 1919 // The sign bit of X is set. If some other bit is set then X is not equal 1920 // to INT_MIN. 1921 computeKnownBits(X, KnownZero, KnownOne, Depth, Q); 1922 if ((KnownOne & Mask) != 0) 1923 return true; 1924 // The sign bit of Y is set. If some other bit is set then Y is not equal 1925 // to INT_MIN. 1926 computeKnownBits(Y, KnownZero, KnownOne, Depth, Q); 1927 if ((KnownOne & Mask) != 0) 1928 return true; 1929 } 1930 1931 // The sum of a non-negative number and a power of two is not zero. 1932 if (XKnownNonNegative && 1933 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q)) 1934 return true; 1935 if (YKnownNonNegative && 1936 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q)) 1937 return true; 1938 } 1939 // X * Y. 1940 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) { 1941 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V); 1942 // If X and Y are non-zero then so is X * Y as long as the multiplication 1943 // does not overflow. 1944 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) && 1945 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q)) 1946 return true; 1947 } 1948 // (C ? X : Y) != 0 if X != 0 and Y != 0. 1949 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 1950 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) && 1951 isKnownNonZero(SI->getFalseValue(), Depth, Q)) 1952 return true; 1953 } 1954 // PHI 1955 else if (const PHINode *PN = dyn_cast<PHINode>(V)) { 1956 // Try and detect a recurrence that monotonically increases from a 1957 // starting value, as these are common as induction variables. 1958 if (PN->getNumIncomingValues() == 2) { 1959 Value *Start = PN->getIncomingValue(0); 1960 Value *Induction = PN->getIncomingValue(1); 1961 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start)) 1962 std::swap(Start, Induction); 1963 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) { 1964 if (!C->isZero() && !C->isNegative()) { 1965 ConstantInt *X; 1966 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) || 1967 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) && 1968 !X->isNegative()) 1969 return true; 1970 } 1971 } 1972 } 1973 // Check if all incoming values are non-zero constant. 1974 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) { 1975 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue(); 1976 }); 1977 if (AllNonZeroConstants) 1978 return true; 1979 } 1980 1981 if (!BitWidth) return false; 1982 APInt KnownZero(BitWidth, 0); 1983 APInt KnownOne(BitWidth, 0); 1984 computeKnownBits(V, KnownZero, KnownOne, Depth, Q); 1985 return KnownOne != 0; 1986 } 1987 1988 /// Return true if V2 == V1 + X, where X is known non-zero. 1989 static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) { 1990 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1); 1991 if (!BO || BO->getOpcode() != Instruction::Add) 1992 return false; 1993 Value *Op = nullptr; 1994 if (V2 == BO->getOperand(0)) 1995 Op = BO->getOperand(1); 1996 else if (V2 == BO->getOperand(1)) 1997 Op = BO->getOperand(0); 1998 else 1999 return false; 2000 return isKnownNonZero(Op, 0, Q); 2001 } 2002 2003 /// Return true if it is known that V1 != V2. 2004 static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) { 2005 if (V1->getType()->isVectorTy() || V1 == V2) 2006 return false; 2007 if (V1->getType() != V2->getType()) 2008 // We can't look through casts yet. 2009 return false; 2010 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q)) 2011 return true; 2012 2013 if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) { 2014 // Are any known bits in V1 contradictory to known bits in V2? If V1 2015 // has a known zero where V2 has a known one, they must not be equal. 2016 auto BitWidth = Ty->getBitWidth(); 2017 APInt KnownZero1(BitWidth, 0); 2018 APInt KnownOne1(BitWidth, 0); 2019 computeKnownBits(V1, KnownZero1, KnownOne1, 0, Q); 2020 APInt KnownZero2(BitWidth, 0); 2021 APInt KnownOne2(BitWidth, 0); 2022 computeKnownBits(V2, KnownZero2, KnownOne2, 0, Q); 2023 2024 auto OppositeBits = (KnownZero1 & KnownOne2) | (KnownZero2 & KnownOne1); 2025 if (OppositeBits.getBoolValue()) 2026 return true; 2027 } 2028 return false; 2029 } 2030 2031 /// Return true if 'V & Mask' is known to be zero. We use this predicate to 2032 /// simplify operations downstream. Mask is known to be zero for bits that V 2033 /// cannot have. 2034 /// 2035 /// This function is defined on values with integer type, values with pointer 2036 /// type, and vectors of integers. In the case 2037 /// where V is a vector, the mask, known zero, and known one values are the 2038 /// same width as the vector element, and the bit is set only if it is true 2039 /// for all of the elements in the vector. 2040 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth, 2041 const Query &Q) { 2042 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0); 2043 computeKnownBits(V, KnownZero, KnownOne, Depth, Q); 2044 return (KnownZero & Mask) == Mask; 2045 } 2046 2047 /// For vector constants, loop over the elements and find the constant with the 2048 /// minimum number of sign bits. Return 0 if the value is not a vector constant 2049 /// or if any element was not analyzed; otherwise, return the count for the 2050 /// element with the minimum number of sign bits. 2051 static unsigned computeNumSignBitsVectorConstant(const Value *V, 2052 unsigned TyBits) { 2053 const auto *CV = dyn_cast<Constant>(V); 2054 if (!CV || !CV->getType()->isVectorTy()) 2055 return 0; 2056 2057 unsigned MinSignBits = TyBits; 2058 unsigned NumElts = CV->getType()->getVectorNumElements(); 2059 for (unsigned i = 0; i != NumElts; ++i) { 2060 // If we find a non-ConstantInt, bail out. 2061 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i)); 2062 if (!Elt) 2063 return 0; 2064 2065 // If the sign bit is 1, flip the bits, so we always count leading zeros. 2066 APInt EltVal = Elt->getValue(); 2067 if (EltVal.isNegative()) 2068 EltVal = ~EltVal; 2069 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros()); 2070 } 2071 2072 return MinSignBits; 2073 } 2074 2075 /// Return the number of times the sign bit of the register is replicated into 2076 /// the other bits. We know that at least 1 bit is always equal to the sign bit 2077 /// (itself), but other cases can give us information. For example, immediately 2078 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each 2079 /// other, so we return 3. For vectors, return the number of sign bits for the 2080 /// vector element with the mininum number of known sign bits. 2081 unsigned ComputeNumSignBits(const Value *V, unsigned Depth, const Query &Q) { 2082 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType()); 2083 unsigned Tmp, Tmp2; 2084 unsigned FirstAnswer = 1; 2085 2086 // Note that ConstantInt is handled by the general computeKnownBits case 2087 // below. 2088 2089 if (Depth == MaxDepth) 2090 return 1; // Limit search depth. 2091 2092 const Operator *U = dyn_cast<Operator>(V); 2093 switch (Operator::getOpcode(V)) { 2094 default: break; 2095 case Instruction::SExt: 2096 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits(); 2097 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp; 2098 2099 case Instruction::SDiv: { 2100 const APInt *Denominator; 2101 // sdiv X, C -> adds log(C) sign bits. 2102 if (match(U->getOperand(1), m_APInt(Denominator))) { 2103 2104 // Ignore non-positive denominator. 2105 if (!Denominator->isStrictlyPositive()) 2106 break; 2107 2108 // Calculate the incoming numerator bits. 2109 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2110 2111 // Add floor(log(C)) bits to the numerator bits. 2112 return std::min(TyBits, NumBits + Denominator->logBase2()); 2113 } 2114 break; 2115 } 2116 2117 case Instruction::SRem: { 2118 const APInt *Denominator; 2119 // srem X, C -> we know that the result is within [-C+1,C) when C is a 2120 // positive constant. This let us put a lower bound on the number of sign 2121 // bits. 2122 if (match(U->getOperand(1), m_APInt(Denominator))) { 2123 2124 // Ignore non-positive denominator. 2125 if (!Denominator->isStrictlyPositive()) 2126 break; 2127 2128 // Calculate the incoming numerator bits. SRem by a positive constant 2129 // can't lower the number of sign bits. 2130 unsigned NumrBits = 2131 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2132 2133 // Calculate the leading sign bit constraints by examining the 2134 // denominator. Given that the denominator is positive, there are two 2135 // cases: 2136 // 2137 // 1. the numerator is positive. The result range is [0,C) and [0,C) u< 2138 // (1 << ceilLogBase2(C)). 2139 // 2140 // 2. the numerator is negative. Then the result range is (-C,0] and 2141 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)). 2142 // 2143 // Thus a lower bound on the number of sign bits is `TyBits - 2144 // ceilLogBase2(C)`. 2145 2146 unsigned ResBits = TyBits - Denominator->ceilLogBase2(); 2147 return std::max(NumrBits, ResBits); 2148 } 2149 break; 2150 } 2151 2152 case Instruction::AShr: { 2153 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2154 // ashr X, C -> adds C sign bits. Vectors too. 2155 const APInt *ShAmt; 2156 if (match(U->getOperand(1), m_APInt(ShAmt))) { 2157 Tmp += ShAmt->getZExtValue(); 2158 if (Tmp > TyBits) Tmp = TyBits; 2159 } 2160 return Tmp; 2161 } 2162 case Instruction::Shl: { 2163 const APInt *ShAmt; 2164 if (match(U->getOperand(1), m_APInt(ShAmt))) { 2165 // shl destroys sign bits. 2166 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2167 Tmp2 = ShAmt->getZExtValue(); 2168 if (Tmp2 >= TyBits || // Bad shift. 2169 Tmp2 >= Tmp) break; // Shifted all sign bits out. 2170 return Tmp - Tmp2; 2171 } 2172 break; 2173 } 2174 case Instruction::And: 2175 case Instruction::Or: 2176 case Instruction::Xor: // NOT is handled here. 2177 // Logical binary ops preserve the number of sign bits at the worst. 2178 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2179 if (Tmp != 1) { 2180 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 2181 FirstAnswer = std::min(Tmp, Tmp2); 2182 // We computed what we know about the sign bits as our first 2183 // answer. Now proceed to the generic code that uses 2184 // computeKnownBits, and pick whichever answer is better. 2185 } 2186 break; 2187 2188 case Instruction::Select: 2189 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 2190 if (Tmp == 1) return 1; // Early out. 2191 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q); 2192 return std::min(Tmp, Tmp2); 2193 2194 case Instruction::Add: 2195 // Add can have at most one carry bit. Thus we know that the output 2196 // is, at worst, one more bit than the inputs. 2197 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2198 if (Tmp == 1) return 1; // Early out. 2199 2200 // Special case decrementing a value (ADD X, -1): 2201 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1))) 2202 if (CRHS->isAllOnesValue()) { 2203 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 2204 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, Depth + 1, Q); 2205 2206 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2207 // sign bits set. 2208 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue()) 2209 return TyBits; 2210 2211 // If we are subtracting one from a positive number, there is no carry 2212 // out of the result. 2213 if (KnownZero.isNegative()) 2214 return Tmp; 2215 } 2216 2217 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 2218 if (Tmp2 == 1) return 1; 2219 return std::min(Tmp, Tmp2)-1; 2220 2221 case Instruction::Sub: 2222 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q); 2223 if (Tmp2 == 1) return 1; 2224 2225 // Handle NEG. 2226 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0))) 2227 if (CLHS->isNullValue()) { 2228 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 2229 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, Depth + 1, Q); 2230 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2231 // sign bits set. 2232 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue()) 2233 return TyBits; 2234 2235 // If the input is known to be positive (the sign bit is known clear), 2236 // the output of the NEG has the same number of sign bits as the input. 2237 if (KnownZero.isNegative()) 2238 return Tmp2; 2239 2240 // Otherwise, we treat this like a SUB. 2241 } 2242 2243 // Sub can have at most one carry bit. Thus we know that the output 2244 // is, at worst, one more bit than the inputs. 2245 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2246 if (Tmp == 1) return 1; // Early out. 2247 return std::min(Tmp, Tmp2)-1; 2248 2249 case Instruction::PHI: { 2250 const PHINode *PN = cast<PHINode>(U); 2251 unsigned NumIncomingValues = PN->getNumIncomingValues(); 2252 // Don't analyze large in-degree PHIs. 2253 if (NumIncomingValues > 4) break; 2254 // Unreachable blocks may have zero-operand PHI nodes. 2255 if (NumIncomingValues == 0) break; 2256 2257 // Take the minimum of all incoming values. This can't infinitely loop 2258 // because of our depth threshold. 2259 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q); 2260 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) { 2261 if (Tmp == 1) return Tmp; 2262 Tmp = std::min( 2263 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q)); 2264 } 2265 return Tmp; 2266 } 2267 2268 case Instruction::Trunc: 2269 // FIXME: it's tricky to do anything useful for this, but it is an important 2270 // case for targets like X86. 2271 break; 2272 2273 case Instruction::ExtractElement: 2274 // Look through extract element. At the moment we keep this simple and skip 2275 // tracking the specific element. But at least we might find information 2276 // valid for all elements of the vector (for example if vector is sign 2277 // extended, shifted, etc). 2278 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q); 2279 } 2280 2281 // Finally, if we can prove that the top bits of the result are 0's or 1's, 2282 // use this information. 2283 2284 // If we can examine all elements of a vector constant successfully, we're 2285 // done (we can't do any better than that). If not, keep trying. 2286 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits)) 2287 return VecSignBits; 2288 2289 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 2290 computeKnownBits(V, KnownZero, KnownOne, Depth, Q); 2291 2292 // If we know that the sign bit is either zero or one, determine the number of 2293 // identical bits in the top of the input value. 2294 if (KnownZero.isNegative()) 2295 return std::max(FirstAnswer, KnownZero.countLeadingOnes()); 2296 2297 if (KnownOne.isNegative()) 2298 return std::max(FirstAnswer, KnownOne.countLeadingOnes()); 2299 2300 // computeKnownBits gave us no extra information about the top bits. 2301 return FirstAnswer; 2302 } 2303 2304 /// This function computes the integer multiple of Base that equals V. 2305 /// If successful, it returns true and returns the multiple in 2306 /// Multiple. If unsuccessful, it returns false. It looks 2307 /// through SExt instructions only if LookThroughSExt is true. 2308 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple, 2309 bool LookThroughSExt, unsigned Depth) { 2310 const unsigned MaxDepth = 6; 2311 2312 assert(V && "No Value?"); 2313 assert(Depth <= MaxDepth && "Limit Search Depth"); 2314 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!"); 2315 2316 Type *T = V->getType(); 2317 2318 ConstantInt *CI = dyn_cast<ConstantInt>(V); 2319 2320 if (Base == 0) 2321 return false; 2322 2323 if (Base == 1) { 2324 Multiple = V; 2325 return true; 2326 } 2327 2328 ConstantExpr *CO = dyn_cast<ConstantExpr>(V); 2329 Constant *BaseVal = ConstantInt::get(T, Base); 2330 if (CO && CO == BaseVal) { 2331 // Multiple is 1. 2332 Multiple = ConstantInt::get(T, 1); 2333 return true; 2334 } 2335 2336 if (CI && CI->getZExtValue() % Base == 0) { 2337 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base); 2338 return true; 2339 } 2340 2341 if (Depth == MaxDepth) return false; // Limit search depth. 2342 2343 Operator *I = dyn_cast<Operator>(V); 2344 if (!I) return false; 2345 2346 switch (I->getOpcode()) { 2347 default: break; 2348 case Instruction::SExt: 2349 if (!LookThroughSExt) return false; 2350 // otherwise fall through to ZExt 2351 case Instruction::ZExt: 2352 return ComputeMultiple(I->getOperand(0), Base, Multiple, 2353 LookThroughSExt, Depth+1); 2354 case Instruction::Shl: 2355 case Instruction::Mul: { 2356 Value *Op0 = I->getOperand(0); 2357 Value *Op1 = I->getOperand(1); 2358 2359 if (I->getOpcode() == Instruction::Shl) { 2360 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1); 2361 if (!Op1CI) return false; 2362 // Turn Op0 << Op1 into Op0 * 2^Op1 2363 APInt Op1Int = Op1CI->getValue(); 2364 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1); 2365 APInt API(Op1Int.getBitWidth(), 0); 2366 API.setBit(BitToSet); 2367 Op1 = ConstantInt::get(V->getContext(), API); 2368 } 2369 2370 Value *Mul0 = nullptr; 2371 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) { 2372 if (Constant *Op1C = dyn_cast<Constant>(Op1)) 2373 if (Constant *MulC = dyn_cast<Constant>(Mul0)) { 2374 if (Op1C->getType()->getPrimitiveSizeInBits() < 2375 MulC->getType()->getPrimitiveSizeInBits()) 2376 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType()); 2377 if (Op1C->getType()->getPrimitiveSizeInBits() > 2378 MulC->getType()->getPrimitiveSizeInBits()) 2379 MulC = ConstantExpr::getZExt(MulC, Op1C->getType()); 2380 2381 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1) 2382 Multiple = ConstantExpr::getMul(MulC, Op1C); 2383 return true; 2384 } 2385 2386 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0)) 2387 if (Mul0CI->getValue() == 1) { 2388 // V == Base * Op1, so return Op1 2389 Multiple = Op1; 2390 return true; 2391 } 2392 } 2393 2394 Value *Mul1 = nullptr; 2395 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) { 2396 if (Constant *Op0C = dyn_cast<Constant>(Op0)) 2397 if (Constant *MulC = dyn_cast<Constant>(Mul1)) { 2398 if (Op0C->getType()->getPrimitiveSizeInBits() < 2399 MulC->getType()->getPrimitiveSizeInBits()) 2400 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType()); 2401 if (Op0C->getType()->getPrimitiveSizeInBits() > 2402 MulC->getType()->getPrimitiveSizeInBits()) 2403 MulC = ConstantExpr::getZExt(MulC, Op0C->getType()); 2404 2405 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0) 2406 Multiple = ConstantExpr::getMul(MulC, Op0C); 2407 return true; 2408 } 2409 2410 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1)) 2411 if (Mul1CI->getValue() == 1) { 2412 // V == Base * Op0, so return Op0 2413 Multiple = Op0; 2414 return true; 2415 } 2416 } 2417 } 2418 } 2419 2420 // We could not determine if V is a multiple of Base. 2421 return false; 2422 } 2423 2424 Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS, 2425 const TargetLibraryInfo *TLI) { 2426 const Function *F = ICS.getCalledFunction(); 2427 if (!F) 2428 return Intrinsic::not_intrinsic; 2429 2430 if (F->isIntrinsic()) 2431 return F->getIntrinsicID(); 2432 2433 if (!TLI) 2434 return Intrinsic::not_intrinsic; 2435 2436 LibFunc::Func Func; 2437 // We're going to make assumptions on the semantics of the functions, check 2438 // that the target knows that it's available in this environment and it does 2439 // not have local linkage. 2440 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func)) 2441 return Intrinsic::not_intrinsic; 2442 2443 if (!ICS.onlyReadsMemory()) 2444 return Intrinsic::not_intrinsic; 2445 2446 // Otherwise check if we have a call to a function that can be turned into a 2447 // vector intrinsic. 2448 switch (Func) { 2449 default: 2450 break; 2451 case LibFunc::sin: 2452 case LibFunc::sinf: 2453 case LibFunc::sinl: 2454 return Intrinsic::sin; 2455 case LibFunc::cos: 2456 case LibFunc::cosf: 2457 case LibFunc::cosl: 2458 return Intrinsic::cos; 2459 case LibFunc::exp: 2460 case LibFunc::expf: 2461 case LibFunc::expl: 2462 return Intrinsic::exp; 2463 case LibFunc::exp2: 2464 case LibFunc::exp2f: 2465 case LibFunc::exp2l: 2466 return Intrinsic::exp2; 2467 case LibFunc::log: 2468 case LibFunc::logf: 2469 case LibFunc::logl: 2470 return Intrinsic::log; 2471 case LibFunc::log10: 2472 case LibFunc::log10f: 2473 case LibFunc::log10l: 2474 return Intrinsic::log10; 2475 case LibFunc::log2: 2476 case LibFunc::log2f: 2477 case LibFunc::log2l: 2478 return Intrinsic::log2; 2479 case LibFunc::fabs: 2480 case LibFunc::fabsf: 2481 case LibFunc::fabsl: 2482 return Intrinsic::fabs; 2483 case LibFunc::fmin: 2484 case LibFunc::fminf: 2485 case LibFunc::fminl: 2486 return Intrinsic::minnum; 2487 case LibFunc::fmax: 2488 case LibFunc::fmaxf: 2489 case LibFunc::fmaxl: 2490 return Intrinsic::maxnum; 2491 case LibFunc::copysign: 2492 case LibFunc::copysignf: 2493 case LibFunc::copysignl: 2494 return Intrinsic::copysign; 2495 case LibFunc::floor: 2496 case LibFunc::floorf: 2497 case LibFunc::floorl: 2498 return Intrinsic::floor; 2499 case LibFunc::ceil: 2500 case LibFunc::ceilf: 2501 case LibFunc::ceill: 2502 return Intrinsic::ceil; 2503 case LibFunc::trunc: 2504 case LibFunc::truncf: 2505 case LibFunc::truncl: 2506 return Intrinsic::trunc; 2507 case LibFunc::rint: 2508 case LibFunc::rintf: 2509 case LibFunc::rintl: 2510 return Intrinsic::rint; 2511 case LibFunc::nearbyint: 2512 case LibFunc::nearbyintf: 2513 case LibFunc::nearbyintl: 2514 return Intrinsic::nearbyint; 2515 case LibFunc::round: 2516 case LibFunc::roundf: 2517 case LibFunc::roundl: 2518 return Intrinsic::round; 2519 case LibFunc::pow: 2520 case LibFunc::powf: 2521 case LibFunc::powl: 2522 return Intrinsic::pow; 2523 case LibFunc::sqrt: 2524 case LibFunc::sqrtf: 2525 case LibFunc::sqrtl: 2526 if (ICS->hasNoNaNs()) 2527 return Intrinsic::sqrt; 2528 return Intrinsic::not_intrinsic; 2529 } 2530 2531 return Intrinsic::not_intrinsic; 2532 } 2533 2534 /// Return true if we can prove that the specified FP value is never equal to 2535 /// -0.0. 2536 /// 2537 /// NOTE: this function will need to be revisited when we support non-default 2538 /// rounding modes! 2539 /// 2540 bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI, 2541 unsigned Depth) { 2542 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) 2543 return !CFP->getValueAPF().isNegZero(); 2544 2545 if (Depth == MaxDepth) 2546 return false; // Limit search depth. 2547 2548 const Operator *I = dyn_cast<Operator>(V); 2549 if (!I) return false; 2550 2551 // Check if the nsz fast-math flag is set 2552 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I)) 2553 if (FPO->hasNoSignedZeros()) 2554 return true; 2555 2556 // (add x, 0.0) is guaranteed to return +0.0, not -0.0. 2557 if (I->getOpcode() == Instruction::FAdd) 2558 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1))) 2559 if (CFP->isNullValue()) 2560 return true; 2561 2562 // sitofp and uitofp turn into +0.0 for zero. 2563 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I)) 2564 return true; 2565 2566 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 2567 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI); 2568 switch (IID) { 2569 default: 2570 break; 2571 // sqrt(-0.0) = -0.0, no other negative results are possible. 2572 case Intrinsic::sqrt: 2573 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1); 2574 // fabs(x) != -0.0 2575 case Intrinsic::fabs: 2576 return true; 2577 } 2578 } 2579 2580 return false; 2581 } 2582 2583 /// If \p SignBitOnly is true, test for a known 0 sign bit rather than a 2584 /// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign 2585 /// bit despite comparing equal. 2586 static bool cannotBeOrderedLessThanZeroImpl(const Value *V, 2587 const TargetLibraryInfo *TLI, 2588 bool SignBitOnly, 2589 unsigned Depth) { 2590 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 2591 return !CFP->getValueAPF().isNegative() || 2592 (!SignBitOnly && CFP->getValueAPF().isZero()); 2593 } 2594 2595 if (Depth == MaxDepth) 2596 return false; // Limit search depth. 2597 2598 const Operator *I = dyn_cast<Operator>(V); 2599 if (!I) 2600 return false; 2601 2602 switch (I->getOpcode()) { 2603 default: 2604 break; 2605 // Unsigned integers are always nonnegative. 2606 case Instruction::UIToFP: 2607 return true; 2608 case Instruction::FMul: 2609 // x*x is always non-negative or a NaN. 2610 if (I->getOperand(0) == I->getOperand(1) && 2611 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs())) 2612 return true; 2613 2614 LLVM_FALLTHROUGH; 2615 case Instruction::FAdd: 2616 case Instruction::FDiv: 2617 case Instruction::FRem: 2618 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 2619 Depth + 1) && 2620 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 2621 Depth + 1); 2622 case Instruction::Select: 2623 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 2624 Depth + 1) && 2625 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly, 2626 Depth + 1); 2627 case Instruction::FPExt: 2628 case Instruction::FPTrunc: 2629 // Widening/narrowing never change sign. 2630 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 2631 Depth + 1); 2632 case Instruction::Call: 2633 Intrinsic::ID IID = getIntrinsicForCallSite(cast<CallInst>(I), TLI); 2634 switch (IID) { 2635 default: 2636 break; 2637 case Intrinsic::maxnum: 2638 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 2639 Depth + 1) || 2640 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 2641 Depth + 1); 2642 case Intrinsic::minnum: 2643 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 2644 Depth + 1) && 2645 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly, 2646 Depth + 1); 2647 case Intrinsic::exp: 2648 case Intrinsic::exp2: 2649 case Intrinsic::fabs: 2650 case Intrinsic::sqrt: 2651 return true; 2652 case Intrinsic::powi: 2653 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) { 2654 // powi(x,n) is non-negative if n is even. 2655 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0) 2656 return true; 2657 } 2658 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly, 2659 Depth + 1); 2660 case Intrinsic::fma: 2661 case Intrinsic::fmuladd: 2662 // x*x+y is non-negative if y is non-negative. 2663 return I->getOperand(0) == I->getOperand(1) && 2664 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) && 2665 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly, 2666 Depth + 1); 2667 } 2668 break; 2669 } 2670 return false; 2671 } 2672 2673 bool llvm::CannotBeOrderedLessThanZero(const Value *V, 2674 const TargetLibraryInfo *TLI) { 2675 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0); 2676 } 2677 2678 bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) { 2679 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0); 2680 } 2681 2682 /// If the specified value can be set by repeating the same byte in memory, 2683 /// return the i8 value that it is represented with. This is 2684 /// true for all i8 values obviously, but is also true for i32 0, i32 -1, 2685 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated 2686 /// byte store (e.g. i16 0x1234), return null. 2687 Value *llvm::isBytewiseValue(Value *V) { 2688 // All byte-wide stores are splatable, even of arbitrary variables. 2689 if (V->getType()->isIntegerTy(8)) return V; 2690 2691 // Handle 'null' ConstantArrayZero etc. 2692 if (Constant *C = dyn_cast<Constant>(V)) 2693 if (C->isNullValue()) 2694 return Constant::getNullValue(Type::getInt8Ty(V->getContext())); 2695 2696 // Constant float and double values can be handled as integer values if the 2697 // corresponding integer value is "byteable". An important case is 0.0. 2698 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 2699 if (CFP->getType()->isFloatTy()) 2700 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext())); 2701 if (CFP->getType()->isDoubleTy()) 2702 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext())); 2703 // Don't handle long double formats, which have strange constraints. 2704 } 2705 2706 // We can handle constant integers that are multiple of 8 bits. 2707 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2708 if (CI->getBitWidth() % 8 == 0) { 2709 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!"); 2710 2711 if (!CI->getValue().isSplat(8)) 2712 return nullptr; 2713 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8)); 2714 } 2715 } 2716 2717 // A ConstantDataArray/Vector is splatable if all its members are equal and 2718 // also splatable. 2719 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) { 2720 Value *Elt = CA->getElementAsConstant(0); 2721 Value *Val = isBytewiseValue(Elt); 2722 if (!Val) 2723 return nullptr; 2724 2725 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I) 2726 if (CA->getElementAsConstant(I) != Elt) 2727 return nullptr; 2728 2729 return Val; 2730 } 2731 2732 // Conceptually, we could handle things like: 2733 // %a = zext i8 %X to i16 2734 // %b = shl i16 %a, 8 2735 // %c = or i16 %a, %b 2736 // but until there is an example that actually needs this, it doesn't seem 2737 // worth worrying about. 2738 return nullptr; 2739 } 2740 2741 2742 // This is the recursive version of BuildSubAggregate. It takes a few different 2743 // arguments. Idxs is the index within the nested struct From that we are 2744 // looking at now (which is of type IndexedType). IdxSkip is the number of 2745 // indices from Idxs that should be left out when inserting into the resulting 2746 // struct. To is the result struct built so far, new insertvalue instructions 2747 // build on that. 2748 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType, 2749 SmallVectorImpl<unsigned> &Idxs, 2750 unsigned IdxSkip, 2751 Instruction *InsertBefore) { 2752 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType); 2753 if (STy) { 2754 // Save the original To argument so we can modify it 2755 Value *OrigTo = To; 2756 // General case, the type indexed by Idxs is a struct 2757 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2758 // Process each struct element recursively 2759 Idxs.push_back(i); 2760 Value *PrevTo = To; 2761 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, 2762 InsertBefore); 2763 Idxs.pop_back(); 2764 if (!To) { 2765 // Couldn't find any inserted value for this index? Cleanup 2766 while (PrevTo != OrigTo) { 2767 InsertValueInst* Del = cast<InsertValueInst>(PrevTo); 2768 PrevTo = Del->getAggregateOperand(); 2769 Del->eraseFromParent(); 2770 } 2771 // Stop processing elements 2772 break; 2773 } 2774 } 2775 // If we successfully found a value for each of our subaggregates 2776 if (To) 2777 return To; 2778 } 2779 // Base case, the type indexed by SourceIdxs is not a struct, or not all of 2780 // the struct's elements had a value that was inserted directly. In the latter 2781 // case, perhaps we can't determine each of the subelements individually, but 2782 // we might be able to find the complete struct somewhere. 2783 2784 // Find the value that is at that particular spot 2785 Value *V = FindInsertedValue(From, Idxs); 2786 2787 if (!V) 2788 return nullptr; 2789 2790 // Insert the value in the new (sub) aggregrate 2791 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip), 2792 "tmp", InsertBefore); 2793 } 2794 2795 // This helper takes a nested struct and extracts a part of it (which is again a 2796 // struct) into a new value. For example, given the struct: 2797 // { a, { b, { c, d }, e } } 2798 // and the indices "1, 1" this returns 2799 // { c, d }. 2800 // 2801 // It does this by inserting an insertvalue for each element in the resulting 2802 // struct, as opposed to just inserting a single struct. This will only work if 2803 // each of the elements of the substruct are known (ie, inserted into From by an 2804 // insertvalue instruction somewhere). 2805 // 2806 // All inserted insertvalue instructions are inserted before InsertBefore 2807 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range, 2808 Instruction *InsertBefore) { 2809 assert(InsertBefore && "Must have someplace to insert!"); 2810 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), 2811 idx_range); 2812 Value *To = UndefValue::get(IndexedType); 2813 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end()); 2814 unsigned IdxSkip = Idxs.size(); 2815 2816 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore); 2817 } 2818 2819 /// Given an aggregrate and an sequence of indices, see if 2820 /// the scalar value indexed is already around as a register, for example if it 2821 /// were inserted directly into the aggregrate. 2822 /// 2823 /// If InsertBefore is not null, this function will duplicate (modified) 2824 /// insertvalues when a part of a nested struct is extracted. 2825 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range, 2826 Instruction *InsertBefore) { 2827 // Nothing to index? Just return V then (this is useful at the end of our 2828 // recursion). 2829 if (idx_range.empty()) 2830 return V; 2831 // We have indices, so V should have an indexable type. 2832 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) && 2833 "Not looking at a struct or array?"); 2834 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) && 2835 "Invalid indices for type?"); 2836 2837 if (Constant *C = dyn_cast<Constant>(V)) { 2838 C = C->getAggregateElement(idx_range[0]); 2839 if (!C) return nullptr; 2840 return FindInsertedValue(C, idx_range.slice(1), InsertBefore); 2841 } 2842 2843 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) { 2844 // Loop the indices for the insertvalue instruction in parallel with the 2845 // requested indices 2846 const unsigned *req_idx = idx_range.begin(); 2847 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); 2848 i != e; ++i, ++req_idx) { 2849 if (req_idx == idx_range.end()) { 2850 // We can't handle this without inserting insertvalues 2851 if (!InsertBefore) 2852 return nullptr; 2853 2854 // The requested index identifies a part of a nested aggregate. Handle 2855 // this specially. For example, 2856 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0 2857 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1 2858 // %C = extractvalue {i32, { i32, i32 } } %B, 1 2859 // This can be changed into 2860 // %A = insertvalue {i32, i32 } undef, i32 10, 0 2861 // %C = insertvalue {i32, i32 } %A, i32 11, 1 2862 // which allows the unused 0,0 element from the nested struct to be 2863 // removed. 2864 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx), 2865 InsertBefore); 2866 } 2867 2868 // This insert value inserts something else than what we are looking for. 2869 // See if the (aggregate) value inserted into has the value we are 2870 // looking for, then. 2871 if (*req_idx != *i) 2872 return FindInsertedValue(I->getAggregateOperand(), idx_range, 2873 InsertBefore); 2874 } 2875 // If we end up here, the indices of the insertvalue match with those 2876 // requested (though possibly only partially). Now we recursively look at 2877 // the inserted value, passing any remaining indices. 2878 return FindInsertedValue(I->getInsertedValueOperand(), 2879 makeArrayRef(req_idx, idx_range.end()), 2880 InsertBefore); 2881 } 2882 2883 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) { 2884 // If we're extracting a value from an aggregate that was extracted from 2885 // something else, we can extract from that something else directly instead. 2886 // However, we will need to chain I's indices with the requested indices. 2887 2888 // Calculate the number of indices required 2889 unsigned size = I->getNumIndices() + idx_range.size(); 2890 // Allocate some space to put the new indices in 2891 SmallVector<unsigned, 5> Idxs; 2892 Idxs.reserve(size); 2893 // Add indices from the extract value instruction 2894 Idxs.append(I->idx_begin(), I->idx_end()); 2895 2896 // Add requested indices 2897 Idxs.append(idx_range.begin(), idx_range.end()); 2898 2899 assert(Idxs.size() == size 2900 && "Number of indices added not correct?"); 2901 2902 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore); 2903 } 2904 // Otherwise, we don't know (such as, extracting from a function return value 2905 // or load instruction) 2906 return nullptr; 2907 } 2908 2909 /// Analyze the specified pointer to see if it can be expressed as a base 2910 /// pointer plus a constant offset. Return the base and offset to the caller. 2911 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, 2912 const DataLayout &DL) { 2913 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType()); 2914 APInt ByteOffset(BitWidth, 0); 2915 2916 // We walk up the defs but use a visited set to handle unreachable code. In 2917 // that case, we stop after accumulating the cycle once (not that it 2918 // matters). 2919 SmallPtrSet<Value *, 16> Visited; 2920 while (Visited.insert(Ptr).second) { 2921 if (Ptr->getType()->isVectorTy()) 2922 break; 2923 2924 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) { 2925 // If one of the values we have visited is an addrspacecast, then 2926 // the pointer type of this GEP may be different from the type 2927 // of the Ptr parameter which was passed to this function. This 2928 // means when we construct GEPOffset, we need to use the size 2929 // of GEP's pointer type rather than the size of the original 2930 // pointer type. 2931 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0); 2932 if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 2933 break; 2934 2935 ByteOffset += GEPOffset.getSExtValue(); 2936 2937 Ptr = GEP->getPointerOperand(); 2938 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast || 2939 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) { 2940 Ptr = cast<Operator>(Ptr)->getOperand(0); 2941 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) { 2942 if (GA->isInterposable()) 2943 break; 2944 Ptr = GA->getAliasee(); 2945 } else { 2946 break; 2947 } 2948 } 2949 Offset = ByteOffset.getSExtValue(); 2950 return Ptr; 2951 } 2952 2953 bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP) { 2954 // Make sure the GEP has exactly three arguments. 2955 if (GEP->getNumOperands() != 3) 2956 return false; 2957 2958 // Make sure the index-ee is a pointer to array of i8. 2959 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType()); 2960 if (!AT || !AT->getElementType()->isIntegerTy(8)) 2961 return false; 2962 2963 // Check to make sure that the first operand of the GEP is an integer and 2964 // has value 0 so that we are sure we're indexing into the initializer. 2965 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1)); 2966 if (!FirstIdx || !FirstIdx->isZero()) 2967 return false; 2968 2969 return true; 2970 } 2971 2972 /// This function computes the length of a null-terminated C string pointed to 2973 /// by V. If successful, it returns true and returns the string in Str. 2974 /// If unsuccessful, it returns false. 2975 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str, 2976 uint64_t Offset, bool TrimAtNul) { 2977 assert(V); 2978 2979 // Look through bitcast instructions and geps. 2980 V = V->stripPointerCasts(); 2981 2982 // If the value is a GEP instruction or constant expression, treat it as an 2983 // offset. 2984 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 2985 // The GEP operator should be based on a pointer to string constant, and is 2986 // indexing into the string constant. 2987 if (!isGEPBasedOnPointerToString(GEP)) 2988 return false; 2989 2990 // If the second index isn't a ConstantInt, then this is a variable index 2991 // into the array. If this occurs, we can't say anything meaningful about 2992 // the string. 2993 uint64_t StartIdx = 0; 2994 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2))) 2995 StartIdx = CI->getZExtValue(); 2996 else 2997 return false; 2998 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset, 2999 TrimAtNul); 3000 } 3001 3002 // The GEP instruction, constant or instruction, must reference a global 3003 // variable that is a constant and is initialized. The referenced constant 3004 // initializer is the array that we'll use for optimization. 3005 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V); 3006 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer()) 3007 return false; 3008 3009 // Handle the all-zeros case. 3010 if (GV->getInitializer()->isNullValue()) { 3011 // This is a degenerate case. The initializer is constant zero so the 3012 // length of the string must be zero. 3013 Str = ""; 3014 return true; 3015 } 3016 3017 // This must be a ConstantDataArray. 3018 const auto *Array = dyn_cast<ConstantDataArray>(GV->getInitializer()); 3019 if (!Array || !Array->isString()) 3020 return false; 3021 3022 // Get the number of elements in the array. 3023 uint64_t NumElts = Array->getType()->getArrayNumElements(); 3024 3025 // Start out with the entire array in the StringRef. 3026 Str = Array->getAsString(); 3027 3028 if (Offset > NumElts) 3029 return false; 3030 3031 // Skip over 'offset' bytes. 3032 Str = Str.substr(Offset); 3033 3034 if (TrimAtNul) { 3035 // Trim off the \0 and anything after it. If the array is not nul 3036 // terminated, we just return the whole end of string. The client may know 3037 // some other way that the string is length-bound. 3038 Str = Str.substr(0, Str.find('\0')); 3039 } 3040 return true; 3041 } 3042 3043 // These next two are very similar to the above, but also look through PHI 3044 // nodes. 3045 // TODO: See if we can integrate these two together. 3046 3047 /// If we can compute the length of the string pointed to by 3048 /// the specified pointer, return 'len+1'. If we can't, return 0. 3049 static uint64_t GetStringLengthH(const Value *V, 3050 SmallPtrSetImpl<const PHINode*> &PHIs) { 3051 // Look through noop bitcast instructions. 3052 V = V->stripPointerCasts(); 3053 3054 // If this is a PHI node, there are two cases: either we have already seen it 3055 // or we haven't. 3056 if (const PHINode *PN = dyn_cast<PHINode>(V)) { 3057 if (!PHIs.insert(PN).second) 3058 return ~0ULL; // already in the set. 3059 3060 // If it was new, see if all the input strings are the same length. 3061 uint64_t LenSoFar = ~0ULL; 3062 for (Value *IncValue : PN->incoming_values()) { 3063 uint64_t Len = GetStringLengthH(IncValue, PHIs); 3064 if (Len == 0) return 0; // Unknown length -> unknown. 3065 3066 if (Len == ~0ULL) continue; 3067 3068 if (Len != LenSoFar && LenSoFar != ~0ULL) 3069 return 0; // Disagree -> unknown. 3070 LenSoFar = Len; 3071 } 3072 3073 // Success, all agree. 3074 return LenSoFar; 3075 } 3076 3077 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y) 3078 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 3079 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs); 3080 if (Len1 == 0) return 0; 3081 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs); 3082 if (Len2 == 0) return 0; 3083 if (Len1 == ~0ULL) return Len2; 3084 if (Len2 == ~0ULL) return Len1; 3085 if (Len1 != Len2) return 0; 3086 return Len1; 3087 } 3088 3089 // Otherwise, see if we can read the string. 3090 StringRef StrData; 3091 if (!getConstantStringInfo(V, StrData)) 3092 return 0; 3093 3094 return StrData.size()+1; 3095 } 3096 3097 /// If we can compute the length of the string pointed to by 3098 /// the specified pointer, return 'len+1'. If we can't, return 0. 3099 uint64_t llvm::GetStringLength(const Value *V) { 3100 if (!V->getType()->isPointerTy()) return 0; 3101 3102 SmallPtrSet<const PHINode*, 32> PHIs; 3103 uint64_t Len = GetStringLengthH(V, PHIs); 3104 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return 3105 // an empty string as a length. 3106 return Len == ~0ULL ? 1 : Len; 3107 } 3108 3109 /// \brief \p PN defines a loop-variant pointer to an object. Check if the 3110 /// previous iteration of the loop was referring to the same object as \p PN. 3111 static bool isSameUnderlyingObjectInLoop(const PHINode *PN, 3112 const LoopInfo *LI) { 3113 // Find the loop-defined value. 3114 Loop *L = LI->getLoopFor(PN->getParent()); 3115 if (PN->getNumIncomingValues() != 2) 3116 return true; 3117 3118 // Find the value from previous iteration. 3119 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0)); 3120 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L) 3121 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1)); 3122 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L) 3123 return true; 3124 3125 // If a new pointer is loaded in the loop, the pointer references a different 3126 // object in every iteration. E.g.: 3127 // for (i) 3128 // int *p = a[i]; 3129 // ... 3130 if (auto *Load = dyn_cast<LoadInst>(PrevValue)) 3131 if (!L->isLoopInvariant(Load->getPointerOperand())) 3132 return false; 3133 return true; 3134 } 3135 3136 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL, 3137 unsigned MaxLookup) { 3138 if (!V->getType()->isPointerTy()) 3139 return V; 3140 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) { 3141 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 3142 V = GEP->getPointerOperand(); 3143 } else if (Operator::getOpcode(V) == Instruction::BitCast || 3144 Operator::getOpcode(V) == Instruction::AddrSpaceCast) { 3145 V = cast<Operator>(V)->getOperand(0); 3146 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 3147 if (GA->isInterposable()) 3148 return V; 3149 V = GA->getAliasee(); 3150 } else { 3151 if (auto CS = CallSite(V)) 3152 if (Value *RV = CS.getReturnedArgOperand()) { 3153 V = RV; 3154 continue; 3155 } 3156 3157 // See if InstructionSimplify knows any relevant tricks. 3158 if (Instruction *I = dyn_cast<Instruction>(V)) 3159 // TODO: Acquire a DominatorTree and AssumptionCache and use them. 3160 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) { 3161 V = Simplified; 3162 continue; 3163 } 3164 3165 return V; 3166 } 3167 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 3168 } 3169 return V; 3170 } 3171 3172 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects, 3173 const DataLayout &DL, LoopInfo *LI, 3174 unsigned MaxLookup) { 3175 SmallPtrSet<Value *, 4> Visited; 3176 SmallVector<Value *, 4> Worklist; 3177 Worklist.push_back(V); 3178 do { 3179 Value *P = Worklist.pop_back_val(); 3180 P = GetUnderlyingObject(P, DL, MaxLookup); 3181 3182 if (!Visited.insert(P).second) 3183 continue; 3184 3185 if (SelectInst *SI = dyn_cast<SelectInst>(P)) { 3186 Worklist.push_back(SI->getTrueValue()); 3187 Worklist.push_back(SI->getFalseValue()); 3188 continue; 3189 } 3190 3191 if (PHINode *PN = dyn_cast<PHINode>(P)) { 3192 // If this PHI changes the underlying object in every iteration of the 3193 // loop, don't look through it. Consider: 3194 // int **A; 3195 // for (i) { 3196 // Prev = Curr; // Prev = PHI (Prev_0, Curr) 3197 // Curr = A[i]; 3198 // *Prev, *Curr; 3199 // 3200 // Prev is tracking Curr one iteration behind so they refer to different 3201 // underlying objects. 3202 if (!LI || !LI->isLoopHeader(PN->getParent()) || 3203 isSameUnderlyingObjectInLoop(PN, LI)) 3204 for (Value *IncValue : PN->incoming_values()) 3205 Worklist.push_back(IncValue); 3206 continue; 3207 } 3208 3209 Objects.push_back(P); 3210 } while (!Worklist.empty()); 3211 } 3212 3213 /// Return true if the only users of this pointer are lifetime markers. 3214 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) { 3215 for (const User *U : V->users()) { 3216 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U); 3217 if (!II) return false; 3218 3219 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 3220 II->getIntrinsicID() != Intrinsic::lifetime_end) 3221 return false; 3222 } 3223 return true; 3224 } 3225 3226 bool llvm::isSafeToSpeculativelyExecute(const Value *V, 3227 const Instruction *CtxI, 3228 const DominatorTree *DT) { 3229 const Operator *Inst = dyn_cast<Operator>(V); 3230 if (!Inst) 3231 return false; 3232 3233 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) 3234 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i))) 3235 if (C->canTrap()) 3236 return false; 3237 3238 switch (Inst->getOpcode()) { 3239 default: 3240 return true; 3241 case Instruction::UDiv: 3242 case Instruction::URem: { 3243 // x / y is undefined if y == 0. 3244 const APInt *V; 3245 if (match(Inst->getOperand(1), m_APInt(V))) 3246 return *V != 0; 3247 return false; 3248 } 3249 case Instruction::SDiv: 3250 case Instruction::SRem: { 3251 // x / y is undefined if y == 0 or x == INT_MIN and y == -1 3252 const APInt *Numerator, *Denominator; 3253 if (!match(Inst->getOperand(1), m_APInt(Denominator))) 3254 return false; 3255 // We cannot hoist this division if the denominator is 0. 3256 if (*Denominator == 0) 3257 return false; 3258 // It's safe to hoist if the denominator is not 0 or -1. 3259 if (*Denominator != -1) 3260 return true; 3261 // At this point we know that the denominator is -1. It is safe to hoist as 3262 // long we know that the numerator is not INT_MIN. 3263 if (match(Inst->getOperand(0), m_APInt(Numerator))) 3264 return !Numerator->isMinSignedValue(); 3265 // The numerator *might* be MinSignedValue. 3266 return false; 3267 } 3268 case Instruction::Load: { 3269 const LoadInst *LI = cast<LoadInst>(Inst); 3270 if (!LI->isUnordered() || 3271 // Speculative load may create a race that did not exist in the source. 3272 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) || 3273 // Speculative load may load data from dirty regions. 3274 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress)) 3275 return false; 3276 const DataLayout &DL = LI->getModule()->getDataLayout(); 3277 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(), 3278 LI->getAlignment(), DL, CtxI, DT); 3279 } 3280 case Instruction::Call: { 3281 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 3282 switch (II->getIntrinsicID()) { 3283 // These synthetic intrinsics have no side-effects and just mark 3284 // information about their operands. 3285 // FIXME: There are other no-op synthetic instructions that potentially 3286 // should be considered at least *safe* to speculate... 3287 case Intrinsic::dbg_declare: 3288 case Intrinsic::dbg_value: 3289 return true; 3290 3291 case Intrinsic::bitreverse: 3292 case Intrinsic::bswap: 3293 case Intrinsic::ctlz: 3294 case Intrinsic::ctpop: 3295 case Intrinsic::cttz: 3296 case Intrinsic::objectsize: 3297 case Intrinsic::sadd_with_overflow: 3298 case Intrinsic::smul_with_overflow: 3299 case Intrinsic::ssub_with_overflow: 3300 case Intrinsic::uadd_with_overflow: 3301 case Intrinsic::umul_with_overflow: 3302 case Intrinsic::usub_with_overflow: 3303 return true; 3304 // These intrinsics are defined to have the same behavior as libm 3305 // functions except for setting errno. 3306 case Intrinsic::sqrt: 3307 case Intrinsic::fma: 3308 case Intrinsic::fmuladd: 3309 return true; 3310 // These intrinsics are defined to have the same behavior as libm 3311 // functions, and the corresponding libm functions never set errno. 3312 case Intrinsic::trunc: 3313 case Intrinsic::copysign: 3314 case Intrinsic::fabs: 3315 case Intrinsic::minnum: 3316 case Intrinsic::maxnum: 3317 return true; 3318 // These intrinsics are defined to have the same behavior as libm 3319 // functions, which never overflow when operating on the IEEE754 types 3320 // that we support, and never set errno otherwise. 3321 case Intrinsic::ceil: 3322 case Intrinsic::floor: 3323 case Intrinsic::nearbyint: 3324 case Intrinsic::rint: 3325 case Intrinsic::round: 3326 return true; 3327 // TODO: are convert_{from,to}_fp16 safe? 3328 // TODO: can we list target-specific intrinsics here? 3329 default: break; 3330 } 3331 } 3332 return false; // The called function could have undefined behavior or 3333 // side-effects, even if marked readnone nounwind. 3334 } 3335 case Instruction::VAArg: 3336 case Instruction::Alloca: 3337 case Instruction::Invoke: 3338 case Instruction::PHI: 3339 case Instruction::Store: 3340 case Instruction::Ret: 3341 case Instruction::Br: 3342 case Instruction::IndirectBr: 3343 case Instruction::Switch: 3344 case Instruction::Unreachable: 3345 case Instruction::Fence: 3346 case Instruction::AtomicRMW: 3347 case Instruction::AtomicCmpXchg: 3348 case Instruction::LandingPad: 3349 case Instruction::Resume: 3350 case Instruction::CatchSwitch: 3351 case Instruction::CatchPad: 3352 case Instruction::CatchRet: 3353 case Instruction::CleanupPad: 3354 case Instruction::CleanupRet: 3355 return false; // Misc instructions which have effects 3356 } 3357 } 3358 3359 bool llvm::mayBeMemoryDependent(const Instruction &I) { 3360 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I); 3361 } 3362 3363 /// Return true if we know that the specified value is never null. 3364 bool llvm::isKnownNonNull(const Value *V) { 3365 assert(V->getType()->isPointerTy() && "V must be pointer type"); 3366 3367 // Alloca never returns null, malloc might. 3368 if (isa<AllocaInst>(V)) return true; 3369 3370 // A byval, inalloca, or nonnull argument is never null. 3371 if (const Argument *A = dyn_cast<Argument>(V)) 3372 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr(); 3373 3374 // A global variable in address space 0 is non null unless extern weak 3375 // or an absolute symbol reference. Other address spaces may have null as a 3376 // valid address for a global, so we can't assume anything. 3377 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 3378 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() && 3379 GV->getType()->getAddressSpace() == 0; 3380 3381 // A Load tagged with nonnull metadata is never null. 3382 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) 3383 return LI->getMetadata(LLVMContext::MD_nonnull); 3384 3385 if (auto CS = ImmutableCallSite(V)) 3386 if (CS.isReturnNonNull()) 3387 return true; 3388 3389 return false; 3390 } 3391 3392 static bool isKnownNonNullFromDominatingCondition(const Value *V, 3393 const Instruction *CtxI, 3394 const DominatorTree *DT) { 3395 assert(V->getType()->isPointerTy() && "V must be pointer type"); 3396 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull"); 3397 assert(CtxI && "Context instruction required for analysis"); 3398 assert(DT && "Dominator tree required for analysis"); 3399 3400 unsigned NumUsesExplored = 0; 3401 for (auto *U : V->users()) { 3402 // Avoid massive lists 3403 if (NumUsesExplored >= DomConditionsMaxUses) 3404 break; 3405 NumUsesExplored++; 3406 // Consider only compare instructions uniquely controlling a branch 3407 CmpInst::Predicate Pred; 3408 if (!match(const_cast<User *>(U), 3409 m_c_ICmp(Pred, m_Specific(V), m_Zero())) || 3410 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)) 3411 continue; 3412 3413 for (auto *CmpU : U->users()) { 3414 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) { 3415 assert(BI->isConditional() && "uses a comparison!"); 3416 3417 BasicBlock *NonNullSuccessor = 3418 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0); 3419 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor); 3420 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent())) 3421 return true; 3422 } else if (Pred == ICmpInst::ICMP_NE && 3423 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) && 3424 DT->dominates(cast<Instruction>(CmpU), CtxI)) { 3425 return true; 3426 } 3427 } 3428 } 3429 3430 return false; 3431 } 3432 3433 bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI, 3434 const DominatorTree *DT) { 3435 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V)) 3436 return false; 3437 3438 if (isKnownNonNull(V)) 3439 return true; 3440 3441 if (!CtxI || !DT) 3442 return false; 3443 3444 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT); 3445 } 3446 3447 OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS, 3448 const Value *RHS, 3449 const DataLayout &DL, 3450 AssumptionCache *AC, 3451 const Instruction *CxtI, 3452 const DominatorTree *DT) { 3453 // Multiplying n * m significant bits yields a result of n + m significant 3454 // bits. If the total number of significant bits does not exceed the 3455 // result bit width (minus 1), there is no overflow. 3456 // This means if we have enough leading zero bits in the operands 3457 // we can guarantee that the result does not overflow. 3458 // Ref: "Hacker's Delight" by Henry Warren 3459 unsigned BitWidth = LHS->getType()->getScalarSizeInBits(); 3460 APInt LHSKnownZero(BitWidth, 0); 3461 APInt LHSKnownOne(BitWidth, 0); 3462 APInt RHSKnownZero(BitWidth, 0); 3463 APInt RHSKnownOne(BitWidth, 0); 3464 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI, 3465 DT); 3466 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI, 3467 DT); 3468 // Note that underestimating the number of zero bits gives a more 3469 // conservative answer. 3470 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() + 3471 RHSKnownZero.countLeadingOnes(); 3472 // First handle the easy case: if we have enough zero bits there's 3473 // definitely no overflow. 3474 if (ZeroBits >= BitWidth) 3475 return OverflowResult::NeverOverflows; 3476 3477 // Get the largest possible values for each operand. 3478 APInt LHSMax = ~LHSKnownZero; 3479 APInt RHSMax = ~RHSKnownZero; 3480 3481 // We know the multiply operation doesn't overflow if the maximum values for 3482 // each operand will not overflow after we multiply them together. 3483 bool MaxOverflow; 3484 LHSMax.umul_ov(RHSMax, MaxOverflow); 3485 if (!MaxOverflow) 3486 return OverflowResult::NeverOverflows; 3487 3488 // We know it always overflows if multiplying the smallest possible values for 3489 // the operands also results in overflow. 3490 bool MinOverflow; 3491 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow); 3492 if (MinOverflow) 3493 return OverflowResult::AlwaysOverflows; 3494 3495 return OverflowResult::MayOverflow; 3496 } 3497 3498 OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS, 3499 const Value *RHS, 3500 const DataLayout &DL, 3501 AssumptionCache *AC, 3502 const Instruction *CxtI, 3503 const DominatorTree *DT) { 3504 bool LHSKnownNonNegative, LHSKnownNegative; 3505 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0, 3506 AC, CxtI, DT); 3507 if (LHSKnownNonNegative || LHSKnownNegative) { 3508 bool RHSKnownNonNegative, RHSKnownNegative; 3509 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0, 3510 AC, CxtI, DT); 3511 3512 if (LHSKnownNegative && RHSKnownNegative) { 3513 // The sign bit is set in both cases: this MUST overflow. 3514 // Create a simple add instruction, and insert it into the struct. 3515 return OverflowResult::AlwaysOverflows; 3516 } 3517 3518 if (LHSKnownNonNegative && RHSKnownNonNegative) { 3519 // The sign bit is clear in both cases: this CANNOT overflow. 3520 // Create a simple add instruction, and insert it into the struct. 3521 return OverflowResult::NeverOverflows; 3522 } 3523 } 3524 3525 return OverflowResult::MayOverflow; 3526 } 3527 3528 static OverflowResult computeOverflowForSignedAdd(const Value *LHS, 3529 const Value *RHS, 3530 const AddOperator *Add, 3531 const DataLayout &DL, 3532 AssumptionCache *AC, 3533 const Instruction *CxtI, 3534 const DominatorTree *DT) { 3535 if (Add && Add->hasNoSignedWrap()) { 3536 return OverflowResult::NeverOverflows; 3537 } 3538 3539 bool LHSKnownNonNegative, LHSKnownNegative; 3540 bool RHSKnownNonNegative, RHSKnownNegative; 3541 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0, 3542 AC, CxtI, DT); 3543 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0, 3544 AC, CxtI, DT); 3545 3546 if ((LHSKnownNonNegative && RHSKnownNegative) || 3547 (LHSKnownNegative && RHSKnownNonNegative)) { 3548 // The sign bits are opposite: this CANNOT overflow. 3549 return OverflowResult::NeverOverflows; 3550 } 3551 3552 // The remaining code needs Add to be available. Early returns if not so. 3553 if (!Add) 3554 return OverflowResult::MayOverflow; 3555 3556 // If the sign of Add is the same as at least one of the operands, this add 3557 // CANNOT overflow. This is particularly useful when the sum is 3558 // @llvm.assume'ed non-negative rather than proved so from analyzing its 3559 // operands. 3560 bool LHSOrRHSKnownNonNegative = 3561 (LHSKnownNonNegative || RHSKnownNonNegative); 3562 bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative); 3563 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) { 3564 bool AddKnownNonNegative, AddKnownNegative; 3565 ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL, 3566 /*Depth=*/0, AC, CxtI, DT); 3567 if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) || 3568 (AddKnownNegative && LHSOrRHSKnownNegative)) { 3569 return OverflowResult::NeverOverflows; 3570 } 3571 } 3572 3573 return OverflowResult::MayOverflow; 3574 } 3575 3576 bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II, 3577 const DominatorTree &DT) { 3578 #ifndef NDEBUG 3579 auto IID = II->getIntrinsicID(); 3580 assert((IID == Intrinsic::sadd_with_overflow || 3581 IID == Intrinsic::uadd_with_overflow || 3582 IID == Intrinsic::ssub_with_overflow || 3583 IID == Intrinsic::usub_with_overflow || 3584 IID == Intrinsic::smul_with_overflow || 3585 IID == Intrinsic::umul_with_overflow) && 3586 "Not an overflow intrinsic!"); 3587 #endif 3588 3589 SmallVector<const BranchInst *, 2> GuardingBranches; 3590 SmallVector<const ExtractValueInst *, 2> Results; 3591 3592 for (const User *U : II->users()) { 3593 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) { 3594 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type"); 3595 3596 if (EVI->getIndices()[0] == 0) 3597 Results.push_back(EVI); 3598 else { 3599 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type"); 3600 3601 for (const auto *U : EVI->users()) 3602 if (const auto *B = dyn_cast<BranchInst>(U)) { 3603 assert(B->isConditional() && "How else is it using an i1?"); 3604 GuardingBranches.push_back(B); 3605 } 3606 } 3607 } else { 3608 // We are using the aggregate directly in a way we don't want to analyze 3609 // here (storing it to a global, say). 3610 return false; 3611 } 3612 } 3613 3614 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) { 3615 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1)); 3616 if (!NoWrapEdge.isSingleEdge()) 3617 return false; 3618 3619 // Check if all users of the add are provably no-wrap. 3620 for (const auto *Result : Results) { 3621 // If the extractvalue itself is not executed on overflow, the we don't 3622 // need to check each use separately, since domination is transitive. 3623 if (DT.dominates(NoWrapEdge, Result->getParent())) 3624 continue; 3625 3626 for (auto &RU : Result->uses()) 3627 if (!DT.dominates(NoWrapEdge, RU)) 3628 return false; 3629 } 3630 3631 return true; 3632 }; 3633 3634 return any_of(GuardingBranches, AllUsesGuardedByBranch); 3635 } 3636 3637 3638 OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add, 3639 const DataLayout &DL, 3640 AssumptionCache *AC, 3641 const Instruction *CxtI, 3642 const DominatorTree *DT) { 3643 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1), 3644 Add, DL, AC, CxtI, DT); 3645 } 3646 3647 OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS, 3648 const Value *RHS, 3649 const DataLayout &DL, 3650 AssumptionCache *AC, 3651 const Instruction *CxtI, 3652 const DominatorTree *DT) { 3653 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT); 3654 } 3655 3656 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) { 3657 // A memory operation returns normally if it isn't volatile. A volatile 3658 // operation is allowed to trap. 3659 // 3660 // An atomic operation isn't guaranteed to return in a reasonable amount of 3661 // time because it's possible for another thread to interfere with it for an 3662 // arbitrary length of time, but programs aren't allowed to rely on that. 3663 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) 3664 return !LI->isVolatile(); 3665 if (const StoreInst *SI = dyn_cast<StoreInst>(I)) 3666 return !SI->isVolatile(); 3667 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I)) 3668 return !CXI->isVolatile(); 3669 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) 3670 return !RMWI->isVolatile(); 3671 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I)) 3672 return !MII->isVolatile(); 3673 3674 // If there is no successor, then execution can't transfer to it. 3675 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) 3676 return !CRI->unwindsToCaller(); 3677 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) 3678 return !CatchSwitch->unwindsToCaller(); 3679 if (isa<ResumeInst>(I)) 3680 return false; 3681 if (isa<ReturnInst>(I)) 3682 return false; 3683 3684 // Calls can throw, or contain an infinite loop, or kill the process. 3685 if (auto CS = ImmutableCallSite(I)) { 3686 // Call sites that throw have implicit non-local control flow. 3687 if (!CS.doesNotThrow()) 3688 return false; 3689 3690 // Non-throwing call sites can loop infinitely, call exit/pthread_exit 3691 // etc. and thus not return. However, LLVM already assumes that 3692 // 3693 // - Thread exiting actions are modeled as writes to memory invisible to 3694 // the program. 3695 // 3696 // - Loops that don't have side effects (side effects are volatile/atomic 3697 // stores and IO) always terminate (see http://llvm.org/PR965). 3698 // Furthermore IO itself is also modeled as writes to memory invisible to 3699 // the program. 3700 // 3701 // We rely on those assumptions here, and use the memory effects of the call 3702 // target as a proxy for checking that it always returns. 3703 3704 // FIXME: This isn't aggressive enough; a call which only writes to a global 3705 // is guaranteed to return. 3706 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() || 3707 match(I, m_Intrinsic<Intrinsic::assume>()); 3708 } 3709 3710 // Other instructions return normally. 3711 return true; 3712 } 3713 3714 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I, 3715 const Loop *L) { 3716 // The loop header is guaranteed to be executed for every iteration. 3717 // 3718 // FIXME: Relax this constraint to cover all basic blocks that are 3719 // guaranteed to be executed at every iteration. 3720 if (I->getParent() != L->getHeader()) return false; 3721 3722 for (const Instruction &LI : *L->getHeader()) { 3723 if (&LI == I) return true; 3724 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false; 3725 } 3726 llvm_unreachable("Instruction not contained in its own parent basic block."); 3727 } 3728 3729 bool llvm::propagatesFullPoison(const Instruction *I) { 3730 switch (I->getOpcode()) { 3731 case Instruction::Add: 3732 case Instruction::Sub: 3733 case Instruction::Xor: 3734 case Instruction::Trunc: 3735 case Instruction::BitCast: 3736 case Instruction::AddrSpaceCast: 3737 // These operations all propagate poison unconditionally. Note that poison 3738 // is not any particular value, so xor or subtraction of poison with 3739 // itself still yields poison, not zero. 3740 return true; 3741 3742 case Instruction::AShr: 3743 case Instruction::SExt: 3744 // For these operations, one bit of the input is replicated across 3745 // multiple output bits. A replicated poison bit is still poison. 3746 return true; 3747 3748 case Instruction::Shl: { 3749 // Left shift *by* a poison value is poison. The number of 3750 // positions to shift is unsigned, so no negative values are 3751 // possible there. Left shift by zero places preserves poison. So 3752 // it only remains to consider left shift of poison by a positive 3753 // number of places. 3754 // 3755 // A left shift by a positive number of places leaves the lowest order bit 3756 // non-poisoned. However, if such a shift has a no-wrap flag, then we can 3757 // make the poison operand violate that flag, yielding a fresh full-poison 3758 // value. 3759 auto *OBO = cast<OverflowingBinaryOperator>(I); 3760 return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap(); 3761 } 3762 3763 case Instruction::Mul: { 3764 // A multiplication by zero yields a non-poison zero result, so we need to 3765 // rule out zero as an operand. Conservatively, multiplication by a 3766 // non-zero constant is not multiplication by zero. 3767 // 3768 // Multiplication by a non-zero constant can leave some bits 3769 // non-poisoned. For example, a multiplication by 2 leaves the lowest 3770 // order bit unpoisoned. So we need to consider that. 3771 // 3772 // Multiplication by 1 preserves poison. If the multiplication has a 3773 // no-wrap flag, then we can make the poison operand violate that flag 3774 // when multiplied by any integer other than 0 and 1. 3775 auto *OBO = cast<OverflowingBinaryOperator>(I); 3776 if (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) { 3777 for (Value *V : OBO->operands()) { 3778 if (auto *CI = dyn_cast<ConstantInt>(V)) { 3779 // A ConstantInt cannot yield poison, so we can assume that it is 3780 // the other operand that is poison. 3781 return !CI->isZero(); 3782 } 3783 } 3784 } 3785 return false; 3786 } 3787 3788 case Instruction::ICmp: 3789 // Comparing poison with any value yields poison. This is why, for 3790 // instance, x s< (x +nsw 1) can be folded to true. 3791 return true; 3792 3793 case Instruction::GetElementPtr: 3794 // A GEP implicitly represents a sequence of additions, subtractions, 3795 // truncations, sign extensions and multiplications. The multiplications 3796 // are by the non-zero sizes of some set of types, so we do not have to be 3797 // concerned with multiplication by zero. If the GEP is in-bounds, then 3798 // these operations are implicitly no-signed-wrap so poison is propagated 3799 // by the arguments above for Add, Sub, Trunc, SExt and Mul. 3800 return cast<GEPOperator>(I)->isInBounds(); 3801 3802 default: 3803 return false; 3804 } 3805 } 3806 3807 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) { 3808 switch (I->getOpcode()) { 3809 case Instruction::Store: 3810 return cast<StoreInst>(I)->getPointerOperand(); 3811 3812 case Instruction::Load: 3813 return cast<LoadInst>(I)->getPointerOperand(); 3814 3815 case Instruction::AtomicCmpXchg: 3816 return cast<AtomicCmpXchgInst>(I)->getPointerOperand(); 3817 3818 case Instruction::AtomicRMW: 3819 return cast<AtomicRMWInst>(I)->getPointerOperand(); 3820 3821 case Instruction::UDiv: 3822 case Instruction::SDiv: 3823 case Instruction::URem: 3824 case Instruction::SRem: 3825 return I->getOperand(1); 3826 3827 default: 3828 return nullptr; 3829 } 3830 } 3831 3832 bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) { 3833 // We currently only look for uses of poison values within the same basic 3834 // block, as that makes it easier to guarantee that the uses will be 3835 // executed given that PoisonI is executed. 3836 // 3837 // FIXME: Expand this to consider uses beyond the same basic block. To do 3838 // this, look out for the distinction between post-dominance and strong 3839 // post-dominance. 3840 const BasicBlock *BB = PoisonI->getParent(); 3841 3842 // Set of instructions that we have proved will yield poison if PoisonI 3843 // does. 3844 SmallSet<const Value *, 16> YieldsPoison; 3845 SmallSet<const BasicBlock *, 4> Visited; 3846 YieldsPoison.insert(PoisonI); 3847 Visited.insert(PoisonI->getParent()); 3848 3849 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end(); 3850 3851 unsigned Iter = 0; 3852 while (Iter++ < MaxDepth) { 3853 for (auto &I : make_range(Begin, End)) { 3854 if (&I != PoisonI) { 3855 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I); 3856 if (NotPoison != nullptr && YieldsPoison.count(NotPoison)) 3857 return true; 3858 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 3859 return false; 3860 } 3861 3862 // Mark poison that propagates from I through uses of I. 3863 if (YieldsPoison.count(&I)) { 3864 for (const User *User : I.users()) { 3865 const Instruction *UserI = cast<Instruction>(User); 3866 if (propagatesFullPoison(UserI)) 3867 YieldsPoison.insert(User); 3868 } 3869 } 3870 } 3871 3872 if (auto *NextBB = BB->getSingleSuccessor()) { 3873 if (Visited.insert(NextBB).second) { 3874 BB = NextBB; 3875 Begin = BB->getFirstNonPHI()->getIterator(); 3876 End = BB->end(); 3877 continue; 3878 } 3879 } 3880 3881 break; 3882 }; 3883 return false; 3884 } 3885 3886 static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) { 3887 if (FMF.noNaNs()) 3888 return true; 3889 3890 if (auto *C = dyn_cast<ConstantFP>(V)) 3891 return !C->isNaN(); 3892 return false; 3893 } 3894 3895 static bool isKnownNonZero(const Value *V) { 3896 if (auto *C = dyn_cast<ConstantFP>(V)) 3897 return !C->isZero(); 3898 return false; 3899 } 3900 3901 /// Match non-obvious integer minimum and maximum sequences. 3902 static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, 3903 Value *CmpLHS, Value *CmpRHS, 3904 Value *TrueVal, Value *FalseVal, 3905 Value *&LHS, Value *&RHS) { 3906 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT) 3907 return {SPF_UNKNOWN, SPNB_NA, false}; 3908 3909 // Z = X -nsw Y 3910 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0) 3911 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0) 3912 if (match(TrueVal, m_Zero()) && 3913 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS)))) { 3914 LHS = TrueVal; 3915 RHS = FalseVal; 3916 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false}; 3917 } 3918 3919 // Z = X -nsw Y 3920 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0) 3921 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0) 3922 if (match(FalseVal, m_Zero()) && 3923 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS)))) { 3924 LHS = TrueVal; 3925 RHS = FalseVal; 3926 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false}; 3927 } 3928 3929 const APInt *C1; 3930 if (!match(CmpRHS, m_APInt(C1))) 3931 return {SPF_UNKNOWN, SPNB_NA, false}; 3932 3933 // An unsigned min/max can be written with a signed compare. 3934 const APInt *C2; 3935 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) || 3936 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) { 3937 // Is the sign bit set? 3938 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX 3939 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN 3940 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue()) { 3941 LHS = TrueVal; 3942 RHS = FalseVal; 3943 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false}; 3944 } 3945 3946 // Is the sign bit clear? 3947 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX 3948 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN 3949 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() && 3950 C2->isMinSignedValue()) { 3951 LHS = TrueVal; 3952 RHS = FalseVal; 3953 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false}; 3954 } 3955 } 3956 3957 // Look through 'not' ops to find disguised signed min/max. 3958 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C) 3959 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C) 3960 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) && 3961 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2) { 3962 LHS = TrueVal; 3963 RHS = FalseVal; 3964 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false}; 3965 } 3966 3967 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X) 3968 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X) 3969 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) && 3970 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2) { 3971 LHS = TrueVal; 3972 RHS = FalseVal; 3973 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false}; 3974 } 3975 3976 return {SPF_UNKNOWN, SPNB_NA, false}; 3977 } 3978 3979 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred, 3980 FastMathFlags FMF, 3981 Value *CmpLHS, Value *CmpRHS, 3982 Value *TrueVal, Value *FalseVal, 3983 Value *&LHS, Value *&RHS) { 3984 LHS = CmpLHS; 3985 RHS = CmpRHS; 3986 3987 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may 3988 // return inconsistent results between implementations. 3989 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0 3990 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1) 3991 // Therefore we behave conservatively and only proceed if at least one of the 3992 // operands is known to not be zero, or if we don't care about signed zeroes. 3993 switch (Pred) { 3994 default: break; 3995 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE: 3996 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE: 3997 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) && 3998 !isKnownNonZero(CmpRHS)) 3999 return {SPF_UNKNOWN, SPNB_NA, false}; 4000 } 4001 4002 SelectPatternNaNBehavior NaNBehavior = SPNB_NA; 4003 bool Ordered = false; 4004 4005 // When given one NaN and one non-NaN input: 4006 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input. 4007 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the 4008 // ordered comparison fails), which could be NaN or non-NaN. 4009 // so here we discover exactly what NaN behavior is required/accepted. 4010 if (CmpInst::isFPPredicate(Pred)) { 4011 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF); 4012 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF); 4013 4014 if (LHSSafe && RHSSafe) { 4015 // Both operands are known non-NaN. 4016 NaNBehavior = SPNB_RETURNS_ANY; 4017 } else if (CmpInst::isOrdered(Pred)) { 4018 // An ordered comparison will return false when given a NaN, so it 4019 // returns the RHS. 4020 Ordered = true; 4021 if (LHSSafe) 4022 // LHS is non-NaN, so if RHS is NaN then NaN will be returned. 4023 NaNBehavior = SPNB_RETURNS_NAN; 4024 else if (RHSSafe) 4025 NaNBehavior = SPNB_RETURNS_OTHER; 4026 else 4027 // Completely unsafe. 4028 return {SPF_UNKNOWN, SPNB_NA, false}; 4029 } else { 4030 Ordered = false; 4031 // An unordered comparison will return true when given a NaN, so it 4032 // returns the LHS. 4033 if (LHSSafe) 4034 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned. 4035 NaNBehavior = SPNB_RETURNS_OTHER; 4036 else if (RHSSafe) 4037 NaNBehavior = SPNB_RETURNS_NAN; 4038 else 4039 // Completely unsafe. 4040 return {SPF_UNKNOWN, SPNB_NA, false}; 4041 } 4042 } 4043 4044 if (TrueVal == CmpRHS && FalseVal == CmpLHS) { 4045 std::swap(CmpLHS, CmpRHS); 4046 Pred = CmpInst::getSwappedPredicate(Pred); 4047 if (NaNBehavior == SPNB_RETURNS_NAN) 4048 NaNBehavior = SPNB_RETURNS_OTHER; 4049 else if (NaNBehavior == SPNB_RETURNS_OTHER) 4050 NaNBehavior = SPNB_RETURNS_NAN; 4051 Ordered = !Ordered; 4052 } 4053 4054 // ([if]cmp X, Y) ? X : Y 4055 if (TrueVal == CmpLHS && FalseVal == CmpRHS) { 4056 switch (Pred) { 4057 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality. 4058 case ICmpInst::ICMP_UGT: 4059 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false}; 4060 case ICmpInst::ICMP_SGT: 4061 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false}; 4062 case ICmpInst::ICMP_ULT: 4063 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false}; 4064 case ICmpInst::ICMP_SLT: 4065 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false}; 4066 case FCmpInst::FCMP_UGT: 4067 case FCmpInst::FCMP_UGE: 4068 case FCmpInst::FCMP_OGT: 4069 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered}; 4070 case FCmpInst::FCMP_ULT: 4071 case FCmpInst::FCMP_ULE: 4072 case FCmpInst::FCMP_OLT: 4073 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered}; 4074 } 4075 } 4076 4077 const APInt *C1; 4078 if (match(CmpRHS, m_APInt(C1))) { 4079 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) || 4080 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) { 4081 4082 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X 4083 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X 4084 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) { 4085 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false}; 4086 } 4087 4088 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X 4089 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X 4090 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) { 4091 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false}; 4092 } 4093 } 4094 } 4095 4096 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS); 4097 } 4098 4099 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, 4100 Instruction::CastOps *CastOp) { 4101 CastInst *CI = dyn_cast<CastInst>(V1); 4102 Constant *C = dyn_cast<Constant>(V2); 4103 if (!CI) 4104 return nullptr; 4105 *CastOp = CI->getOpcode(); 4106 4107 if (auto *CI2 = dyn_cast<CastInst>(V2)) { 4108 // If V1 and V2 are both the same cast from the same type, we can look 4109 // through V1. 4110 if (CI2->getOpcode() == CI->getOpcode() && 4111 CI2->getSrcTy() == CI->getSrcTy()) 4112 return CI2->getOperand(0); 4113 return nullptr; 4114 } else if (!C) { 4115 return nullptr; 4116 } 4117 4118 Constant *CastedTo = nullptr; 4119 4120 if (isa<ZExtInst>(CI) && CmpI->isUnsigned()) 4121 CastedTo = ConstantExpr::getTrunc(C, CI->getSrcTy()); 4122 4123 if (isa<SExtInst>(CI) && CmpI->isSigned()) 4124 CastedTo = ConstantExpr::getTrunc(C, CI->getSrcTy(), true); 4125 4126 if (isa<TruncInst>(CI)) 4127 CastedTo = ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned()); 4128 4129 if (isa<FPTruncInst>(CI)) 4130 CastedTo = ConstantExpr::getFPExtend(C, CI->getSrcTy(), true); 4131 4132 if (isa<FPExtInst>(CI)) 4133 CastedTo = ConstantExpr::getFPTrunc(C, CI->getSrcTy(), true); 4134 4135 if (isa<FPToUIInst>(CI)) 4136 CastedTo = ConstantExpr::getUIToFP(C, CI->getSrcTy(), true); 4137 4138 if (isa<FPToSIInst>(CI)) 4139 CastedTo = ConstantExpr::getSIToFP(C, CI->getSrcTy(), true); 4140 4141 if (isa<UIToFPInst>(CI)) 4142 CastedTo = ConstantExpr::getFPToUI(C, CI->getSrcTy(), true); 4143 4144 if (isa<SIToFPInst>(CI)) 4145 CastedTo = ConstantExpr::getFPToSI(C, CI->getSrcTy(), true); 4146 4147 if (!CastedTo) 4148 return nullptr; 4149 4150 Constant *CastedBack = 4151 ConstantExpr::getCast(CI->getOpcode(), CastedTo, C->getType(), true); 4152 // Make sure the cast doesn't lose any information. 4153 if (CastedBack != C) 4154 return nullptr; 4155 4156 return CastedTo; 4157 } 4158 4159 SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, 4160 Instruction::CastOps *CastOp) { 4161 SelectInst *SI = dyn_cast<SelectInst>(V); 4162 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false}; 4163 4164 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition()); 4165 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false}; 4166 4167 CmpInst::Predicate Pred = CmpI->getPredicate(); 4168 Value *CmpLHS = CmpI->getOperand(0); 4169 Value *CmpRHS = CmpI->getOperand(1); 4170 Value *TrueVal = SI->getTrueValue(); 4171 Value *FalseVal = SI->getFalseValue(); 4172 FastMathFlags FMF; 4173 if (isa<FPMathOperator>(CmpI)) 4174 FMF = CmpI->getFastMathFlags(); 4175 4176 // Bail out early. 4177 if (CmpI->isEquality()) 4178 return {SPF_UNKNOWN, SPNB_NA, false}; 4179 4180 // Deal with type mismatches. 4181 if (CastOp && CmpLHS->getType() != TrueVal->getType()) { 4182 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) 4183 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, 4184 cast<CastInst>(TrueVal)->getOperand(0), C, 4185 LHS, RHS); 4186 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) 4187 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, 4188 C, cast<CastInst>(FalseVal)->getOperand(0), 4189 LHS, RHS); 4190 } 4191 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, 4192 LHS, RHS); 4193 } 4194 4195 /// Return true if "icmp Pred LHS RHS" is always true. 4196 static bool isTruePredicate(CmpInst::Predicate Pred, 4197 const Value *LHS, const Value *RHS, 4198 const DataLayout &DL, unsigned Depth, 4199 AssumptionCache *AC, const Instruction *CxtI, 4200 const DominatorTree *DT) { 4201 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!"); 4202 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS) 4203 return true; 4204 4205 switch (Pred) { 4206 default: 4207 return false; 4208 4209 case CmpInst::ICMP_SLE: { 4210 const APInt *C; 4211 4212 // LHS s<= LHS +_{nsw} C if C >= 0 4213 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C)))) 4214 return !C->isNegative(); 4215 return false; 4216 } 4217 4218 case CmpInst::ICMP_ULE: { 4219 const APInt *C; 4220 4221 // LHS u<= LHS +_{nuw} C for any C 4222 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C)))) 4223 return true; 4224 4225 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB) 4226 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B, 4227 const Value *&X, 4228 const APInt *&CA, const APInt *&CB) { 4229 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) && 4230 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB)))) 4231 return true; 4232 4233 // If X & C == 0 then (X | C) == X +_{nuw} C 4234 if (match(A, m_Or(m_Value(X), m_APInt(CA))) && 4235 match(B, m_Or(m_Specific(X), m_APInt(CB)))) { 4236 unsigned BitWidth = CA->getBitWidth(); 4237 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0); 4238 computeKnownBits(X, KnownZero, KnownOne, DL, Depth + 1, AC, CxtI, DT); 4239 4240 if ((KnownZero & *CA) == *CA && (KnownZero & *CB) == *CB) 4241 return true; 4242 } 4243 4244 return false; 4245 }; 4246 4247 const Value *X; 4248 const APInt *CLHS, *CRHS; 4249 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS)) 4250 return CLHS->ule(*CRHS); 4251 4252 return false; 4253 } 4254 } 4255 } 4256 4257 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred 4258 /// ALHS ARHS" is true. Otherwise, return None. 4259 static Optional<bool> 4260 isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, 4261 const Value *ARHS, const Value *BLHS, 4262 const Value *BRHS, const DataLayout &DL, 4263 unsigned Depth, AssumptionCache *AC, 4264 const Instruction *CxtI, const DominatorTree *DT) { 4265 switch (Pred) { 4266 default: 4267 return None; 4268 4269 case CmpInst::ICMP_SLT: 4270 case CmpInst::ICMP_SLE: 4271 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI, 4272 DT) && 4273 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI, DT)) 4274 return true; 4275 return None; 4276 4277 case CmpInst::ICMP_ULT: 4278 case CmpInst::ICMP_ULE: 4279 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI, 4280 DT) && 4281 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI, DT)) 4282 return true; 4283 return None; 4284 } 4285 } 4286 4287 /// Return true if the operands of the two compares match. IsSwappedOps is true 4288 /// when the operands match, but are swapped. 4289 static bool isMatchingOps(const Value *ALHS, const Value *ARHS, 4290 const Value *BLHS, const Value *BRHS, 4291 bool &IsSwappedOps) { 4292 4293 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS); 4294 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS); 4295 return IsMatchingOps || IsSwappedOps; 4296 } 4297 4298 /// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is 4299 /// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS 4300 /// BRHS" is false. Otherwise, return None if we can't infer anything. 4301 static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred, 4302 const Value *ALHS, 4303 const Value *ARHS, 4304 CmpInst::Predicate BPred, 4305 const Value *BLHS, 4306 const Value *BRHS, 4307 bool IsSwappedOps) { 4308 // Canonicalize the operands so they're matching. 4309 if (IsSwappedOps) { 4310 std::swap(BLHS, BRHS); 4311 BPred = ICmpInst::getSwappedPredicate(BPred); 4312 } 4313 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred)) 4314 return true; 4315 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred)) 4316 return false; 4317 4318 return None; 4319 } 4320 4321 /// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is 4322 /// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS 4323 /// C2" is false. Otherwise, return None if we can't infer anything. 4324 static Optional<bool> 4325 isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS, 4326 const ConstantInt *C1, 4327 CmpInst::Predicate BPred, 4328 const Value *BLHS, const ConstantInt *C2) { 4329 assert(ALHS == BLHS && "LHS operands must match."); 4330 ConstantRange DomCR = 4331 ConstantRange::makeExactICmpRegion(APred, C1->getValue()); 4332 ConstantRange CR = 4333 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue()); 4334 ConstantRange Intersection = DomCR.intersectWith(CR); 4335 ConstantRange Difference = DomCR.difference(CR); 4336 if (Intersection.isEmptySet()) 4337 return false; 4338 if (Difference.isEmptySet()) 4339 return true; 4340 return None; 4341 } 4342 4343 Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS, 4344 const DataLayout &DL, bool InvertAPred, 4345 unsigned Depth, AssumptionCache *AC, 4346 const Instruction *CxtI, 4347 const DominatorTree *DT) { 4348 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for example. 4349 if (LHS->getType() != RHS->getType()) 4350 return None; 4351 4352 Type *OpTy = LHS->getType(); 4353 assert(OpTy->getScalarType()->isIntegerTy(1)); 4354 4355 // LHS ==> RHS by definition 4356 if (!InvertAPred && LHS == RHS) 4357 return true; 4358 4359 if (OpTy->isVectorTy()) 4360 // TODO: extending the code below to handle vectors 4361 return None; 4362 assert(OpTy->isIntegerTy(1) && "implied by above"); 4363 4364 ICmpInst::Predicate APred, BPred; 4365 Value *ALHS, *ARHS; 4366 Value *BLHS, *BRHS; 4367 4368 if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) || 4369 !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS)))) 4370 return None; 4371 4372 if (InvertAPred) 4373 APred = CmpInst::getInversePredicate(APred); 4374 4375 // Can we infer anything when the two compares have matching operands? 4376 bool IsSwappedOps; 4377 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) { 4378 if (Optional<bool> Implication = isImpliedCondMatchingOperands( 4379 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps)) 4380 return Implication; 4381 // No amount of additional analysis will infer the second condition, so 4382 // early exit. 4383 return None; 4384 } 4385 4386 // Can we infer anything when the LHS operands match and the RHS operands are 4387 // constants (not necessarily matching)? 4388 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) { 4389 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands( 4390 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS, 4391 cast<ConstantInt>(BRHS))) 4392 return Implication; 4393 // No amount of additional analysis will infer the second condition, so 4394 // early exit. 4395 return None; 4396 } 4397 4398 if (APred == BPred) 4399 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC, 4400 CxtI, DT); 4401 4402 return None; 4403 } 4404