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