InstCombineShifts.cpp 56 KB

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