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