1 //===- InstCombineShifts.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 implements the visitShl, visitLShr, and visitAShr functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/Analysis/ConstantFolding.h" 15 #include "llvm/Analysis/InstructionSimplify.h" 16 #include "llvm/IR/IntrinsicInst.h" 17 #include "llvm/IR/PatternMatch.h" 18 using namespace llvm; 19 using namespace PatternMatch; 20 21 #define DEBUG_TYPE "instcombine" 22 23 // Given pattern: 24 // (x shiftopcode Q) shiftopcode K 25 // we should rewrite it as 26 // x shiftopcode (Q+K) iff (Q+K) u< bitwidth(x) 27 // This is valid for any shift, but they must be identical. 28 // 29 // AnalyzeForSignBitExtraction indicates that we will only analyze whether this 30 // pattern has any 2 right-shifts that sum to 1 less than original bit width. 31 Value *InstCombiner::reassociateShiftAmtsOfTwoSameDirectionShifts( 32 BinaryOperator *Sh0, const SimplifyQuery &SQ, 33 bool AnalyzeForSignBitExtraction) { 34 // Look for a shift of some instruction, ignore zext of shift amount if any. 35 Instruction *Sh0Op0; 36 Value *ShAmt0; 37 if (!match(Sh0, 38 m_Shift(m_Instruction(Sh0Op0), m_ZExtOrSelf(m_Value(ShAmt0))))) 39 return nullptr; 40 41 // If there is a truncation between the two shifts, we must make note of it 42 // and look through it. The truncation imposes additional constraints on the 43 // transform. 44 Instruction *Sh1; 45 Value *Trunc = nullptr; 46 match(Sh0Op0, 47 m_CombineOr(m_CombineAnd(m_Trunc(m_Instruction(Sh1)), m_Value(Trunc)), 48 m_Instruction(Sh1))); 49 50 // Inner shift: (x shiftopcode ShAmt1) 51 // Like with other shift, ignore zext of shift amount if any. 52 Value *X, *ShAmt1; 53 if (!match(Sh1, m_Shift(m_Value(X), m_ZExtOrSelf(m_Value(ShAmt1))))) 54 return nullptr; 55 56 // We have two shift amounts from two different shifts. The types of those 57 // shift amounts may not match. If that's the case let's bailout now.. 58 if (ShAmt0->getType() != ShAmt1->getType()) 59 return nullptr; 60 61 // We are only looking for signbit extraction if we have two right shifts. 62 bool HadTwoRightShifts = match(Sh0, m_Shr(m_Value(), m_Value())) && 63 match(Sh1, m_Shr(m_Value(), m_Value())); 64 // ... and if it's not two right-shifts, we know the answer already. 65 if (AnalyzeForSignBitExtraction && !HadTwoRightShifts) 66 return nullptr; 67 68 // The shift opcodes must be identical, unless we are just checking whether 69 // this pattern can be interpreted as a sign-bit-extraction. 70 Instruction::BinaryOps ShiftOpcode = Sh0->getOpcode(); 71 bool IdenticalShOpcodes = Sh0->getOpcode() == Sh1->getOpcode(); 72 if (!IdenticalShOpcodes && !AnalyzeForSignBitExtraction) 73 return nullptr; 74 75 // If we saw truncation, we'll need to produce extra instruction, 76 // and for that one of the operands of the shift must be one-use, 77 // unless of course we don't actually plan to produce any instructions here. 78 if (Trunc && !AnalyzeForSignBitExtraction && 79 !match(Sh0, m_c_BinOp(m_OneUse(m_Value()), m_Value()))) 80 return nullptr; 81 82 // Can we fold (ShAmt0+ShAmt1) ? 83 auto *NewShAmt = dyn_cast_or_null<Constant>( 84 SimplifyAddInst(ShAmt0, ShAmt1, /*isNSW=*/false, /*isNUW=*/false, 85 SQ.getWithInstruction(Sh0))); 86 if (!NewShAmt) 87 return nullptr; // Did not simplify. 88 unsigned NewShAmtBitWidth = NewShAmt->getType()->getScalarSizeInBits(); 89 unsigned XBitWidth = X->getType()->getScalarSizeInBits(); 90 // Is the new shift amount smaller than the bit width of inner/new shift? 91 if (!match(NewShAmt, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT, 92 APInt(NewShAmtBitWidth, XBitWidth)))) 93 return nullptr; // FIXME: could perform constant-folding. 94 95 // If there was a truncation, and we have a right-shift, we can only fold if 96 // we are left with the original sign bit. Likewise, if we were just checking 97 // that this is a sighbit extraction, this is the place to check it. 98 // FIXME: zero shift amount is also legal here, but we can't *easily* check 99 // more than one predicate so it's not really worth it. 100 if (HadTwoRightShifts && (Trunc || AnalyzeForSignBitExtraction)) { 101 // If it's not a sign bit extraction, then we're done. 102 if (!match(NewShAmt, 103 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ, 104 APInt(NewShAmtBitWidth, XBitWidth - 1)))) 105 return nullptr; 106 // If it is, and that was the question, return the base value. 107 if (AnalyzeForSignBitExtraction) 108 return X; 109 } 110 111 assert(IdenticalShOpcodes && "Should not get here with different shifts."); 112 113 // All good, we can do this fold. 114 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, X->getType()); 115 116 BinaryOperator *NewShift = BinaryOperator::Create(ShiftOpcode, X, NewShAmt); 117 118 // The flags can only be propagated if there wasn't a trunc. 119 if (!Trunc) { 120 // If the pattern did not involve trunc, and both of the original shifts 121 // had the same flag set, preserve the flag. 122 if (ShiftOpcode == Instruction::BinaryOps::Shl) { 123 NewShift->setHasNoUnsignedWrap(Sh0->hasNoUnsignedWrap() && 124 Sh1->hasNoUnsignedWrap()); 125 NewShift->setHasNoSignedWrap(Sh0->hasNoSignedWrap() && 126 Sh1->hasNoSignedWrap()); 127 } else { 128 NewShift->setIsExact(Sh0->isExact() && Sh1->isExact()); 129 } 130 } 131 132 Instruction *Ret = NewShift; 133 if (Trunc) { 134 Builder.Insert(NewShift); 135 Ret = CastInst::Create(Instruction::Trunc, NewShift, Sh0->getType()); 136 } 137 138 return Ret; 139 } 140 141 // If we have some pattern that leaves only some low bits set, and then performs 142 // left-shift of those bits, if none of the bits that are left after the final 143 // shift are modified by the mask, we can omit the mask. 144 // 145 // There are many variants to this pattern: 146 // a) (x & ((1 << MaskShAmt) - 1)) << ShiftShAmt 147 // b) (x & (~(-1 << MaskShAmt))) << ShiftShAmt 148 // c) (x & (-1 >> MaskShAmt)) << ShiftShAmt 149 // d) (x & ((-1 << MaskShAmt) >> MaskShAmt)) << ShiftShAmt 150 // e) ((x << MaskShAmt) l>> MaskShAmt) << ShiftShAmt 151 // f) ((x << MaskShAmt) a>> MaskShAmt) << ShiftShAmt 152 // All these patterns can be simplified to just: 153 // x << ShiftShAmt 154 // iff: 155 // a,b) (MaskShAmt+ShiftShAmt) u>= bitwidth(x) 156 // c,d,e,f) (ShiftShAmt-MaskShAmt) s>= 0 (i.e. ShiftShAmt u>= MaskShAmt) 157 static Instruction * 158 dropRedundantMaskingOfLeftShiftInput(BinaryOperator *OuterShift, 159 const SimplifyQuery &Q, 160 InstCombiner::BuilderTy &Builder) { 161 assert(OuterShift->getOpcode() == Instruction::BinaryOps::Shl && 162 "The input must be 'shl'!"); 163 164 Value *Masked, *ShiftShAmt; 165 match(OuterShift, 166 m_Shift(m_Value(Masked), m_ZExtOrSelf(m_Value(ShiftShAmt)))); 167 168 // *If* there is a truncation between an outer shift and a possibly-mask, 169 // then said truncation *must* be one-use, else we can't perform the fold. 170 Value *Trunc; 171 if (match(Masked, m_CombineAnd(m_Trunc(m_Value(Masked)), m_Value(Trunc))) && 172 !Trunc->hasOneUse()) 173 return nullptr; 174 175 Type *NarrowestTy = OuterShift->getType(); 176 Type *WidestTy = Masked->getType(); 177 bool HadTrunc = WidestTy != NarrowestTy; 178 179 // The mask must be computed in a type twice as wide to ensure 180 // that no bits are lost if the sum-of-shifts is wider than the base type. 181 Type *ExtendedTy = WidestTy->getExtendedType(); 182 183 Value *MaskShAmt; 184 185 // ((1 << MaskShAmt) - 1) 186 auto MaskA = m_Add(m_Shl(m_One(), m_Value(MaskShAmt)), m_AllOnes()); 187 // (~(-1 << maskNbits)) 188 auto MaskB = m_Xor(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_AllOnes()); 189 // (-1 >> MaskShAmt) 190 auto MaskC = m_Shr(m_AllOnes(), m_Value(MaskShAmt)); 191 // ((-1 << MaskShAmt) >> MaskShAmt) 192 auto MaskD = 193 m_Shr(m_Shl(m_AllOnes(), m_Value(MaskShAmt)), m_Deferred(MaskShAmt)); 194 195 Value *X; 196 Constant *NewMask; 197 198 if (match(Masked, m_c_And(m_CombineOr(MaskA, MaskB), m_Value(X)))) { 199 // Peek through an optional zext of the shift amount. 200 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt))); 201 202 // We have two shift amounts from two different shifts. The types of those 203 // shift amounts may not match. If that's the case let's bailout now. 204 if (MaskShAmt->getType() != ShiftShAmt->getType()) 205 return nullptr; 206 207 // Can we simplify (MaskShAmt+ShiftShAmt) ? 208 auto *SumOfShAmts = dyn_cast_or_null<Constant>(SimplifyAddInst( 209 MaskShAmt, ShiftShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q)); 210 if (!SumOfShAmts) 211 return nullptr; // Did not simplify. 212 // In this pattern SumOfShAmts correlates with the number of low bits 213 // that shall remain in the root value (OuterShift). 214 215 // An extend of an undef value becomes zero because the high bits are never 216 // completely unknown. Replace the the `undef` shift amounts with final 217 // shift bitwidth to ensure that the value remains undef when creating the 218 // subsequent shift op. 219 SumOfShAmts = Constant::replaceUndefsWith( 220 SumOfShAmts, ConstantInt::get(SumOfShAmts->getType()->getScalarType(), 221 ExtendedTy->getScalarSizeInBits())); 222 auto *ExtendedSumOfShAmts = ConstantExpr::getZExt(SumOfShAmts, ExtendedTy); 223 // And compute the mask as usual: ~(-1 << (SumOfShAmts)) 224 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy); 225 auto *ExtendedInvertedMask = 226 ConstantExpr::getShl(ExtendedAllOnes, ExtendedSumOfShAmts); 227 NewMask = ConstantExpr::getNot(ExtendedInvertedMask); 228 } else if (match(Masked, m_c_And(m_CombineOr(MaskC, MaskD), m_Value(X))) || 229 match(Masked, m_Shr(m_Shl(m_Value(X), m_Value(MaskShAmt)), 230 m_Deferred(MaskShAmt)))) { 231 // Peek through an optional zext of the shift amount. 232 match(MaskShAmt, m_ZExtOrSelf(m_Value(MaskShAmt))); 233 234 // We have two shift amounts from two different shifts. The types of those 235 // shift amounts may not match. If that's the case let's bailout now. 236 if (MaskShAmt->getType() != ShiftShAmt->getType()) 237 return nullptr; 238 239 // Can we simplify (ShiftShAmt-MaskShAmt) ? 240 auto *ShAmtsDiff = dyn_cast_or_null<Constant>(SimplifySubInst( 241 ShiftShAmt, MaskShAmt, /*IsNSW=*/false, /*IsNUW=*/false, Q)); 242 if (!ShAmtsDiff) 243 return nullptr; // Did not simplify. 244 // In this pattern ShAmtsDiff correlates with the number of high bits that 245 // shall be unset in the root value (OuterShift). 246 247 // An extend of an undef value becomes zero because the high bits are never 248 // completely unknown. Replace the the `undef` shift amounts with negated 249 // bitwidth of innermost shift to ensure that the value remains undef when 250 // creating the subsequent shift op. 251 unsigned WidestTyBitWidth = WidestTy->getScalarSizeInBits(); 252 ShAmtsDiff = Constant::replaceUndefsWith( 253 ShAmtsDiff, ConstantInt::get(ShAmtsDiff->getType()->getScalarType(), 254 -WidestTyBitWidth)); 255 auto *ExtendedNumHighBitsToClear = ConstantExpr::getZExt( 256 ConstantExpr::getSub(ConstantInt::get(ShAmtsDiff->getType(), 257 WidestTyBitWidth, 258 /*isSigned=*/false), 259 ShAmtsDiff), 260 ExtendedTy); 261 // And compute the mask as usual: (-1 l>> (NumHighBitsToClear)) 262 auto *ExtendedAllOnes = ConstantExpr::getAllOnesValue(ExtendedTy); 263 NewMask = 264 ConstantExpr::getLShr(ExtendedAllOnes, ExtendedNumHighBitsToClear); 265 } else 266 return nullptr; // Don't know anything about this pattern. 267 268 NewMask = ConstantExpr::getTrunc(NewMask, NarrowestTy); 269 270 // Does this mask has any unset bits? If not then we can just not apply it. 271 bool NeedMask = !match(NewMask, m_AllOnes()); 272 273 // If we need to apply a mask, there are several more restrictions we have. 274 if (NeedMask) { 275 // The old masking instruction must go away. 276 if (!Masked->hasOneUse()) 277 return nullptr; 278 // The original "masking" instruction must not have been`ashr`. 279 if (match(Masked, m_AShr(m_Value(), m_Value()))) 280 return nullptr; 281 } 282 283 // If we need to apply truncation, let's do it first, since we can. 284 // We have already ensured that the old truncation will go away. 285 if (HadTrunc) 286 X = Builder.CreateTrunc(X, NarrowestTy); 287 288 // No 'NUW'/'NSW'! We no longer know that we won't shift-out non-0 bits. 289 // We didn't change the Type of this outermost shift, so we can just do it. 290 auto *NewShift = BinaryOperator::Create(OuterShift->getOpcode(), X, 291 OuterShift->getOperand(1)); 292 if (!NeedMask) 293 return NewShift; 294 295 Builder.Insert(NewShift); 296 return BinaryOperator::Create(Instruction::And, NewShift, NewMask); 297 } 298 299 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) { 300 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 301 assert(Op0->getType() == Op1->getType()); 302 303 // If the shift amount is a one-use `sext`, we can demote it to `zext`. 304 Value *Y; 305 if (match(Op1, m_OneUse(m_SExt(m_Value(Y))))) { 306 Value *NewExt = Builder.CreateZExt(Y, I.getType(), Op1->getName()); 307 return BinaryOperator::Create(I.getOpcode(), Op0, NewExt); 308 } 309 310 // See if we can fold away this shift. 311 if (SimplifyDemandedInstructionBits(I)) 312 return &I; 313 314 // Try to fold constant and into select arguments. 315 if (isa<Constant>(Op0)) 316 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 317 if (Instruction *R = FoldOpIntoSelect(I, SI)) 318 return R; 319 320 if (Constant *CUI = dyn_cast<Constant>(Op1)) 321 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I)) 322 return Res; 323 324 if (auto *NewShift = cast_or_null<Instruction>( 325 reassociateShiftAmtsOfTwoSameDirectionShifts(&I, SQ))) 326 return NewShift; 327 328 // (C1 shift (A add C2)) -> (C1 shift C2) shift A) 329 // iff A and C2 are both positive. 330 Value *A; 331 Constant *C; 332 if (match(Op0, m_Constant()) && match(Op1, m_Add(m_Value(A), m_Constant(C)))) 333 if (isKnownNonNegative(A, DL, 0, &AC, &I, &DT) && 334 isKnownNonNegative(C, DL, 0, &AC, &I, &DT)) 335 return BinaryOperator::Create( 336 I.getOpcode(), Builder.CreateBinOp(I.getOpcode(), Op0, C), A); 337 338 // X shift (A srem B) -> X shift (A and B-1) iff B is a power of 2. 339 // Because shifts by negative values (which could occur if A were negative) 340 // are undefined. 341 const APInt *B; 342 if (Op1->hasOneUse() && match(Op1, m_SRem(m_Value(A), m_Power2(B)))) { 343 // FIXME: Should this get moved into SimplifyDemandedBits by saying we don't 344 // demand the sign bit (and many others) here?? 345 Value *Rem = Builder.CreateAnd(A, ConstantInt::get(I.getType(), *B - 1), 346 Op1->getName()); 347 I.setOperand(1, Rem); 348 return &I; 349 } 350 351 return nullptr; 352 } 353 354 /// Return true if we can simplify two logical (either left or right) shifts 355 /// that have constant shift amounts: OuterShift (InnerShift X, C1), C2. 356 static bool canEvaluateShiftedShift(unsigned OuterShAmt, bool IsOuterShl, 357 Instruction *InnerShift, InstCombiner &IC, 358 Instruction *CxtI) { 359 assert(InnerShift->isLogicalShift() && "Unexpected instruction type"); 360 361 // We need constant scalar or constant splat shifts. 362 const APInt *InnerShiftConst; 363 if (!match(InnerShift->getOperand(1), m_APInt(InnerShiftConst))) 364 return false; 365 366 // Two logical shifts in the same direction: 367 // shl (shl X, C1), C2 --> shl X, C1 + C2 368 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2 369 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl; 370 if (IsInnerShl == IsOuterShl) 371 return true; 372 373 // Equal shift amounts in opposite directions become bitwise 'and': 374 // lshr (shl X, C), C --> and X, C' 375 // shl (lshr X, C), C --> and X, C' 376 if (*InnerShiftConst == OuterShAmt) 377 return true; 378 379 // If the 2nd shift is bigger than the 1st, we can fold: 380 // lshr (shl X, C1), C2 --> and (shl X, C1 - C2), C3 381 // shl (lshr X, C1), C2 --> and (lshr X, C1 - C2), C3 382 // but it isn't profitable unless we know the and'd out bits are already zero. 383 // Also, check that the inner shift is valid (less than the type width) or 384 // we'll crash trying to produce the bit mask for the 'and'. 385 unsigned TypeWidth = InnerShift->getType()->getScalarSizeInBits(); 386 if (InnerShiftConst->ugt(OuterShAmt) && InnerShiftConst->ult(TypeWidth)) { 387 unsigned InnerShAmt = InnerShiftConst->getZExtValue(); 388 unsigned MaskShift = 389 IsInnerShl ? TypeWidth - InnerShAmt : InnerShAmt - OuterShAmt; 390 APInt Mask = APInt::getLowBitsSet(TypeWidth, OuterShAmt) << MaskShift; 391 if (IC.MaskedValueIsZero(InnerShift->getOperand(0), Mask, 0, CxtI)) 392 return true; 393 } 394 395 return false; 396 } 397 398 /// See if we can compute the specified value, but shifted logically to the left 399 /// or right by some number of bits. This should return true if the expression 400 /// can be computed for the same cost as the current expression tree. This is 401 /// used to eliminate extraneous shifting from things like: 402 /// %C = shl i128 %A, 64 403 /// %D = shl i128 %B, 96 404 /// %E = or i128 %C, %D 405 /// %F = lshr i128 %E, 64 406 /// where the client will ask if E can be computed shifted right by 64-bits. If 407 /// this succeeds, getShiftedValue() will be called to produce the value. 408 static bool canEvaluateShifted(Value *V, unsigned NumBits, bool IsLeftShift, 409 InstCombiner &IC, Instruction *CxtI) { 410 // We can always evaluate constants shifted. 411 if (isa<Constant>(V)) 412 return true; 413 414 Instruction *I = dyn_cast<Instruction>(V); 415 if (!I) return false; 416 417 // If this is the opposite shift, we can directly reuse the input of the shift 418 // if the needed bits are already zero in the input. This allows us to reuse 419 // the value which means that we don't care if the shift has multiple uses. 420 // TODO: Handle opposite shift by exact value. 421 ConstantInt *CI = nullptr; 422 if ((IsLeftShift && match(I, m_LShr(m_Value(), m_ConstantInt(CI)))) || 423 (!IsLeftShift && match(I, m_Shl(m_Value(), m_ConstantInt(CI))))) { 424 if (CI->getValue() == NumBits) { 425 // TODO: Check that the input bits are already zero with MaskedValueIsZero 426 #if 0 427 // If this is a truncate of a logical shr, we can truncate it to a smaller 428 // lshr iff we know that the bits we would otherwise be shifting in are 429 // already zeros. 430 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits(); 431 uint32_t BitWidth = Ty->getScalarSizeInBits(); 432 if (MaskedValueIsZero(I->getOperand(0), 433 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) && 434 CI->getLimitedValue(BitWidth) < BitWidth) { 435 return CanEvaluateTruncated(I->getOperand(0), Ty); 436 } 437 #endif 438 439 } 440 } 441 442 // We can't mutate something that has multiple uses: doing so would 443 // require duplicating the instruction in general, which isn't profitable. 444 if (!I->hasOneUse()) return false; 445 446 switch (I->getOpcode()) { 447 default: return false; 448 case Instruction::And: 449 case Instruction::Or: 450 case Instruction::Xor: 451 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted. 452 return canEvaluateShifted(I->getOperand(0), NumBits, IsLeftShift, IC, I) && 453 canEvaluateShifted(I->getOperand(1), NumBits, IsLeftShift, IC, I); 454 455 case Instruction::Shl: 456 case Instruction::LShr: 457 return canEvaluateShiftedShift(NumBits, IsLeftShift, I, IC, CxtI); 458 459 case Instruction::Select: { 460 SelectInst *SI = cast<SelectInst>(I); 461 Value *TrueVal = SI->getTrueValue(); 462 Value *FalseVal = SI->getFalseValue(); 463 return canEvaluateShifted(TrueVal, NumBits, IsLeftShift, IC, SI) && 464 canEvaluateShifted(FalseVal, NumBits, IsLeftShift, IC, SI); 465 } 466 case Instruction::PHI: { 467 // We can change a phi if we can change all operands. Note that we never 468 // get into trouble with cyclic PHIs here because we only consider 469 // instructions with a single use. 470 PHINode *PN = cast<PHINode>(I); 471 for (Value *IncValue : PN->incoming_values()) 472 if (!canEvaluateShifted(IncValue, NumBits, IsLeftShift, IC, PN)) 473 return false; 474 return true; 475 } 476 } 477 } 478 479 /// Fold OuterShift (InnerShift X, C1), C2. 480 /// See canEvaluateShiftedShift() for the constraints on these instructions. 481 static Value *foldShiftedShift(BinaryOperator *InnerShift, unsigned OuterShAmt, 482 bool IsOuterShl, 483 InstCombiner::BuilderTy &Builder) { 484 bool IsInnerShl = InnerShift->getOpcode() == Instruction::Shl; 485 Type *ShType = InnerShift->getType(); 486 unsigned TypeWidth = ShType->getScalarSizeInBits(); 487 488 // We only accept shifts-by-a-constant in canEvaluateShifted(). 489 const APInt *C1; 490 match(InnerShift->getOperand(1), m_APInt(C1)); 491 unsigned InnerShAmt = C1->getZExtValue(); 492 493 // Change the shift amount and clear the appropriate IR flags. 494 auto NewInnerShift = [&](unsigned ShAmt) { 495 InnerShift->setOperand(1, ConstantInt::get(ShType, ShAmt)); 496 if (IsInnerShl) { 497 InnerShift->setHasNoUnsignedWrap(false); 498 InnerShift->setHasNoSignedWrap(false); 499 } else { 500 InnerShift->setIsExact(false); 501 } 502 return InnerShift; 503 }; 504 505 // Two logical shifts in the same direction: 506 // shl (shl X, C1), C2 --> shl X, C1 + C2 507 // lshr (lshr X, C1), C2 --> lshr X, C1 + C2 508 if (IsInnerShl == IsOuterShl) { 509 // If this is an oversized composite shift, then unsigned shifts get 0. 510 if (InnerShAmt + OuterShAmt >= TypeWidth) 511 return Constant::getNullValue(ShType); 512 513 return NewInnerShift(InnerShAmt + OuterShAmt); 514 } 515 516 // Equal shift amounts in opposite directions become bitwise 'and': 517 // lshr (shl X, C), C --> and X, C' 518 // shl (lshr X, C), C --> and X, C' 519 if (InnerShAmt == OuterShAmt) { 520 APInt Mask = IsInnerShl 521 ? APInt::getLowBitsSet(TypeWidth, TypeWidth - OuterShAmt) 522 : APInt::getHighBitsSet(TypeWidth, TypeWidth - OuterShAmt); 523 Value *And = Builder.CreateAnd(InnerShift->getOperand(0), 524 ConstantInt::get(ShType, Mask)); 525 if (auto *AndI = dyn_cast<Instruction>(And)) { 526 AndI->moveBefore(InnerShift); 527 AndI->takeName(InnerShift); 528 } 529 return And; 530 } 531 532 assert(InnerShAmt > OuterShAmt && 533 "Unexpected opposite direction logical shift pair"); 534 535 // In general, we would need an 'and' for this transform, but 536 // canEvaluateShiftedShift() guarantees that the masked-off bits are not used. 537 // lshr (shl X, C1), C2 --> shl X, C1 - C2 538 // shl (lshr X, C1), C2 --> lshr X, C1 - C2 539 return NewInnerShift(InnerShAmt - OuterShAmt); 540 } 541 542 /// When canEvaluateShifted() returns true for an expression, this function 543 /// inserts the new computation that produces the shifted value. 544 static Value *getShiftedValue(Value *V, unsigned NumBits, bool isLeftShift, 545 InstCombiner &IC, const DataLayout &DL) { 546 // We can always evaluate constants shifted. 547 if (Constant *C = dyn_cast<Constant>(V)) { 548 if (isLeftShift) 549 V = IC.Builder.CreateShl(C, NumBits); 550 else 551 V = IC.Builder.CreateLShr(C, NumBits); 552 // If we got a constantexpr back, try to simplify it with TD info. 553 if (auto *C = dyn_cast<Constant>(V)) 554 if (auto *FoldedC = 555 ConstantFoldConstant(C, DL, &IC.getTargetLibraryInfo())) 556 V = FoldedC; 557 return V; 558 } 559 560 Instruction *I = cast<Instruction>(V); 561 IC.Worklist.Add(I); 562 563 switch (I->getOpcode()) { 564 default: llvm_unreachable("Inconsistency with CanEvaluateShifted"); 565 case Instruction::And: 566 case Instruction::Or: 567 case Instruction::Xor: 568 // Bitwise operators can all arbitrarily be arbitrarily evaluated shifted. 569 I->setOperand( 570 0, getShiftedValue(I->getOperand(0), NumBits, isLeftShift, IC, DL)); 571 I->setOperand( 572 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL)); 573 return I; 574 575 case Instruction::Shl: 576 case Instruction::LShr: 577 return foldShiftedShift(cast<BinaryOperator>(I), NumBits, isLeftShift, 578 IC.Builder); 579 580 case Instruction::Select: 581 I->setOperand( 582 1, getShiftedValue(I->getOperand(1), NumBits, isLeftShift, IC, DL)); 583 I->setOperand( 584 2, getShiftedValue(I->getOperand(2), NumBits, isLeftShift, IC, DL)); 585 return I; 586 case Instruction::PHI: { 587 // We can change a phi if we can change all operands. Note that we never 588 // get into trouble with cyclic PHIs here because we only consider 589 // instructions with a single use. 590 PHINode *PN = cast<PHINode>(I); 591 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 592 PN->setIncomingValue(i, getShiftedValue(PN->getIncomingValue(i), NumBits, 593 isLeftShift, IC, DL)); 594 return PN; 595 } 596 } 597 } 598 599 // If this is a bitwise operator or add with a constant RHS we might be able 600 // to pull it through a shift. 601 static bool canShiftBinOpWithConstantRHS(BinaryOperator &Shift, 602 BinaryOperator *BO) { 603 switch (BO->getOpcode()) { 604 default: 605 return false; // Do not perform transform! 606 case Instruction::Add: 607 return Shift.getOpcode() == Instruction::Shl; 608 case Instruction::Or: 609 case Instruction::Xor: 610 case Instruction::And: 611 return true; 612 } 613 } 614 615 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, Constant *Op1, 616 BinaryOperator &I) { 617 bool isLeftShift = I.getOpcode() == Instruction::Shl; 618 619 const APInt *Op1C; 620 if (!match(Op1, m_APInt(Op1C))) 621 return nullptr; 622 623 // See if we can propagate this shift into the input, this covers the trivial 624 // cast of lshr(shl(x,c1),c2) as well as other more complex cases. 625 if (I.getOpcode() != Instruction::AShr && 626 canEvaluateShifted(Op0, Op1C->getZExtValue(), isLeftShift, *this, &I)) { 627 LLVM_DEBUG( 628 dbgs() << "ICE: GetShiftedValue propagating shift through expression" 629 " to eliminate shift:\n IN: " 630 << *Op0 << "\n SH: " << I << "\n"); 631 632 return replaceInstUsesWith( 633 I, getShiftedValue(Op0, Op1C->getZExtValue(), isLeftShift, *this, DL)); 634 } 635 636 // See if we can simplify any instructions used by the instruction whose sole 637 // purpose is to compute bits we don't care about. 638 unsigned TypeBits = Op0->getType()->getScalarSizeInBits(); 639 640 assert(!Op1C->uge(TypeBits) && 641 "Shift over the type width should have been removed already"); 642 643 if (Instruction *FoldedShift = foldBinOpIntoSelectOrPhi(I)) 644 return FoldedShift; 645 646 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2)) 647 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) { 648 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0)); 649 // If 'shift2' is an ashr, we would have to get the sign bit into a funny 650 // place. Don't try to do this transformation in this case. Also, we 651 // require that the input operand is a shift-by-constant so that we have 652 // confidence that the shifts will get folded together. We could do this 653 // xform in more cases, but it is unlikely to be profitable. 654 if (TrOp && I.isLogicalShift() && TrOp->isShift() && 655 isa<ConstantInt>(TrOp->getOperand(1))) { 656 // Okay, we'll do this xform. Make the shift of shift. 657 Constant *ShAmt = 658 ConstantExpr::getZExt(cast<Constant>(Op1), TrOp->getType()); 659 // (shift2 (shift1 & 0x00FF), c2) 660 Value *NSh = Builder.CreateBinOp(I.getOpcode(), TrOp, ShAmt, I.getName()); 661 662 // For logical shifts, the truncation has the effect of making the high 663 // part of the register be zeros. Emulate this by inserting an AND to 664 // clear the top bits as needed. This 'and' will usually be zapped by 665 // other xforms later if dead. 666 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits(); 667 unsigned DstSize = TI->getType()->getScalarSizeInBits(); 668 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize)); 669 670 // The mask we constructed says what the trunc would do if occurring 671 // between the shifts. We want to know the effect *after* the second 672 // shift. We know that it is a logical shift by a constant, so adjust the 673 // mask as appropriate. 674 if (I.getOpcode() == Instruction::Shl) 675 MaskV <<= Op1C->getZExtValue(); 676 else { 677 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift"); 678 MaskV.lshrInPlace(Op1C->getZExtValue()); 679 } 680 681 // shift1 & 0x00FF 682 Value *And = Builder.CreateAnd(NSh, 683 ConstantInt::get(I.getContext(), MaskV), 684 TI->getName()); 685 686 // Return the value truncated to the interesting size. 687 return new TruncInst(And, I.getType()); 688 } 689 } 690 691 if (Op0->hasOneUse()) { 692 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) { 693 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C) 694 Value *V1, *V2; 695 ConstantInt *CC; 696 switch (Op0BO->getOpcode()) { 697 default: break; 698 case Instruction::Add: 699 case Instruction::And: 700 case Instruction::Or: 701 case Instruction::Xor: { 702 // These operators commute. 703 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C) 704 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() && 705 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), 706 m_Specific(Op1)))) { 707 Value *YS = // (Y << C) 708 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName()); 709 // (X + (Y << C)) 710 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), YS, V1, 711 Op0BO->getOperand(1)->getName()); 712 unsigned Op1Val = Op1C->getLimitedValue(TypeBits); 713 714 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val); 715 Constant *Mask = ConstantInt::get(I.getContext(), Bits); 716 if (VectorType *VT = dyn_cast<VectorType>(X->getType())) 717 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask); 718 return BinaryOperator::CreateAnd(X, Mask); 719 } 720 721 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C)) 722 Value *Op0BOOp1 = Op0BO->getOperand(1); 723 if (isLeftShift && Op0BOOp1->hasOneUse() && 724 match(Op0BOOp1, 725 m_And(m_OneUse(m_Shr(m_Value(V1), m_Specific(Op1))), 726 m_ConstantInt(CC)))) { 727 Value *YS = // (Y << C) 728 Builder.CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName()); 729 // X & (CC << C) 730 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1), 731 V1->getName()+".mask"); 732 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM); 733 } 734 LLVM_FALLTHROUGH; 735 } 736 737 case Instruction::Sub: { 738 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C) 739 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() && 740 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), 741 m_Specific(Op1)))) { 742 Value *YS = // (Y << C) 743 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName()); 744 // (X + (Y << C)) 745 Value *X = Builder.CreateBinOp(Op0BO->getOpcode(), V1, YS, 746 Op0BO->getOperand(0)->getName()); 747 unsigned Op1Val = Op1C->getLimitedValue(TypeBits); 748 749 APInt Bits = APInt::getHighBitsSet(TypeBits, TypeBits - Op1Val); 750 Constant *Mask = ConstantInt::get(I.getContext(), Bits); 751 if (VectorType *VT = dyn_cast<VectorType>(X->getType())) 752 Mask = ConstantVector::getSplat(VT->getNumElements(), Mask); 753 return BinaryOperator::CreateAnd(X, Mask); 754 } 755 756 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C) 757 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() && 758 match(Op0BO->getOperand(0), 759 m_And(m_OneUse(m_Shr(m_Value(V1), m_Value(V2))), 760 m_ConstantInt(CC))) && V2 == Op1) { 761 Value *YS = // (Y << C) 762 Builder.CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName()); 763 // X & (CC << C) 764 Value *XM = Builder.CreateAnd(V1, ConstantExpr::getShl(CC, Op1), 765 V1->getName()+".mask"); 766 767 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS); 768 } 769 770 break; 771 } 772 } 773 774 775 // If the operand is a bitwise operator with a constant RHS, and the 776 // shift is the only use, we can pull it out of the shift. 777 const APInt *Op0C; 778 if (match(Op0BO->getOperand(1), m_APInt(Op0C))) { 779 if (canShiftBinOpWithConstantRHS(I, Op0BO)) { 780 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 781 cast<Constant>(Op0BO->getOperand(1)), Op1); 782 783 Value *NewShift = 784 Builder.CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1); 785 NewShift->takeName(Op0BO); 786 787 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift, 788 NewRHS); 789 } 790 } 791 792 // If the operand is a subtract with a constant LHS, and the shift 793 // is the only use, we can pull it out of the shift. 794 // This folds (shl (sub C1, X), C2) -> (sub (C1 << C2), (shl X, C2)) 795 if (isLeftShift && Op0BO->getOpcode() == Instruction::Sub && 796 match(Op0BO->getOperand(0), m_APInt(Op0C))) { 797 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 798 cast<Constant>(Op0BO->getOperand(0)), Op1); 799 800 Value *NewShift = Builder.CreateShl(Op0BO->getOperand(1), Op1); 801 NewShift->takeName(Op0BO); 802 803 return BinaryOperator::CreateSub(NewRHS, NewShift); 804 } 805 } 806 807 // If we have a select that conditionally executes some binary operator, 808 // see if we can pull it the select and operator through the shift. 809 // 810 // For example, turning: 811 // shl (select C, (add X, C1), X), C2 812 // Into: 813 // Y = shl X, C2 814 // select C, (add Y, C1 << C2), Y 815 Value *Cond; 816 BinaryOperator *TBO; 817 Value *FalseVal; 818 if (match(Op0, m_Select(m_Value(Cond), m_OneUse(m_BinOp(TBO)), 819 m_Value(FalseVal)))) { 820 const APInt *C; 821 if (!isa<Constant>(FalseVal) && TBO->getOperand(0) == FalseVal && 822 match(TBO->getOperand(1), m_APInt(C)) && 823 canShiftBinOpWithConstantRHS(I, TBO)) { 824 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 825 cast<Constant>(TBO->getOperand(1)), Op1); 826 827 Value *NewShift = 828 Builder.CreateBinOp(I.getOpcode(), FalseVal, Op1); 829 Value *NewOp = Builder.CreateBinOp(TBO->getOpcode(), NewShift, 830 NewRHS); 831 return SelectInst::Create(Cond, NewOp, NewShift); 832 } 833 } 834 835 BinaryOperator *FBO; 836 Value *TrueVal; 837 if (match(Op0, m_Select(m_Value(Cond), m_Value(TrueVal), 838 m_OneUse(m_BinOp(FBO))))) { 839 const APInt *C; 840 if (!isa<Constant>(TrueVal) && FBO->getOperand(0) == TrueVal && 841 match(FBO->getOperand(1), m_APInt(C)) && 842 canShiftBinOpWithConstantRHS(I, FBO)) { 843 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), 844 cast<Constant>(FBO->getOperand(1)), Op1); 845 846 Value *NewShift = 847 Builder.CreateBinOp(I.getOpcode(), TrueVal, Op1); 848 Value *NewOp = Builder.CreateBinOp(FBO->getOpcode(), NewShift, 849 NewRHS); 850 return SelectInst::Create(Cond, NewShift, NewOp); 851 } 852 } 853 } 854 855 return nullptr; 856 } 857 858 Instruction *InstCombiner::visitShl(BinaryOperator &I) { 859 const SimplifyQuery Q = SQ.getWithInstruction(&I); 860 861 if (Value *V = SimplifyShlInst(I.getOperand(0), I.getOperand(1), 862 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), Q)) 863 return replaceInstUsesWith(I, V); 864 865 if (Instruction *X = foldVectorBinop(I)) 866 return X; 867 868 if (Instruction *V = commonShiftTransforms(I)) 869 return V; 870 871 if (Instruction *V = dropRedundantMaskingOfLeftShiftInput(&I, Q, Builder)) 872 return V; 873 874 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 875 Type *Ty = I.getType(); 876 unsigned BitWidth = Ty->getScalarSizeInBits(); 877 878 const APInt *ShAmtAPInt; 879 if (match(Op1, m_APInt(ShAmtAPInt))) { 880 unsigned ShAmt = ShAmtAPInt->getZExtValue(); 881 882 // shl (zext X), ShAmt --> zext (shl X, ShAmt) 883 // This is only valid if X would have zeros shifted out. 884 Value *X; 885 if (match(Op0, m_OneUse(m_ZExt(m_Value(X))))) { 886 unsigned SrcWidth = X->getType()->getScalarSizeInBits(); 887 if (ShAmt < SrcWidth && 888 MaskedValueIsZero(X, APInt::getHighBitsSet(SrcWidth, ShAmt), 0, &I)) 889 return new ZExtInst(Builder.CreateShl(X, ShAmt), Ty); 890 } 891 892 // (X >> C) << C --> X & (-1 << C) 893 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1)))) { 894 APInt Mask(APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)); 895 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask)); 896 } 897 898 // FIXME: we do not yet transform non-exact shr's. The backend (DAGCombine) 899 // needs a few fixes for the rotate pattern recognition first. 900 const APInt *ShOp1; 901 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_APInt(ShOp1))))) { 902 unsigned ShrAmt = ShOp1->getZExtValue(); 903 if (ShrAmt < ShAmt) { 904 // If C1 < C2: (X >>?,exact C1) << C2 --> X << (C2 - C1) 905 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShrAmt); 906 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff); 907 NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap()); 908 NewShl->setHasNoSignedWrap(I.hasNoSignedWrap()); 909 return NewShl; 910 } 911 if (ShrAmt > ShAmt) { 912 // If C1 > C2: (X >>?exact C1) << C2 --> X >>?exact (C1 - C2) 913 Constant *ShiftDiff = ConstantInt::get(Ty, ShrAmt - ShAmt); 914 auto *NewShr = BinaryOperator::Create( 915 cast<BinaryOperator>(Op0)->getOpcode(), X, ShiftDiff); 916 NewShr->setIsExact(true); 917 return NewShr; 918 } 919 } 920 921 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1)))) { 922 unsigned AmtSum = ShAmt + ShOp1->getZExtValue(); 923 // Oversized shifts are simplified to zero in InstSimplify. 924 if (AmtSum < BitWidth) 925 // (X << C1) << C2 --> X << (C1 + C2) 926 return BinaryOperator::CreateShl(X, ConstantInt::get(Ty, AmtSum)); 927 } 928 929 // If the shifted-out value is known-zero, then this is a NUW shift. 930 if (!I.hasNoUnsignedWrap() && 931 MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, ShAmt), 0, &I)) { 932 I.setHasNoUnsignedWrap(); 933 return &I; 934 } 935 936 // If the shifted-out value is all signbits, then this is a NSW shift. 937 if (!I.hasNoSignedWrap() && ComputeNumSignBits(Op0, 0, &I) > ShAmt) { 938 I.setHasNoSignedWrap(); 939 return &I; 940 } 941 } 942 943 // Transform (x >> y) << y to x & (-1 << y) 944 // Valid for any type of right-shift. 945 Value *X; 946 if (match(Op0, m_OneUse(m_Shr(m_Value(X), m_Specific(Op1))))) { 947 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty); 948 Value *Mask = Builder.CreateShl(AllOnes, Op1); 949 return BinaryOperator::CreateAnd(Mask, X); 950 } 951 952 Constant *C1; 953 if (match(Op1, m_Constant(C1))) { 954 Constant *C2; 955 Value *X; 956 // (C2 << X) << C1 --> (C2 << C1) << X 957 if (match(Op0, m_OneUse(m_Shl(m_Constant(C2), m_Value(X))))) 958 return BinaryOperator::CreateShl(ConstantExpr::getShl(C2, C1), X); 959 960 // (X * C2) << C1 --> X * (C2 << C1) 961 if (match(Op0, m_Mul(m_Value(X), m_Constant(C2)))) 962 return BinaryOperator::CreateMul(X, ConstantExpr::getShl(C2, C1)); 963 964 // shl (zext i1 X), C1 --> select (X, 1 << C1, 0) 965 if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { 966 auto *NewC = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C1); 967 return SelectInst::Create(X, NewC, ConstantInt::getNullValue(Ty)); 968 } 969 } 970 971 // (1 << (C - x)) -> ((1 << C) >> x) if C is bitwidth - 1 972 if (match(Op0, m_One()) && 973 match(Op1, m_Sub(m_SpecificInt(BitWidth - 1), m_Value(X)))) 974 return BinaryOperator::CreateLShr( 975 ConstantInt::get(Ty, APInt::getSignMask(BitWidth)), X); 976 977 return nullptr; 978 } 979 980 Instruction *InstCombiner::visitLShr(BinaryOperator &I) { 981 if (Value *V = SimplifyLShrInst(I.getOperand(0), I.getOperand(1), I.isExact(), 982 SQ.getWithInstruction(&I))) 983 return replaceInstUsesWith(I, V); 984 985 if (Instruction *X = foldVectorBinop(I)) 986 return X; 987 988 if (Instruction *R = commonShiftTransforms(I)) 989 return R; 990 991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 992 Type *Ty = I.getType(); 993 const APInt *ShAmtAPInt; 994 if (match(Op1, m_APInt(ShAmtAPInt))) { 995 unsigned ShAmt = ShAmtAPInt->getZExtValue(); 996 unsigned BitWidth = Ty->getScalarSizeInBits(); 997 auto *II = dyn_cast<IntrinsicInst>(Op0); 998 if (II && isPowerOf2_32(BitWidth) && Log2_32(BitWidth) == ShAmt && 999 (II->getIntrinsicID() == Intrinsic::ctlz || 1000 II->getIntrinsicID() == Intrinsic::cttz || 1001 II->getIntrinsicID() == Intrinsic::ctpop)) { 1002 // ctlz.i32(x)>>5 --> zext(x == 0) 1003 // cttz.i32(x)>>5 --> zext(x == 0) 1004 // ctpop.i32(x)>>5 --> zext(x == -1) 1005 bool IsPop = II->getIntrinsicID() == Intrinsic::ctpop; 1006 Constant *RHS = ConstantInt::getSigned(Ty, IsPop ? -1 : 0); 1007 Value *Cmp = Builder.CreateICmpEQ(II->getArgOperand(0), RHS); 1008 return new ZExtInst(Cmp, Ty); 1009 } 1010 1011 Value *X; 1012 const APInt *ShOp1; 1013 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShOp1))) && ShOp1->ult(BitWidth)) { 1014 if (ShOp1->ult(ShAmt)) { 1015 unsigned ShlAmt = ShOp1->getZExtValue(); 1016 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt); 1017 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) { 1018 // (X <<nuw C1) >>u C2 --> X >>u (C2 - C1) 1019 auto *NewLShr = BinaryOperator::CreateLShr(X, ShiftDiff); 1020 NewLShr->setIsExact(I.isExact()); 1021 return NewLShr; 1022 } 1023 // (X << C1) >>u C2 --> (X >>u (C2 - C1)) & (-1 >> C2) 1024 Value *NewLShr = Builder.CreateLShr(X, ShiftDiff, "", I.isExact()); 1025 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt)); 1026 return BinaryOperator::CreateAnd(NewLShr, ConstantInt::get(Ty, Mask)); 1027 } 1028 if (ShOp1->ugt(ShAmt)) { 1029 unsigned ShlAmt = ShOp1->getZExtValue(); 1030 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt); 1031 if (cast<BinaryOperator>(Op0)->hasNoUnsignedWrap()) { 1032 // (X <<nuw C1) >>u C2 --> X <<nuw (C1 - C2) 1033 auto *NewShl = BinaryOperator::CreateShl(X, ShiftDiff); 1034 NewShl->setHasNoUnsignedWrap(true); 1035 return NewShl; 1036 } 1037 // (X << C1) >>u C2 --> X << (C1 - C2) & (-1 >> C2) 1038 Value *NewShl = Builder.CreateShl(X, ShiftDiff); 1039 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt)); 1040 return BinaryOperator::CreateAnd(NewShl, ConstantInt::get(Ty, Mask)); 1041 } 1042 assert(*ShOp1 == ShAmt); 1043 // (X << C) >>u C --> X & (-1 >>u C) 1044 APInt Mask(APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt)); 1045 return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, Mask)); 1046 } 1047 1048 if (match(Op0, m_OneUse(m_ZExt(m_Value(X)))) && 1049 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) { 1050 assert(ShAmt < X->getType()->getScalarSizeInBits() && 1051 "Big shift not simplified to zero?"); 1052 // lshr (zext iM X to iN), C --> zext (lshr X, C) to iN 1053 Value *NewLShr = Builder.CreateLShr(X, ShAmt); 1054 return new ZExtInst(NewLShr, Ty); 1055 } 1056 1057 if (match(Op0, m_SExt(m_Value(X))) && 1058 (!Ty->isIntegerTy() || shouldChangeType(Ty, X->getType()))) { 1059 // Are we moving the sign bit to the low bit and widening with high zeros? 1060 unsigned SrcTyBitWidth = X->getType()->getScalarSizeInBits(); 1061 if (ShAmt == BitWidth - 1) { 1062 // lshr (sext i1 X to iN), N-1 --> zext X to iN 1063 if (SrcTyBitWidth == 1) 1064 return new ZExtInst(X, Ty); 1065 1066 // lshr (sext iM X to iN), N-1 --> zext (lshr X, M-1) to iN 1067 if (Op0->hasOneUse()) { 1068 Value *NewLShr = Builder.CreateLShr(X, SrcTyBitWidth - 1); 1069 return new ZExtInst(NewLShr, Ty); 1070 } 1071 } 1072 1073 // lshr (sext iM X to iN), N-M --> zext (ashr X, min(N-M, M-1)) to iN 1074 if (ShAmt == BitWidth - SrcTyBitWidth && Op0->hasOneUse()) { 1075 // The new shift amount can't be more than the narrow source type. 1076 unsigned NewShAmt = std::min(ShAmt, SrcTyBitWidth - 1); 1077 Value *AShr = Builder.CreateAShr(X, NewShAmt); 1078 return new ZExtInst(AShr, Ty); 1079 } 1080 } 1081 1082 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShOp1)))) { 1083 unsigned AmtSum = ShAmt + ShOp1->getZExtValue(); 1084 // Oversized shifts are simplified to zero in InstSimplify. 1085 if (AmtSum < BitWidth) 1086 // (X >>u C1) >>u C2 --> X >>u (C1 + C2) 1087 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum)); 1088 } 1089 1090 // If the shifted-out value is known-zero, then this is an exact shift. 1091 if (!I.isExact() && 1092 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) { 1093 I.setIsExact(); 1094 return &I; 1095 } 1096 } 1097 1098 // Transform (x << y) >> y to x & (-1 >> y) 1099 Value *X; 1100 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_Specific(Op1))))) { 1101 Constant *AllOnes = ConstantInt::getAllOnesValue(Ty); 1102 Value *Mask = Builder.CreateLShr(AllOnes, Op1); 1103 return BinaryOperator::CreateAnd(Mask, X); 1104 } 1105 1106 return nullptr; 1107 } 1108 1109 Instruction * 1110 InstCombiner::foldVariableSignZeroExtensionOfVariableHighBitExtract( 1111 BinaryOperator &OldAShr) { 1112 assert(OldAShr.getOpcode() == Instruction::AShr && 1113 "Must be called with arithmetic right-shift instruction only."); 1114 1115 // Check that constant C is a splat of the element-wise bitwidth of V. 1116 auto BitWidthSplat = [](Constant *C, Value *V) { 1117 return match( 1118 C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ, 1119 APInt(C->getType()->getScalarSizeInBits(), 1120 V->getType()->getScalarSizeInBits()))); 1121 }; 1122 1123 // It should look like variable-length sign-extension on the outside: 1124 // (Val << (bitwidth(Val)-Nbits)) a>> (bitwidth(Val)-Nbits) 1125 Value *NBits; 1126 Instruction *MaybeTrunc; 1127 Constant *C1, *C2; 1128 if (!match(&OldAShr, 1129 m_AShr(m_Shl(m_Instruction(MaybeTrunc), 1130 m_ZExtOrSelf(m_Sub(m_Constant(C1), 1131 m_ZExtOrSelf(m_Value(NBits))))), 1132 m_ZExtOrSelf(m_Sub(m_Constant(C2), 1133 m_ZExtOrSelf(m_Deferred(NBits)))))) || 1134 !BitWidthSplat(C1, &OldAShr) || !BitWidthSplat(C2, &OldAShr)) 1135 return nullptr; 1136 1137 // There may or may not be a truncation after outer two shifts. 1138 Instruction *HighBitExtract; 1139 match(MaybeTrunc, m_TruncOrSelf(m_Instruction(HighBitExtract))); 1140 bool HadTrunc = MaybeTrunc != HighBitExtract; 1141 1142 // And finally, the innermost part of the pattern must be a right-shift. 1143 Value *X, *NumLowBitsToSkip; 1144 if (!match(HighBitExtract, m_Shr(m_Value(X), m_Value(NumLowBitsToSkip)))) 1145 return nullptr; 1146 1147 // Said right-shift must extract high NBits bits - C0 must be it's bitwidth. 1148 Constant *C0; 1149 if (!match(NumLowBitsToSkip, 1150 m_ZExtOrSelf( 1151 m_Sub(m_Constant(C0), m_ZExtOrSelf(m_Specific(NBits))))) || 1152 !BitWidthSplat(C0, HighBitExtract)) 1153 return nullptr; 1154 1155 // Since the NBits is identical for all shifts, if the outermost and 1156 // innermost shifts are identical, then outermost shifts are redundant. 1157 // If we had truncation, do keep it though. 1158 if (HighBitExtract->getOpcode() == OldAShr.getOpcode()) 1159 return replaceInstUsesWith(OldAShr, MaybeTrunc); 1160 1161 // Else, if there was a truncation, then we need to ensure that one 1162 // instruction will go away. 1163 if (HadTrunc && !match(&OldAShr, m_c_BinOp(m_OneUse(m_Value()), m_Value()))) 1164 return nullptr; 1165 1166 // Finally, bypass two innermost shifts, and perform the outermost shift on 1167 // the operands of the innermost shift. 1168 Instruction *NewAShr = 1169 BinaryOperator::Create(OldAShr.getOpcode(), X, NumLowBitsToSkip); 1170 NewAShr->copyIRFlags(HighBitExtract); // We can preserve 'exact'-ness. 1171 if (!HadTrunc) 1172 return NewAShr; 1173 1174 Builder.Insert(NewAShr); 1175 return TruncInst::CreateTruncOrBitCast(NewAShr, OldAShr.getType()); 1176 } 1177 1178 Instruction *InstCombiner::visitAShr(BinaryOperator &I) { 1179 if (Value *V = SimplifyAShrInst(I.getOperand(0), I.getOperand(1), I.isExact(), 1180 SQ.getWithInstruction(&I))) 1181 return replaceInstUsesWith(I, V); 1182 1183 if (Instruction *X = foldVectorBinop(I)) 1184 return X; 1185 1186 if (Instruction *R = commonShiftTransforms(I)) 1187 return R; 1188 1189 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1190 Type *Ty = I.getType(); 1191 unsigned BitWidth = Ty->getScalarSizeInBits(); 1192 const APInt *ShAmtAPInt; 1193 if (match(Op1, m_APInt(ShAmtAPInt)) && ShAmtAPInt->ult(BitWidth)) { 1194 unsigned ShAmt = ShAmtAPInt->getZExtValue(); 1195 1196 // If the shift amount equals the difference in width of the destination 1197 // and source scalar types: 1198 // ashr (shl (zext X), C), C --> sext X 1199 Value *X; 1200 if (match(Op0, m_Shl(m_ZExt(m_Value(X)), m_Specific(Op1))) && 1201 ShAmt == BitWidth - X->getType()->getScalarSizeInBits()) 1202 return new SExtInst(X, Ty); 1203 1204 // We can't handle (X << C1) >>s C2. It shifts arbitrary bits in. However, 1205 // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bits. 1206 const APInt *ShOp1; 1207 if (match(Op0, m_NSWShl(m_Value(X), m_APInt(ShOp1))) && 1208 ShOp1->ult(BitWidth)) { 1209 unsigned ShlAmt = ShOp1->getZExtValue(); 1210 if (ShlAmt < ShAmt) { 1211 // (X <<nsw C1) >>s C2 --> X >>s (C2 - C1) 1212 Constant *ShiftDiff = ConstantInt::get(Ty, ShAmt - ShlAmt); 1213 auto *NewAShr = BinaryOperator::CreateAShr(X, ShiftDiff); 1214 NewAShr->setIsExact(I.isExact()); 1215 return NewAShr; 1216 } 1217 if (ShlAmt > ShAmt) { 1218 // (X <<nsw C1) >>s C2 --> X <<nsw (C1 - C2) 1219 Constant *ShiftDiff = ConstantInt::get(Ty, ShlAmt - ShAmt); 1220 auto *NewShl = BinaryOperator::Create(Instruction::Shl, X, ShiftDiff); 1221 NewShl->setHasNoSignedWrap(true); 1222 return NewShl; 1223 } 1224 } 1225 1226 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShOp1))) && 1227 ShOp1->ult(BitWidth)) { 1228 unsigned AmtSum = ShAmt + ShOp1->getZExtValue(); 1229 // Oversized arithmetic shifts replicate the sign bit. 1230 AmtSum = std::min(AmtSum, BitWidth - 1); 1231 // (X >>s C1) >>s C2 --> X >>s (C1 + C2) 1232 return BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum)); 1233 } 1234 1235 if (match(Op0, m_OneUse(m_SExt(m_Value(X)))) && 1236 (Ty->isVectorTy() || shouldChangeType(Ty, X->getType()))) { 1237 // ashr (sext X), C --> sext (ashr X, C') 1238 Type *SrcTy = X->getType(); 1239 ShAmt = std::min(ShAmt, SrcTy->getScalarSizeInBits() - 1); 1240 Value *NewSh = Builder.CreateAShr(X, ConstantInt::get(SrcTy, ShAmt)); 1241 return new SExtInst(NewSh, Ty); 1242 } 1243 1244 // If the shifted-out value is known-zero, then this is an exact shift. 1245 if (!I.isExact() && 1246 MaskedValueIsZero(Op0, APInt::getLowBitsSet(BitWidth, ShAmt), 0, &I)) { 1247 I.setIsExact(); 1248 return &I; 1249 } 1250 } 1251 1252 if (Instruction *R = foldVariableSignZeroExtensionOfVariableHighBitExtract(I)) 1253 return R; 1254 1255 // See if we can turn a signed shr into an unsigned shr. 1256 if (MaskedValueIsZero(Op0, APInt::getSignMask(BitWidth), 0, &I)) 1257 return BinaryOperator::CreateLShr(Op0, Op1); 1258 1259 return nullptr; 1260 } 1261