InstCombineSimplifyDemanded.cpp 68 KB

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