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