1 //===- InstCombineSimplifyDemanded.cpp ------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains logic for simplifying instructions based on information 10 // about how they are used. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/Analysis/ValueTracking.h" 16 #include "llvm/IR/GetElementPtrTypeIterator.h" 17 #include "llvm/IR/IntrinsicInst.h" 18 #include "llvm/IR/PatternMatch.h" 19 #include "llvm/Support/KnownBits.h" 20 #include "llvm/Transforms/InstCombine/InstCombiner.h" 21 22 using namespace llvm; 23 using namespace llvm::PatternMatch; 24 25 #define DEBUG_TYPE "instcombine" 26 27 /// Check to see if the specified operand of the specified instruction is a 28 /// constant integer. If so, check to see if there are any bits set in the 29 /// constant that are not demanded. If so, shrink the constant and return true. 30 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 31 const APInt &Demanded) { 32 assert(I && "No instruction?"); 33 assert(OpNo < I->getNumOperands() && "Operand index too large"); 34 35 // The operand must be a constant integer or splat integer. 36 Value *Op = I->getOperand(OpNo); 37 const APInt *C; 38 if (!match(Op, m_APInt(C))) 39 return false; 40 41 // If there are no bits set that aren't demanded, nothing to do. 42 if (C->isSubsetOf(Demanded)) 43 return false; 44 45 // This instruction is producing bits that are not demanded. Shrink the RHS. 46 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded)); 47 48 return true; 49 } 50 51 52 53 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if 54 /// the instruction has any properties that allow us to simplify its operands. 55 bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst) { 56 unsigned BitWidth = Inst.getType()->getScalarSizeInBits(); 57 KnownBits Known(BitWidth); 58 APInt DemandedMask(APInt::getAllOnes(BitWidth)); 59 60 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known, 61 0, &Inst); 62 if (!V) return false; 63 if (V == &Inst) return true; 64 replaceInstUsesWith(Inst, V); 65 return true; 66 } 67 68 /// This form of SimplifyDemandedBits simplifies the specified instruction 69 /// operand if possible, updating it in place. It returns true if it made any 70 /// change and false otherwise. 71 bool InstCombinerImpl::SimplifyDemandedBits(Instruction *I, unsigned OpNo, 72 const APInt &DemandedMask, 73 KnownBits &Known, unsigned Depth) { 74 Use &U = I->getOperandUse(OpNo); 75 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known, 76 Depth, I); 77 if (!NewVal) return false; 78 if (Instruction* OpInst = dyn_cast<Instruction>(U)) 79 salvageDebugInfo(*OpInst); 80 81 replaceUse(U, NewVal); 82 return true; 83 } 84 85 /// This function attempts to replace V with a simpler value based on the 86 /// demanded bits. When this function is called, it is known that only the bits 87 /// set in DemandedMask of the result of V are ever used downstream. 88 /// Consequently, depending on the mask and V, it may be possible to replace V 89 /// with a constant or one of its operands. In such cases, this function does 90 /// the replacement and returns true. In all other cases, it returns false after 91 /// analyzing the expression and setting KnownOne and known to be one in the 92 /// expression. Known.Zero contains all the bits that are known to be zero in 93 /// the expression. These are provided to potentially allow the caller (which 94 /// might recursively be SimplifyDemandedBits itself) to simplify the 95 /// expression. 96 /// Known.One and Known.Zero always follow the invariant that: 97 /// Known.One & Known.Zero == 0. 98 /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and 99 /// Known.Zero may only be accurate for those bits set in DemandedMask. Note 100 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all 101 /// be the same. 102 /// 103 /// This returns null if it did not change anything and it permits no 104 /// simplification. This returns V itself if it did some simplification of V's 105 /// operands based on the information about what bits are demanded. This returns 106 /// some other non-null value if it found out that V is equal to another value 107 /// in the context where the specified bits are demanded, but not for all users. 108 Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 109 KnownBits &Known, 110 unsigned Depth, 111 Instruction *CxtI) { 112 assert(V != nullptr && "Null pointer of Value???"); 113 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth"); 114 uint32_t BitWidth = DemandedMask.getBitWidth(); 115 Type *VTy = V->getType(); 116 assert( 117 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) && 118 Known.getBitWidth() == BitWidth && 119 "Value *V, DemandedMask and Known must have same BitWidth"); 120 121 if (isa<Constant>(V)) { 122 computeKnownBits(V, Known, Depth, CxtI); 123 return nullptr; 124 } 125 126 Known.resetAll(); 127 if (DemandedMask.isZero()) // Not demanding any bits from V. 128 return UndefValue::get(VTy); 129 130 if (Depth == MaxAnalysisRecursionDepth) 131 return nullptr; 132 133 if (isa<ScalableVectorType>(VTy)) 134 return nullptr; 135 136 Instruction *I = dyn_cast<Instruction>(V); 137 if (!I) { 138 computeKnownBits(V, Known, Depth, CxtI); 139 return nullptr; // Only analyze instructions. 140 } 141 142 // If there are multiple uses of this value and we aren't at the root, then 143 // we can't do any simplifications of the operands, because DemandedMask 144 // only reflects the bits demanded by *one* of the users. 145 if (Depth != 0 && !I->hasOneUse()) 146 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI); 147 148 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth); 149 150 // If this is the root being simplified, allow it to have multiple uses, 151 // just set the DemandedMask to all bits so that we can try to simplify the 152 // operands. This allows visitTruncInst (for example) to simplify the 153 // operand of a trunc without duplicating all the logic below. 154 if (Depth == 0 && !V->hasOneUse()) 155 DemandedMask.setAllBits(); 156 157 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care 158 // about the high bits of the operands. 159 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) { 160 unsigned NLZ = DemandedMask.countLeadingZeros(); 161 // Right fill the mask of bits for the operands to demand the most 162 // significant bit and all those below it. 163 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ); 164 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) || 165 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) || 166 ShrinkDemandedConstant(I, 1, DemandedFromOps) || 167 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) { 168 if (NLZ > 0) { 169 // Disable the nsw and nuw flags here: We can no longer guarantee that 170 // we won't wrap after simplification. Removing the nsw/nuw flags is 171 // legal here because the top bit is not demanded. 172 I->setHasNoSignedWrap(false); 173 I->setHasNoUnsignedWrap(false); 174 } 175 return true; 176 } 177 return false; 178 }; 179 180 switch (I->getOpcode()) { 181 default: 182 computeKnownBits(I, Known, Depth, CxtI); 183 break; 184 case Instruction::And: { 185 // If either the LHS or the RHS are Zero, the result is zero. 186 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 187 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown, 188 Depth + 1)) 189 return I; 190 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 191 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 192 193 Known = LHSKnown & RHSKnown; 194 195 // If the client is only demanding bits that we know, return the known 196 // constant. 197 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 198 return Constant::getIntegerValue(VTy, Known.One); 199 200 // If all of the demanded bits are known 1 on one side, return the other. 201 // These bits cannot contribute to the result of the 'and'. 202 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 203 return I->getOperand(0); 204 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 205 return I->getOperand(1); 206 207 // If the RHS is a constant, see if we can simplify it. 208 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero)) 209 return I; 210 211 break; 212 } 213 case Instruction::Or: { 214 // If either the LHS or the RHS are One, the result is One. 215 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 216 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown, 217 Depth + 1)) 218 return I; 219 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 220 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 221 222 Known = LHSKnown | RHSKnown; 223 224 // If the client is only demanding bits that we know, return the known 225 // constant. 226 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 227 return Constant::getIntegerValue(VTy, Known.One); 228 229 // If all of the demanded bits are known zero on one side, return the other. 230 // These bits cannot contribute to the result of the 'or'. 231 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 232 return I->getOperand(0); 233 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 234 return I->getOperand(1); 235 236 // If the RHS is a constant, see if we can simplify it. 237 if (ShrinkDemandedConstant(I, 1, DemandedMask)) 238 return I; 239 240 break; 241 } 242 case Instruction::Xor: { 243 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) || 244 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1)) 245 return I; 246 Value *LHS, *RHS; 247 if (DemandedMask == 1 && 248 match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) && 249 match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) { 250 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1 251 IRBuilderBase::InsertPointGuard Guard(Builder); 252 Builder.SetInsertPoint(I); 253 auto *Xor = Builder.CreateXor(LHS, RHS); 254 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor); 255 } 256 257 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 258 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 259 260 Known = LHSKnown ^ RHSKnown; 261 262 // If the client is only demanding bits that we know, return the known 263 // constant. 264 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 265 return Constant::getIntegerValue(VTy, Known.One); 266 267 // If all of the demanded bits are known zero on one side, return the other. 268 // These bits cannot contribute to the result of the 'xor'. 269 if (DemandedMask.isSubsetOf(RHSKnown.Zero)) 270 return I->getOperand(0); 271 if (DemandedMask.isSubsetOf(LHSKnown.Zero)) 272 return I->getOperand(1); 273 274 // If all of the demanded bits are known to be zero on one side or the 275 // other, turn this into an *inclusive* or. 276 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 277 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) { 278 Instruction *Or = 279 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1), 280 I->getName()); 281 return InsertNewInstWith(Or, *I); 282 } 283 284 // If all of the demanded bits on one side are known, and all of the set 285 // bits on that side are also known to be set on the other side, turn this 286 // into an AND, as we know the bits will be cleared. 287 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 288 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) && 289 RHSKnown.One.isSubsetOf(LHSKnown.One)) { 290 Constant *AndC = Constant::getIntegerValue(VTy, 291 ~RHSKnown.One & DemandedMask); 292 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC); 293 return InsertNewInstWith(And, *I); 294 } 295 296 // If the RHS is a constant, see if we can change it. Don't alter a -1 297 // constant because that's a canonical 'not' op, and that is better for 298 // combining, SCEV, and codegen. 299 const APInt *C; 300 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) { 301 if ((*C | ~DemandedMask).isAllOnes()) { 302 // Force bits to 1 to create a 'not' op. 303 I->setOperand(1, ConstantInt::getAllOnesValue(VTy)); 304 return I; 305 } 306 // If we can't turn this into a 'not', try to shrink the constant. 307 if (ShrinkDemandedConstant(I, 1, DemandedMask)) 308 return I; 309 } 310 311 // If our LHS is an 'and' and if it has one use, and if any of the bits we 312 // are flipping are known to be set, then the xor is just resetting those 313 // bits to zero. We can just knock out bits from the 'and' and the 'xor', 314 // simplifying both of them. 315 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) { 316 ConstantInt *AndRHS, *XorRHS; 317 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() && 318 match(I->getOperand(1), m_ConstantInt(XorRHS)) && 319 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) && 320 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) { 321 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask); 322 323 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue()); 324 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC); 325 InsertNewInstWith(NewAnd, *I); 326 327 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue()); 328 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC); 329 return InsertNewInstWith(NewXor, *I); 330 } 331 } 332 break; 333 } 334 case Instruction::Select: { 335 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) || 336 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1)) 337 return I; 338 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?"); 339 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?"); 340 341 // If the operands are constants, see if we can simplify them. 342 // This is similar to ShrinkDemandedConstant, but for a select we want to 343 // try to keep the selected constants the same as icmp value constants, if 344 // we can. This helps not break apart (or helps put back together) 345 // canonical patterns like min and max. 346 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo, 347 const APInt &DemandedMask) { 348 const APInt *SelC; 349 if (!match(I->getOperand(OpNo), m_APInt(SelC))) 350 return false; 351 352 // Get the constant out of the ICmp, if there is one. 353 // Only try this when exactly 1 operand is a constant (if both operands 354 // are constant, the icmp should eventually simplify). Otherwise, we may 355 // invert the transform that reduces set bits and infinite-loop. 356 Value *X; 357 const APInt *CmpC; 358 ICmpInst::Predicate Pred; 359 if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) || 360 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth()) 361 return ShrinkDemandedConstant(I, OpNo, DemandedMask); 362 363 // If the constant is already the same as the ICmp, leave it as-is. 364 if (*CmpC == *SelC) 365 return false; 366 // If the constants are not already the same, but can be with the demand 367 // mask, use the constant value from the ICmp. 368 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) { 369 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC)); 370 return true; 371 } 372 return ShrinkDemandedConstant(I, OpNo, DemandedMask); 373 }; 374 if (CanonicalizeSelectConstant(I, 1, DemandedMask) || 375 CanonicalizeSelectConstant(I, 2, DemandedMask)) 376 return I; 377 378 // Only known if known in both the LHS and RHS. 379 Known = KnownBits::commonBits(LHSKnown, RHSKnown); 380 break; 381 } 382 case Instruction::Trunc: { 383 // If we do not demand the high bits of a right-shifted and truncated value, 384 // then we may be able to truncate it before the shift. 385 Value *X; 386 const APInt *C; 387 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) { 388 // The shift amount must be valid (not poison) in the narrow type, and 389 // it must not be greater than the high bits demanded of the result. 390 if (C->ult(VTy->getScalarSizeInBits()) && 391 C->ule(DemandedMask.countLeadingZeros())) { 392 // trunc (lshr X, C) --> lshr (trunc X), C 393 IRBuilderBase::InsertPointGuard Guard(Builder); 394 Builder.SetInsertPoint(I); 395 Value *Trunc = Builder.CreateTrunc(X, VTy); 396 return Builder.CreateLShr(Trunc, C->getZExtValue()); 397 } 398 } 399 } 400 LLVM_FALLTHROUGH; 401 case Instruction::ZExt: { 402 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 403 404 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth); 405 KnownBits InputKnown(SrcBitWidth); 406 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1)) 407 return I; 408 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?"); 409 Known = InputKnown.zextOrTrunc(BitWidth); 410 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 411 break; 412 } 413 case Instruction::BitCast: 414 if (!I->getOperand(0)->getType()->isIntOrIntVectorTy()) 415 return nullptr; // vector->int or fp->int? 416 417 if (auto *DstVTy = dyn_cast<VectorType>(VTy)) { 418 if (auto *SrcVTy = dyn_cast<VectorType>(I->getOperand(0)->getType())) { 419 if (cast<FixedVectorType>(DstVTy)->getNumElements() != 420 cast<FixedVectorType>(SrcVTy)->getNumElements()) 421 // Don't touch a bitcast between vectors of different element counts. 422 return nullptr; 423 } else 424 // Don't touch a scalar-to-vector bitcast. 425 return nullptr; 426 } else if (I->getOperand(0)->getType()->isVectorTy()) 427 // Don't touch a vector-to-scalar bitcast. 428 return nullptr; 429 430 if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1)) 431 return I; 432 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 433 break; 434 case Instruction::SExt: { 435 // Compute the bits in the result that are not present in the input. 436 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits(); 437 438 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth); 439 440 // If any of the sign extended bits are demanded, we know that the sign 441 // bit is demanded. 442 if (DemandedMask.getActiveBits() > SrcBitWidth) 443 InputDemandedBits.setBit(SrcBitWidth-1); 444 445 KnownBits InputKnown(SrcBitWidth); 446 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1)) 447 return I; 448 449 // If the input sign bit is known zero, or if the NewBits are not demanded 450 // convert this into a zero extension. 451 if (InputKnown.isNonNegative() || 452 DemandedMask.getActiveBits() <= SrcBitWidth) { 453 // Convert to ZExt cast. 454 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName()); 455 return InsertNewInstWith(NewCast, *I); 456 } 457 458 // If the sign bit of the input is known set or clear, then we know the 459 // top bits of the result. 460 Known = InputKnown.sext(BitWidth); 461 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 462 break; 463 } 464 case Instruction::Add: 465 if ((DemandedMask & 1) == 0) { 466 // If we do not need the low bit, try to convert bool math to logic: 467 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN 468 Value *X, *Y; 469 if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))), 470 m_OneUse(m_SExt(m_Value(Y))))) && 471 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) { 472 // Truth table for inputs and output signbits: 473 // X:0 | X:1 474 // ---------- 475 // Y:0 | 0 | 0 | 476 // Y:1 | -1 | 0 | 477 // ---------- 478 IRBuilderBase::InsertPointGuard Guard(Builder); 479 Builder.SetInsertPoint(I); 480 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y); 481 return Builder.CreateSExt(AndNot, VTy); 482 } 483 484 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN 485 // TODO: Relax the one-use checks because we are removing an instruction? 486 if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))), 487 m_OneUse(m_SExt(m_Value(Y))))) && 488 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) { 489 // Truth table for inputs and output signbits: 490 // X:0 | X:1 491 // ----------- 492 // Y:0 | -1 | -1 | 493 // Y:1 | -1 | 0 | 494 // ----------- 495 IRBuilderBase::InsertPointGuard Guard(Builder); 496 Builder.SetInsertPoint(I); 497 Value *Or = Builder.CreateOr(X, Y); 498 return Builder.CreateSExt(Or, VTy); 499 } 500 } 501 LLVM_FALLTHROUGH; 502 case Instruction::Sub: { 503 APInt DemandedFromOps; 504 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps)) 505 return I; 506 507 // If we are known to be adding/subtracting zeros to every bit below 508 // the highest demanded bit, we just return the other side. 509 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero)) 510 return I->getOperand(0); 511 // We can't do this with the LHS for subtraction, unless we are only 512 // demanding the LSB. 513 if ((I->getOpcode() == Instruction::Add || DemandedFromOps.isOne()) && 514 DemandedFromOps.isSubsetOf(LHSKnown.Zero)) 515 return I->getOperand(1); 516 517 // Otherwise just compute the known bits of the result. 518 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap(); 519 Known = KnownBits::computeForAddSub(I->getOpcode() == Instruction::Add, 520 NSW, LHSKnown, RHSKnown); 521 break; 522 } 523 case Instruction::Mul: { 524 APInt DemandedFromOps; 525 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps)) 526 return I; 527 528 if (DemandedMask.isPowerOf2()) { 529 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1. 530 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is 531 // odd (has LSB set), then the left-shifted low bit of X is the answer. 532 unsigned CTZ = DemandedMask.countTrailingZeros(); 533 const APInt *C; 534 if (match(I->getOperand(1), m_APInt(C)) && 535 C->countTrailingZeros() == CTZ) { 536 Constant *ShiftC = ConstantInt::get(VTy, CTZ); 537 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC); 538 return InsertNewInstWith(Shl, *I); 539 } 540 } 541 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because: 542 // X * X is odd iff X is odd. 543 // 'Quadratic Reciprocity': X * X -> 0 for bit[1] 544 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) { 545 Constant *One = ConstantInt::get(VTy, 1); 546 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One); 547 return InsertNewInstWith(And1, *I); 548 } 549 550 computeKnownBits(I, Known, Depth, CxtI); 551 break; 552 } 553 case Instruction::Shl: { 554 const APInt *SA; 555 if (match(I->getOperand(1), m_APInt(SA))) { 556 const APInt *ShrAmt; 557 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt)))) 558 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0))) 559 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA, 560 DemandedMask, Known)) 561 return R; 562 563 // TODO: If we only want bits that already match the signbit then we don't 564 // need to shift. 565 566 // If we can pre-shift a right-shifted constant to the left without 567 // losing any high bits amd we don't demand the low bits, then eliminate 568 // the left-shift: 569 // (C >> X) << LeftShiftAmtC --> (C << RightShiftAmtC) >> X 570 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 571 Value *X; 572 Constant *C; 573 if (DemandedMask.countTrailingZeros() >= ShiftAmt && 574 match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) { 575 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt); 576 Constant *NewC = ConstantExpr::getShl(C, LeftShiftAmtC); 577 if (ConstantExpr::getLShr(NewC, LeftShiftAmtC) == C) { 578 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X); 579 return InsertNewInstWith(Lshr, *I); 580 } 581 } 582 583 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt)); 584 585 // If the shift is NUW/NSW, then it does demand the high bits. 586 ShlOperator *IOp = cast<ShlOperator>(I); 587 if (IOp->hasNoSignedWrap()) 588 DemandedMaskIn.setHighBits(ShiftAmt+1); 589 else if (IOp->hasNoUnsignedWrap()) 590 DemandedMaskIn.setHighBits(ShiftAmt); 591 592 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 593 return I; 594 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 595 596 bool SignBitZero = Known.Zero.isSignBitSet(); 597 bool SignBitOne = Known.One.isSignBitSet(); 598 Known.Zero <<= ShiftAmt; 599 Known.One <<= ShiftAmt; 600 // low bits known zero. 601 if (ShiftAmt) 602 Known.Zero.setLowBits(ShiftAmt); 603 604 // If this shift has "nsw" keyword, then the result is either a poison 605 // value or has the same sign bit as the first operand. 606 if (IOp->hasNoSignedWrap()) { 607 if (SignBitZero) 608 Known.Zero.setSignBit(); 609 else if (SignBitOne) 610 Known.One.setSignBit(); 611 if (Known.hasConflict()) 612 return UndefValue::get(VTy); 613 } 614 } else { 615 // This is a variable shift, so we can't shift the demand mask by a known 616 // amount. But if we are not demanding high bits, then we are not 617 // demanding those bits from the pre-shifted operand either. 618 if (unsigned CTLZ = DemandedMask.countLeadingZeros()) { 619 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ)); 620 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) { 621 // We can't guarantee that nsw/nuw hold after simplifying the operand. 622 I->dropPoisonGeneratingFlags(); 623 return I; 624 } 625 } 626 computeKnownBits(I, Known, Depth, CxtI); 627 } 628 break; 629 } 630 case Instruction::LShr: { 631 const APInt *SA; 632 if (match(I->getOperand(1), m_APInt(SA))) { 633 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 634 635 // If we are just demanding the shifted sign bit and below, then this can 636 // be treated as an ASHR in disguise. 637 if (DemandedMask.countLeadingZeros() >= ShiftAmt) { 638 // If we only want bits that already match the signbit then we don't 639 // need to shift. 640 unsigned NumHiDemandedBits = 641 BitWidth - DemandedMask.countTrailingZeros(); 642 unsigned SignBits = 643 ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI); 644 if (SignBits >= NumHiDemandedBits) 645 return I->getOperand(0); 646 647 // If we can pre-shift a left-shifted constant to the right without 648 // losing any low bits (we already know we don't demand the high bits), 649 // then eliminate the right-shift: 650 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X 651 Value *X; 652 Constant *C; 653 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) { 654 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt); 655 Constant *NewC = ConstantExpr::getLShr(C, RightShiftAmtC); 656 if (ConstantExpr::getShl(NewC, RightShiftAmtC) == C) { 657 Instruction *Shl = BinaryOperator::CreateShl(NewC, X); 658 return InsertNewInstWith(Shl, *I); 659 } 660 } 661 } 662 663 // Unsigned shift right. 664 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); 665 666 // If the shift is exact, then it does demand the low bits (and knows that 667 // they are zero). 668 if (cast<LShrOperator>(I)->isExact()) 669 DemandedMaskIn.setLowBits(ShiftAmt); 670 671 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 672 return I; 673 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 674 Known.Zero.lshrInPlace(ShiftAmt); 675 Known.One.lshrInPlace(ShiftAmt); 676 if (ShiftAmt) 677 Known.Zero.setHighBits(ShiftAmt); // high bits known zero. 678 } else { 679 computeKnownBits(I, Known, Depth, CxtI); 680 } 681 break; 682 } 683 case Instruction::AShr: { 684 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI); 685 686 // If we only want bits that already match the signbit then we don't need 687 // to shift. 688 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countTrailingZeros(); 689 if (SignBits >= NumHiDemandedBits) 690 return I->getOperand(0); 691 692 // If this is an arithmetic shift right and only the low-bit is set, we can 693 // always convert this into a logical shr, even if the shift amount is 694 // variable. The low bit of the shift cannot be an input sign bit unless 695 // the shift amount is >= the size of the datatype, which is undefined. 696 if (DemandedMask.isOne()) { 697 // Perform the logical shift right. 698 Instruction *NewVal = BinaryOperator::CreateLShr( 699 I->getOperand(0), I->getOperand(1), I->getName()); 700 return InsertNewInstWith(NewVal, *I); 701 } 702 703 const APInt *SA; 704 if (match(I->getOperand(1), m_APInt(SA))) { 705 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1); 706 707 // Signed shift right. 708 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt)); 709 // If any of the high bits are demanded, we should set the sign bit as 710 // demanded. 711 if (DemandedMask.countLeadingZeros() <= ShiftAmt) 712 DemandedMaskIn.setSignBit(); 713 714 // If the shift is exact, then it does demand the low bits (and knows that 715 // they are zero). 716 if (cast<AShrOperator>(I)->isExact()) 717 DemandedMaskIn.setLowBits(ShiftAmt); 718 719 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) 720 return I; 721 722 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 723 // Compute the new bits that are at the top now plus sign bits. 724 APInt HighBits(APInt::getHighBitsSet( 725 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth))); 726 Known.Zero.lshrInPlace(ShiftAmt); 727 Known.One.lshrInPlace(ShiftAmt); 728 729 // If the input sign bit is known to be zero, or if none of the top bits 730 // are demanded, turn this into an unsigned shift right. 731 assert(BitWidth > ShiftAmt && "Shift amount not saturated?"); 732 if (Known.Zero[BitWidth-ShiftAmt-1] || 733 !DemandedMask.intersects(HighBits)) { 734 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0), 735 I->getOperand(1)); 736 LShr->setIsExact(cast<BinaryOperator>(I)->isExact()); 737 return InsertNewInstWith(LShr, *I); 738 } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one. 739 Known.One |= HighBits; 740 } 741 } else { 742 computeKnownBits(I, Known, Depth, CxtI); 743 } 744 break; 745 } 746 case Instruction::UDiv: { 747 // UDiv doesn't demand low bits that are zero in the divisor. 748 const APInt *SA; 749 if (match(I->getOperand(1), m_APInt(SA))) { 750 // If the shift is exact, then it does demand the low bits. 751 if (cast<UDivOperator>(I)->isExact()) 752 break; 753 754 // FIXME: Take the demanded mask of the result into account. 755 unsigned RHSTrailingZeros = SA->countTrailingZeros(); 756 APInt DemandedMaskIn = 757 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros); 758 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1)) 759 return I; 760 761 // Propagate zero bits from the input. 762 Known.Zero.setHighBits(std::min( 763 BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros)); 764 } else { 765 computeKnownBits(I, Known, Depth, CxtI); 766 } 767 break; 768 } 769 case Instruction::SRem: { 770 const APInt *Rem; 771 if (match(I->getOperand(1), m_APInt(Rem))) { 772 // X % -1 demands all the bits because we don't want to introduce 773 // INT_MIN % -1 (== undef) by accident. 774 if (Rem->isAllOnes()) 775 break; 776 APInt RA = Rem->abs(); 777 if (RA.isPowerOf2()) { 778 if (DemandedMask.ult(RA)) // srem won't affect demanded bits 779 return I->getOperand(0); 780 781 APInt LowBits = RA - 1; 782 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth); 783 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1)) 784 return I; 785 786 // The low bits of LHS are unchanged by the srem. 787 Known.Zero = LHSKnown.Zero & LowBits; 788 Known.One = LHSKnown.One & LowBits; 789 790 // If LHS is non-negative or has all low bits zero, then the upper bits 791 // are all zero. 792 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero)) 793 Known.Zero |= ~LowBits; 794 795 // If LHS is negative and not all low bits are zero, then the upper bits 796 // are all one. 797 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One)) 798 Known.One |= ~LowBits; 799 800 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 801 break; 802 } 803 } 804 805 // The sign bit is the LHS's sign bit, except when the result of the 806 // remainder is zero. 807 if (DemandedMask.isSignBitSet()) { 808 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI); 809 // If it's known zero, our sign bit is also zero. 810 if (LHSKnown.isNonNegative()) 811 Known.makeNonNegative(); 812 } 813 break; 814 } 815 case Instruction::URem: { 816 KnownBits Known2(BitWidth); 817 APInt AllOnes = APInt::getAllOnes(BitWidth); 818 if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) || 819 SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1)) 820 return I; 821 822 unsigned Leaders = Known2.countMinLeadingZeros(); 823 Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask; 824 break; 825 } 826 case Instruction::Call: { 827 bool KnownBitsComputed = false; 828 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 829 switch (II->getIntrinsicID()) { 830 case Intrinsic::abs: { 831 if (DemandedMask == 1) 832 return II->getArgOperand(0); 833 break; 834 } 835 case Intrinsic::ctpop: { 836 // Checking if the number of clear bits is odd (parity)? If the type has 837 // an even number of bits, that's the same as checking if the number of 838 // set bits is odd, so we can eliminate the 'not' op. 839 Value *X; 840 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 && 841 match(II->getArgOperand(0), m_Not(m_Value(X)))) { 842 Function *Ctpop = Intrinsic::getDeclaration( 843 II->getModule(), Intrinsic::ctpop, VTy); 844 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), *I); 845 } 846 break; 847 } 848 case Intrinsic::bswap: { 849 // If the only bits demanded come from one byte of the bswap result, 850 // just shift the input byte into position to eliminate the bswap. 851 unsigned NLZ = DemandedMask.countLeadingZeros(); 852 unsigned NTZ = DemandedMask.countTrailingZeros(); 853 854 // Round NTZ down to the next byte. If we have 11 trailing zeros, then 855 // we need all the bits down to bit 8. Likewise, round NLZ. If we 856 // have 14 leading zeros, round to 8. 857 NLZ = alignDown(NLZ, 8); 858 NTZ = alignDown(NTZ, 8); 859 // If we need exactly one byte, we can do this transformation. 860 if (BitWidth - NLZ - NTZ == 8) { 861 // Replace this with either a left or right shift to get the byte into 862 // the right place. 863 Instruction *NewVal; 864 if (NLZ > NTZ) 865 NewVal = BinaryOperator::CreateLShr( 866 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ)); 867 else 868 NewVal = BinaryOperator::CreateShl( 869 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ)); 870 NewVal->takeName(I); 871 return InsertNewInstWith(NewVal, *I); 872 } 873 break; 874 } 875 case Intrinsic::fshr: 876 case Intrinsic::fshl: { 877 const APInt *SA; 878 if (!match(I->getOperand(2), m_APInt(SA))) 879 break; 880 881 // Normalize to funnel shift left. APInt shifts of BitWidth are well- 882 // defined, so no need to special-case zero shifts here. 883 uint64_t ShiftAmt = SA->urem(BitWidth); 884 if (II->getIntrinsicID() == Intrinsic::fshr) 885 ShiftAmt = BitWidth - ShiftAmt; 886 887 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt)); 888 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt)); 889 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) || 890 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1)) 891 return I; 892 893 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) | 894 RHSKnown.Zero.lshr(BitWidth - ShiftAmt); 895 Known.One = LHSKnown.One.shl(ShiftAmt) | 896 RHSKnown.One.lshr(BitWidth - ShiftAmt); 897 KnownBitsComputed = true; 898 break; 899 } 900 case Intrinsic::umax: { 901 // UMax(A, C) == A if ... 902 // The lowest non-zero bit of DemandMask is higher than the highest 903 // non-zero bit of C. 904 const APInt *C; 905 unsigned CTZ = DemandedMask.countTrailingZeros(); 906 if (match(II->getArgOperand(1), m_APInt(C)) && 907 CTZ >= C->getActiveBits()) 908 return II->getArgOperand(0); 909 break; 910 } 911 case Intrinsic::umin: { 912 // UMin(A, C) == A if ... 913 // The lowest non-zero bit of DemandMask is higher than the highest 914 // non-one bit of C. 915 // This comes from using DeMorgans on the above umax example. 916 const APInt *C; 917 unsigned CTZ = DemandedMask.countTrailingZeros(); 918 if (match(II->getArgOperand(1), m_APInt(C)) && 919 CTZ >= C->getBitWidth() - C->countLeadingOnes()) 920 return II->getArgOperand(0); 921 break; 922 } 923 default: { 924 // Handle target specific intrinsics 925 Optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic( 926 *II, DemandedMask, Known, KnownBitsComputed); 927 if (V) 928 return V.value(); 929 break; 930 } 931 } 932 } 933 934 if (!KnownBitsComputed) 935 computeKnownBits(V, Known, Depth, CxtI); 936 break; 937 } 938 } 939 940 // If the client is only demanding bits that we know, return the known 941 // constant. 942 if (DemandedMask.isSubsetOf(Known.Zero|Known.One)) 943 return Constant::getIntegerValue(VTy, Known.One); 944 return nullptr; 945 } 946 947 /// Helper routine of SimplifyDemandedUseBits. It computes Known 948 /// bits. It also tries to handle simplifications that can be done based on 949 /// DemandedMask, but without modifying the Instruction. 950 Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits( 951 Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth, 952 Instruction *CxtI) { 953 unsigned BitWidth = DemandedMask.getBitWidth(); 954 Type *ITy = I->getType(); 955 956 KnownBits LHSKnown(BitWidth); 957 KnownBits RHSKnown(BitWidth); 958 959 // Despite the fact that we can't simplify this instruction in all User's 960 // context, we can at least compute the known bits, and we can 961 // do simplifications that apply to *just* the one user if we know that 962 // this instruction has a simpler value in that context. 963 switch (I->getOpcode()) { 964 case Instruction::And: { 965 // If either the LHS or the RHS are Zero, the result is zero. 966 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 967 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 968 CxtI); 969 970 Known = LHSKnown & RHSKnown; 971 972 // If the client is only demanding bits that we know, return the known 973 // constant. 974 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 975 return Constant::getIntegerValue(ITy, Known.One); 976 977 // If all of the demanded bits are known 1 on one side, return the other. 978 // These bits cannot contribute to the result of the 'and' in this 979 // context. 980 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One)) 981 return I->getOperand(0); 982 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One)) 983 return I->getOperand(1); 984 985 break; 986 } 987 case Instruction::Or: { 988 // We can simplify (X|Y) -> X or Y in the user's context if we know that 989 // only bits from X or Y are demanded. 990 991 // If either the LHS or the RHS are One, the result is One. 992 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 993 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 994 CxtI); 995 996 Known = LHSKnown | RHSKnown; 997 998 // If the client is only demanding bits that we know, return the known 999 // constant. 1000 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 1001 return Constant::getIntegerValue(ITy, Known.One); 1002 1003 // If all of the demanded bits are known zero on one side, return the 1004 // other. These bits cannot contribute to the result of the 'or' in this 1005 // context. 1006 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero)) 1007 return I->getOperand(0); 1008 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero)) 1009 return I->getOperand(1); 1010 1011 break; 1012 } 1013 case Instruction::Xor: { 1014 // We can simplify (X^Y) -> X or Y in the user's context if we know that 1015 // only bits from X or Y are demanded. 1016 1017 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI); 1018 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, 1019 CxtI); 1020 1021 Known = LHSKnown ^ RHSKnown; 1022 1023 // If the client is only demanding bits that we know, return the known 1024 // constant. 1025 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 1026 return Constant::getIntegerValue(ITy, Known.One); 1027 1028 // If all of the demanded bits are known zero on one side, return the 1029 // other. 1030 if (DemandedMask.isSubsetOf(RHSKnown.Zero)) 1031 return I->getOperand(0); 1032 if (DemandedMask.isSubsetOf(LHSKnown.Zero)) 1033 return I->getOperand(1); 1034 1035 break; 1036 } 1037 case Instruction::AShr: { 1038 // Compute the Known bits to simplify things downstream. 1039 computeKnownBits(I, Known, Depth, CxtI); 1040 1041 // If this user is only demanding bits that we know, return the known 1042 // constant. 1043 if (DemandedMask.isSubsetOf(Known.Zero | Known.One)) 1044 return Constant::getIntegerValue(ITy, Known.One); 1045 1046 // If the right shift operand 0 is a result of a left shift by the same 1047 // amount, this is probably a zero/sign extension, which may be unnecessary, 1048 // if we do not demand any of the new sign bits. So, return the original 1049 // operand instead. 1050 const APInt *ShiftRC; 1051 const APInt *ShiftLC; 1052 Value *X; 1053 unsigned BitWidth = DemandedMask.getBitWidth(); 1054 if (match(I, 1055 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) && 1056 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) && 1057 DemandedMask.isSubsetOf(APInt::getLowBitsSet( 1058 BitWidth, BitWidth - ShiftRC->getZExtValue()))) { 1059 return X; 1060 } 1061 1062 break; 1063 } 1064 default: 1065 // Compute the Known bits to simplify things downstream. 1066 computeKnownBits(I, Known, Depth, CxtI); 1067 1068 // If this user is only demanding bits that we know, return the known 1069 // constant. 1070 if (DemandedMask.isSubsetOf(Known.Zero|Known.One)) 1071 return Constant::getIntegerValue(ITy, Known.One); 1072 1073 break; 1074 } 1075 1076 return nullptr; 1077 } 1078 1079 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify 1080 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into 1081 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign 1082 /// of "C2-C1". 1083 /// 1084 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1, 1085 /// ..., bn}, without considering the specific value X is holding. 1086 /// This transformation is legal iff one of following conditions is hold: 1087 /// 1) All the bit in S are 0, in this case E1 == E2. 1088 /// 2) We don't care those bits in S, per the input DemandedMask. 1089 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the 1090 /// rest bits. 1091 /// 1092 /// Currently we only test condition 2). 1093 /// 1094 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was 1095 /// not successful. 1096 Value *InstCombinerImpl::simplifyShrShlDemandedBits( 1097 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl, 1098 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) { 1099 if (!ShlOp1 || !ShrOp1) 1100 return nullptr; // No-op. 1101 1102 Value *VarX = Shr->getOperand(0); 1103 Type *Ty = VarX->getType(); 1104 unsigned BitWidth = Ty->getScalarSizeInBits(); 1105 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth)) 1106 return nullptr; // Undef. 1107 1108 unsigned ShlAmt = ShlOp1.getZExtValue(); 1109 unsigned ShrAmt = ShrOp1.getZExtValue(); 1110 1111 Known.One.clearAllBits(); 1112 Known.Zero.setLowBits(ShlAmt - 1); 1113 Known.Zero &= DemandedMask; 1114 1115 APInt BitMask1(APInt::getAllOnes(BitWidth)); 1116 APInt BitMask2(APInt::getAllOnes(BitWidth)); 1117 1118 bool isLshr = (Shr->getOpcode() == Instruction::LShr); 1119 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) : 1120 (BitMask1.ashr(ShrAmt) << ShlAmt); 1121 1122 if (ShrAmt <= ShlAmt) { 1123 BitMask2 <<= (ShlAmt - ShrAmt); 1124 } else { 1125 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt): 1126 BitMask2.ashr(ShrAmt - ShlAmt); 1127 } 1128 1129 // Check if condition-2 (see the comment to this function) is satified. 1130 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) { 1131 if (ShrAmt == ShlAmt) 1132 return VarX; 1133 1134 if (!Shr->hasOneUse()) 1135 return nullptr; 1136 1137 BinaryOperator *New; 1138 if (ShrAmt < ShlAmt) { 1139 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt); 1140 New = BinaryOperator::CreateShl(VarX, Amt); 1141 BinaryOperator *Orig = cast<BinaryOperator>(Shl); 1142 New->setHasNoSignedWrap(Orig->hasNoSignedWrap()); 1143 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap()); 1144 } else { 1145 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt); 1146 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) : 1147 BinaryOperator::CreateAShr(VarX, Amt); 1148 if (cast<BinaryOperator>(Shr)->isExact()) 1149 New->setIsExact(true); 1150 } 1151 1152 return InsertNewInstWith(New, *Shl); 1153 } 1154 1155 return nullptr; 1156 } 1157 1158 /// The specified value produces a vector with any number of elements. 1159 /// This method analyzes which elements of the operand are undef or poison and 1160 /// returns that information in UndefElts. 1161 /// 1162 /// DemandedElts contains the set of elements that are actually used by the 1163 /// caller, and by default (AllowMultipleUsers equals false) the value is 1164 /// simplified only if it has a single caller. If AllowMultipleUsers is set 1165 /// to true, DemandedElts refers to the union of sets of elements that are 1166 /// used by all callers. 1167 /// 1168 /// If the information about demanded elements can be used to simplify the 1169 /// operation, the operation is simplified, then the resultant value is 1170 /// returned. This returns null if no change was made. 1171 Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V, 1172 APInt DemandedElts, 1173 APInt &UndefElts, 1174 unsigned Depth, 1175 bool AllowMultipleUsers) { 1176 // Cannot analyze scalable type. The number of vector elements is not a 1177 // compile-time constant. 1178 if (isa<ScalableVectorType>(V->getType())) 1179 return nullptr; 1180 1181 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements(); 1182 APInt EltMask(APInt::getAllOnes(VWidth)); 1183 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!"); 1184 1185 if (match(V, m_Undef())) { 1186 // If the entire vector is undef or poison, just return this info. 1187 UndefElts = EltMask; 1188 return nullptr; 1189 } 1190 1191 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison. 1192 UndefElts = EltMask; 1193 return PoisonValue::get(V->getType()); 1194 } 1195 1196 UndefElts = 0; 1197 1198 if (auto *C = dyn_cast<Constant>(V)) { 1199 // Check if this is identity. If so, return 0 since we are not simplifying 1200 // anything. 1201 if (DemandedElts.isAllOnes()) 1202 return nullptr; 1203 1204 Type *EltTy = cast<VectorType>(V->getType())->getElementType(); 1205 Constant *Poison = PoisonValue::get(EltTy); 1206 SmallVector<Constant*, 16> Elts; 1207 for (unsigned i = 0; i != VWidth; ++i) { 1208 if (!DemandedElts[i]) { // If not demanded, set to poison. 1209 Elts.push_back(Poison); 1210 UndefElts.setBit(i); 1211 continue; 1212 } 1213 1214 Constant *Elt = C->getAggregateElement(i); 1215 if (!Elt) return nullptr; 1216 1217 Elts.push_back(Elt); 1218 if (isa<UndefValue>(Elt)) // Already undef or poison. 1219 UndefElts.setBit(i); 1220 } 1221 1222 // If we changed the constant, return it. 1223 Constant *NewCV = ConstantVector::get(Elts); 1224 return NewCV != C ? NewCV : nullptr; 1225 } 1226 1227 // Limit search depth. 1228 if (Depth == 10) 1229 return nullptr; 1230 1231 if (!AllowMultipleUsers) { 1232 // If multiple users are using the root value, proceed with 1233 // simplification conservatively assuming that all elements 1234 // are needed. 1235 if (!V->hasOneUse()) { 1236 // Quit if we find multiple users of a non-root value though. 1237 // They'll be handled when it's their turn to be visited by 1238 // the main instcombine process. 1239 if (Depth != 0) 1240 // TODO: Just compute the UndefElts information recursively. 1241 return nullptr; 1242 1243 // Conservatively assume that all elements are needed. 1244 DemandedElts = EltMask; 1245 } 1246 } 1247 1248 Instruction *I = dyn_cast<Instruction>(V); 1249 if (!I) return nullptr; // Only analyze instructions. 1250 1251 bool MadeChange = false; 1252 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum, 1253 APInt Demanded, APInt &Undef) { 1254 auto *II = dyn_cast<IntrinsicInst>(Inst); 1255 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum); 1256 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) { 1257 replaceOperand(*Inst, OpNum, V); 1258 MadeChange = true; 1259 } 1260 }; 1261 1262 APInt UndefElts2(VWidth, 0); 1263 APInt UndefElts3(VWidth, 0); 1264 switch (I->getOpcode()) { 1265 default: break; 1266 1267 case Instruction::GetElementPtr: { 1268 // The LangRef requires that struct geps have all constant indices. As 1269 // such, we can't convert any operand to partial undef. 1270 auto mayIndexStructType = [](GetElementPtrInst &GEP) { 1271 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP); 1272 I != E; I++) 1273 if (I.isStruct()) 1274 return true; 1275 return false; 1276 }; 1277 if (mayIndexStructType(cast<GetElementPtrInst>(*I))) 1278 break; 1279 1280 // Conservatively track the demanded elements back through any vector 1281 // operands we may have. We know there must be at least one, or we 1282 // wouldn't have a vector result to get here. Note that we intentionally 1283 // merge the undef bits here since gepping with either an poison base or 1284 // index results in poison. 1285 for (unsigned i = 0; i < I->getNumOperands(); i++) { 1286 if (i == 0 ? match(I->getOperand(i), m_Undef()) 1287 : match(I->getOperand(i), m_Poison())) { 1288 // If the entire vector is undefined, just return this info. 1289 UndefElts = EltMask; 1290 return nullptr; 1291 } 1292 if (I->getOperand(i)->getType()->isVectorTy()) { 1293 APInt UndefEltsOp(VWidth, 0); 1294 simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp); 1295 // gep(x, undef) is not undef, so skip considering idx ops here 1296 // Note that we could propagate poison, but we can't distinguish between 1297 // undef & poison bits ATM 1298 if (i == 0) 1299 UndefElts |= UndefEltsOp; 1300 } 1301 } 1302 1303 break; 1304 } 1305 case Instruction::InsertElement: { 1306 // If this is a variable index, we don't know which element it overwrites. 1307 // demand exactly the same input as we produce. 1308 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2)); 1309 if (!Idx) { 1310 // Note that we can't propagate undef elt info, because we don't know 1311 // which elt is getting updated. 1312 simplifyAndSetOp(I, 0, DemandedElts, UndefElts2); 1313 break; 1314 } 1315 1316 // The element inserted overwrites whatever was there, so the input demanded 1317 // set is simpler than the output set. 1318 unsigned IdxNo = Idx->getZExtValue(); 1319 APInt PreInsertDemandedElts = DemandedElts; 1320 if (IdxNo < VWidth) 1321 PreInsertDemandedElts.clearBit(IdxNo); 1322 1323 // If we only demand the element that is being inserted and that element 1324 // was extracted from the same index in another vector with the same type, 1325 // replace this insert with that other vector. 1326 // Note: This is attempted before the call to simplifyAndSetOp because that 1327 // may change UndefElts to a value that does not match with Vec. 1328 Value *Vec; 1329 if (PreInsertDemandedElts == 0 && 1330 match(I->getOperand(1), 1331 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) && 1332 Vec->getType() == I->getType()) { 1333 return Vec; 1334 } 1335 1336 simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts); 1337 1338 // If this is inserting an element that isn't demanded, remove this 1339 // insertelement. 1340 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) { 1341 Worklist.push(I); 1342 return I->getOperand(0); 1343 } 1344 1345 // The inserted element is defined. 1346 UndefElts.clearBit(IdxNo); 1347 break; 1348 } 1349 case Instruction::ShuffleVector: { 1350 auto *Shuffle = cast<ShuffleVectorInst>(I); 1351 assert(Shuffle->getOperand(0)->getType() == 1352 Shuffle->getOperand(1)->getType() && 1353 "Expected shuffle operands to have same type"); 1354 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType()) 1355 ->getNumElements(); 1356 // Handle trivial case of a splat. Only check the first element of LHS 1357 // operand. 1358 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) && 1359 DemandedElts.isAllOnes()) { 1360 if (!match(I->getOperand(1), m_Undef())) { 1361 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType())); 1362 MadeChange = true; 1363 } 1364 APInt LeftDemanded(OpWidth, 1); 1365 APInt LHSUndefElts(OpWidth, 0); 1366 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts); 1367 if (LHSUndefElts[0]) 1368 UndefElts = EltMask; 1369 else 1370 UndefElts.clearAllBits(); 1371 break; 1372 } 1373 1374 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0); 1375 for (unsigned i = 0; i < VWidth; i++) { 1376 if (DemandedElts[i]) { 1377 unsigned MaskVal = Shuffle->getMaskValue(i); 1378 if (MaskVal != -1u) { 1379 assert(MaskVal < OpWidth * 2 && 1380 "shufflevector mask index out of range!"); 1381 if (MaskVal < OpWidth) 1382 LeftDemanded.setBit(MaskVal); 1383 else 1384 RightDemanded.setBit(MaskVal - OpWidth); 1385 } 1386 } 1387 } 1388 1389 APInt LHSUndefElts(OpWidth, 0); 1390 simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts); 1391 1392 APInt RHSUndefElts(OpWidth, 0); 1393 simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts); 1394 1395 // If this shuffle does not change the vector length and the elements 1396 // demanded by this shuffle are an identity mask, then this shuffle is 1397 // unnecessary. 1398 // 1399 // We are assuming canonical form for the mask, so the source vector is 1400 // operand 0 and operand 1 is not used. 1401 // 1402 // Note that if an element is demanded and this shuffle mask is undefined 1403 // for that element, then the shuffle is not considered an identity 1404 // operation. The shuffle prevents poison from the operand vector from 1405 // leaking to the result by replacing poison with an undefined value. 1406 if (VWidth == OpWidth) { 1407 bool IsIdentityShuffle = true; 1408 for (unsigned i = 0; i < VWidth; i++) { 1409 unsigned MaskVal = Shuffle->getMaskValue(i); 1410 if (DemandedElts[i] && i != MaskVal) { 1411 IsIdentityShuffle = false; 1412 break; 1413 } 1414 } 1415 if (IsIdentityShuffle) 1416 return Shuffle->getOperand(0); 1417 } 1418 1419 bool NewUndefElts = false; 1420 unsigned LHSIdx = -1u, LHSValIdx = -1u; 1421 unsigned RHSIdx = -1u, RHSValIdx = -1u; 1422 bool LHSUniform = true; 1423 bool RHSUniform = true; 1424 for (unsigned i = 0; i < VWidth; i++) { 1425 unsigned MaskVal = Shuffle->getMaskValue(i); 1426 if (MaskVal == -1u) { 1427 UndefElts.setBit(i); 1428 } else if (!DemandedElts[i]) { 1429 NewUndefElts = true; 1430 UndefElts.setBit(i); 1431 } else if (MaskVal < OpWidth) { 1432 if (LHSUndefElts[MaskVal]) { 1433 NewUndefElts = true; 1434 UndefElts.setBit(i); 1435 } else { 1436 LHSIdx = LHSIdx == -1u ? i : OpWidth; 1437 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth; 1438 LHSUniform = LHSUniform && (MaskVal == i); 1439 } 1440 } else { 1441 if (RHSUndefElts[MaskVal - OpWidth]) { 1442 NewUndefElts = true; 1443 UndefElts.setBit(i); 1444 } else { 1445 RHSIdx = RHSIdx == -1u ? i : OpWidth; 1446 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth; 1447 RHSUniform = RHSUniform && (MaskVal - OpWidth == i); 1448 } 1449 } 1450 } 1451 1452 // Try to transform shuffle with constant vector and single element from 1453 // this constant vector to single insertelement instruction. 1454 // shufflevector V, C, <v1, v2, .., ci, .., vm> -> 1455 // insertelement V, C[ci], ci-n 1456 if (OpWidth == 1457 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) { 1458 Value *Op = nullptr; 1459 Constant *Value = nullptr; 1460 unsigned Idx = -1u; 1461 1462 // Find constant vector with the single element in shuffle (LHS or RHS). 1463 if (LHSIdx < OpWidth && RHSUniform) { 1464 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) { 1465 Op = Shuffle->getOperand(1); 1466 Value = CV->getOperand(LHSValIdx); 1467 Idx = LHSIdx; 1468 } 1469 } 1470 if (RHSIdx < OpWidth && LHSUniform) { 1471 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) { 1472 Op = Shuffle->getOperand(0); 1473 Value = CV->getOperand(RHSValIdx); 1474 Idx = RHSIdx; 1475 } 1476 } 1477 // Found constant vector with single element - convert to insertelement. 1478 if (Op && Value) { 1479 Instruction *New = InsertElementInst::Create( 1480 Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx), 1481 Shuffle->getName()); 1482 InsertNewInstWith(New, *Shuffle); 1483 return New; 1484 } 1485 } 1486 if (NewUndefElts) { 1487 // Add additional discovered undefs. 1488 SmallVector<int, 16> Elts; 1489 for (unsigned i = 0; i < VWidth; ++i) { 1490 if (UndefElts[i]) 1491 Elts.push_back(UndefMaskElem); 1492 else 1493 Elts.push_back(Shuffle->getMaskValue(i)); 1494 } 1495 Shuffle->setShuffleMask(Elts); 1496 MadeChange = true; 1497 } 1498 break; 1499 } 1500 case Instruction::Select: { 1501 // If this is a vector select, try to transform the select condition based 1502 // on the current demanded elements. 1503 SelectInst *Sel = cast<SelectInst>(I); 1504 if (Sel->getCondition()->getType()->isVectorTy()) { 1505 // TODO: We are not doing anything with UndefElts based on this call. 1506 // It is overwritten below based on the other select operands. If an 1507 // element of the select condition is known undef, then we are free to 1508 // choose the output value from either arm of the select. If we know that 1509 // one of those values is undef, then the output can be undef. 1510 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1511 } 1512 1513 // Next, see if we can transform the arms of the select. 1514 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts); 1515 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) { 1516 for (unsigned i = 0; i < VWidth; i++) { 1517 // isNullValue() always returns false when called on a ConstantExpr. 1518 // Skip constant expressions to avoid propagating incorrect information. 1519 Constant *CElt = CV->getAggregateElement(i); 1520 if (isa<ConstantExpr>(CElt)) 1521 continue; 1522 // TODO: If a select condition element is undef, we can demand from 1523 // either side. If one side is known undef, choosing that side would 1524 // propagate undef. 1525 if (CElt->isNullValue()) 1526 DemandedLHS.clearBit(i); 1527 else 1528 DemandedRHS.clearBit(i); 1529 } 1530 } 1531 1532 simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2); 1533 simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3); 1534 1535 // Output elements are undefined if the element from each arm is undefined. 1536 // TODO: This can be improved. See comment in select condition handling. 1537 UndefElts = UndefElts2 & UndefElts3; 1538 break; 1539 } 1540 case Instruction::BitCast: { 1541 // Vector->vector casts only. 1542 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType()); 1543 if (!VTy) break; 1544 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements(); 1545 APInt InputDemandedElts(InVWidth, 0); 1546 UndefElts2 = APInt(InVWidth, 0); 1547 unsigned Ratio; 1548 1549 if (VWidth == InVWidth) { 1550 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same 1551 // elements as are demanded of us. 1552 Ratio = 1; 1553 InputDemandedElts = DemandedElts; 1554 } else if ((VWidth % InVWidth) == 0) { 1555 // If the number of elements in the output is a multiple of the number of 1556 // elements in the input then an input element is live if any of the 1557 // corresponding output elements are live. 1558 Ratio = VWidth / InVWidth; 1559 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) 1560 if (DemandedElts[OutIdx]) 1561 InputDemandedElts.setBit(OutIdx / Ratio); 1562 } else if ((InVWidth % VWidth) == 0) { 1563 // If the number of elements in the input is a multiple of the number of 1564 // elements in the output then an input element is live if the 1565 // corresponding output element is live. 1566 Ratio = InVWidth / VWidth; 1567 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx) 1568 if (DemandedElts[InIdx / Ratio]) 1569 InputDemandedElts.setBit(InIdx); 1570 } else { 1571 // Unsupported so far. 1572 break; 1573 } 1574 1575 simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2); 1576 1577 if (VWidth == InVWidth) { 1578 UndefElts = UndefElts2; 1579 } else if ((VWidth % InVWidth) == 0) { 1580 // If the number of elements in the output is a multiple of the number of 1581 // elements in the input then an output element is undef if the 1582 // corresponding input element is undef. 1583 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) 1584 if (UndefElts2[OutIdx / Ratio]) 1585 UndefElts.setBit(OutIdx); 1586 } else if ((InVWidth % VWidth) == 0) { 1587 // If the number of elements in the input is a multiple of the number of 1588 // elements in the output then an output element is undef if all of the 1589 // corresponding input elements are undef. 1590 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) { 1591 APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio); 1592 if (SubUndef.countPopulation() == Ratio) 1593 UndefElts.setBit(OutIdx); 1594 } 1595 } else { 1596 llvm_unreachable("Unimp"); 1597 } 1598 break; 1599 } 1600 case Instruction::FPTrunc: 1601 case Instruction::FPExt: 1602 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1603 break; 1604 1605 case Instruction::Call: { 1606 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I); 1607 if (!II) break; 1608 switch (II->getIntrinsicID()) { 1609 case Intrinsic::masked_gather: // fallthrough 1610 case Intrinsic::masked_load: { 1611 // Subtlety: If we load from a pointer, the pointer must be valid 1612 // regardless of whether the element is demanded. Doing otherwise risks 1613 // segfaults which didn't exist in the original program. 1614 APInt DemandedPtrs(APInt::getAllOnes(VWidth)), 1615 DemandedPassThrough(DemandedElts); 1616 if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2))) 1617 for (unsigned i = 0; i < VWidth; i++) { 1618 Constant *CElt = CV->getAggregateElement(i); 1619 if (CElt->isNullValue()) 1620 DemandedPtrs.clearBit(i); 1621 else if (CElt->isAllOnesValue()) 1622 DemandedPassThrough.clearBit(i); 1623 } 1624 if (II->getIntrinsicID() == Intrinsic::masked_gather) 1625 simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2); 1626 simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3); 1627 1628 // Output elements are undefined if the element from both sources are. 1629 // TODO: can strengthen via mask as well. 1630 UndefElts = UndefElts2 & UndefElts3; 1631 break; 1632 } 1633 default: { 1634 // Handle target specific intrinsics 1635 Optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic( 1636 *II, DemandedElts, UndefElts, UndefElts2, UndefElts3, 1637 simplifyAndSetOp); 1638 if (V) 1639 return V.value(); 1640 break; 1641 } 1642 } // switch on IntrinsicID 1643 break; 1644 } // case Call 1645 } // switch on Opcode 1646 1647 // TODO: We bail completely on integer div/rem and shifts because they have 1648 // UB/poison potential, but that should be refined. 1649 BinaryOperator *BO; 1650 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) { 1651 simplifyAndSetOp(I, 0, DemandedElts, UndefElts); 1652 simplifyAndSetOp(I, 1, DemandedElts, UndefElts2); 1653 1654 // Output elements are undefined if both are undefined. Consider things 1655 // like undef & 0. The result is known zero, not undef. 1656 UndefElts &= UndefElts2; 1657 } 1658 1659 // If we've proven all of the lanes undef, return an undef value. 1660 // TODO: Intersect w/demanded lanes 1661 if (UndefElts.isAllOnes()) 1662 return UndefValue::get(I->getType());; 1663 1664 return MadeChange ? I : nullptr; 1665 } 1666