[RISCV] Fix mgather -> riscv.masked.strided.load combine not extending indices (...
[llvm-project.git] / llvm / lib / Transforms / InstCombine / InstCombineSimplifyDemanded.cpp
blob79873a9b4cbb4cecf14d54e33b69485f474c14e7
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.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/IR/GetElementPtrTypeIterator.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Support/KnownBits.h"
20 #include "llvm/Transforms/InstCombine/InstCombiner.h"
22 using namespace llvm;
23 using namespace llvm::PatternMatch;
25 #define DEBUG_TYPE "instcombine"
27 static cl::opt<bool>
28 VerifyKnownBits("instcombine-verify-known-bits",
29 cl::desc("Verify that computeKnownBits() and "
30 "SimplifyDemandedBits() are consistent"),
31 cl::Hidden, cl::init(false));
33 /// Check to see if the specified operand of the specified instruction is a
34 /// constant integer. If so, check to see if there are any bits set in the
35 /// constant that are not demanded. If so, shrink the constant and return true.
36 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
37 const APInt &Demanded) {
38 assert(I && "No instruction?");
39 assert(OpNo < I->getNumOperands() && "Operand index too large");
41 // The operand must be a constant integer or splat integer.
42 Value *Op = I->getOperand(OpNo);
43 const APInt *C;
44 if (!match(Op, m_APInt(C)))
45 return false;
47 // If there are no bits set that aren't demanded, nothing to do.
48 if (C->isSubsetOf(Demanded))
49 return false;
51 // This instruction is producing bits that are not demanded. Shrink the RHS.
52 I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
54 return true;
57 /// Returns the bitwidth of the given scalar or pointer type. For vector types,
58 /// returns the element type's bitwidth.
59 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
60 if (unsigned BitWidth = Ty->getScalarSizeInBits())
61 return BitWidth;
63 return DL.getPointerTypeSizeInBits(Ty);
66 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
67 /// the instruction has any properties that allow us to simplify its operands.
68 bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst,
69 KnownBits &Known) {
70 APInt DemandedMask(APInt::getAllOnes(Known.getBitWidth()));
71 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
72 0, &Inst);
73 if (!V) return false;
74 if (V == &Inst) return true;
75 replaceInstUsesWith(Inst, V);
76 return true;
79 /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
80 /// the instruction has any properties that allow us to simplify its operands.
81 bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst) {
82 KnownBits Known(getBitWidth(Inst.getType(), DL));
83 return SimplifyDemandedInstructionBits(Inst, Known);
86 /// This form of SimplifyDemandedBits simplifies the specified instruction
87 /// operand if possible, updating it in place. It returns true if it made any
88 /// change and false otherwise.
89 bool InstCombinerImpl::SimplifyDemandedBits(Instruction *I, unsigned OpNo,
90 const APInt &DemandedMask,
91 KnownBits &Known, unsigned Depth) {
92 Use &U = I->getOperandUse(OpNo);
93 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
94 Depth, I);
95 if (!NewVal) return false;
96 if (Instruction* OpInst = dyn_cast<Instruction>(U))
97 salvageDebugInfo(*OpInst);
99 replaceUse(U, NewVal);
100 return true;
103 /// This function attempts to replace V with a simpler value based on the
104 /// demanded bits. When this function is called, it is known that only the bits
105 /// set in DemandedMask of the result of V are ever used downstream.
106 /// Consequently, depending on the mask and V, it may be possible to replace V
107 /// with a constant or one of its operands. In such cases, this function does
108 /// the replacement and returns true. In all other cases, it returns false after
109 /// analyzing the expression and setting KnownOne and known to be one in the
110 /// expression. Known.Zero contains all the bits that are known to be zero in
111 /// the expression. These are provided to potentially allow the caller (which
112 /// might recursively be SimplifyDemandedBits itself) to simplify the
113 /// expression.
114 /// Known.One and Known.Zero always follow the invariant that:
115 /// Known.One & Known.Zero == 0.
116 /// That is, a bit can't be both 1 and 0. The bits in Known.One and Known.Zero
117 /// are accurate even for bits not in DemandedMask. Note
118 /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
119 /// be the same.
121 /// This returns null if it did not change anything and it permits no
122 /// simplification. This returns V itself if it did some simplification of V's
123 /// operands based on the information about what bits are demanded. This returns
124 /// some other non-null value if it found out that V is equal to another value
125 /// in the context where the specified bits are demanded, but not for all users.
126 Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
127 KnownBits &Known,
128 unsigned Depth,
129 Instruction *CxtI) {
130 assert(V != nullptr && "Null pointer of Value???");
131 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
132 uint32_t BitWidth = DemandedMask.getBitWidth();
133 Type *VTy = V->getType();
134 assert(
135 (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
136 Known.getBitWidth() == BitWidth &&
137 "Value *V, DemandedMask and Known must have same BitWidth");
139 if (isa<Constant>(V)) {
140 computeKnownBits(V, Known, Depth, CxtI);
141 return nullptr;
144 Known.resetAll();
145 if (DemandedMask.isZero()) // Not demanding any bits from V.
146 return UndefValue::get(VTy);
148 if (Depth == MaxAnalysisRecursionDepth)
149 return nullptr;
151 Instruction *I = dyn_cast<Instruction>(V);
152 if (!I) {
153 computeKnownBits(V, Known, Depth, CxtI);
154 return nullptr; // Only analyze instructions.
157 // If there are multiple uses of this value and we aren't at the root, then
158 // we can't do any simplifications of the operands, because DemandedMask
159 // only reflects the bits demanded by *one* of the users.
160 if (Depth != 0 && !I->hasOneUse())
161 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
163 KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
164 // If this is the root being simplified, allow it to have multiple uses,
165 // just set the DemandedMask to all bits so that we can try to simplify the
166 // operands. This allows visitTruncInst (for example) to simplify the
167 // operand of a trunc without duplicating all the logic below.
168 if (Depth == 0 && !V->hasOneUse())
169 DemandedMask.setAllBits();
171 // Update flags after simplifying an operand based on the fact that some high
172 // order bits are not demanded.
173 auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
174 unsigned NLZ) {
175 if (NLZ > 0) {
176 // Disable the nsw and nuw flags here: We can no longer guarantee that
177 // we won't wrap after simplification. Removing the nsw/nuw flags is
178 // legal here because the top bit is not demanded.
179 I->setHasNoSignedWrap(false);
180 I->setHasNoUnsignedWrap(false);
182 return I;
185 // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
186 // about the high bits of the operands.
187 auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
188 unsigned NLZ = DemandedMask.countl_zero();
189 // Right fill the mask of bits for the operands to demand the most
190 // significant bit and all those below it.
191 DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
192 if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
193 SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
194 ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
195 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
196 disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
197 return true;
199 return false;
202 switch (I->getOpcode()) {
203 default:
204 computeKnownBits(I, Known, Depth, CxtI);
205 break;
206 case Instruction::And: {
207 // If either the LHS or the RHS are Zero, the result is zero.
208 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
209 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
210 Depth + 1))
211 return I;
212 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
213 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
215 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
216 Depth, SQ.getWithInstruction(CxtI));
218 // If the client is only demanding bits that we know, return the known
219 // constant.
220 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
221 return Constant::getIntegerValue(VTy, Known.One);
223 // If all of the demanded bits are known 1 on one side, return the other.
224 // These bits cannot contribute to the result of the 'and'.
225 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
226 return I->getOperand(0);
227 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
228 return I->getOperand(1);
230 // If the RHS is a constant, see if we can simplify it.
231 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
232 return I;
234 break;
236 case Instruction::Or: {
237 // If either the LHS or the RHS are One, the result is One.
238 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
239 SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
240 Depth + 1)) {
241 // Disjoint flag may not longer hold.
242 I->dropPoisonGeneratingFlags();
243 return I;
245 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
246 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
248 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
249 Depth, SQ.getWithInstruction(CxtI));
251 // If the client is only demanding bits that we know, return the known
252 // constant.
253 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
254 return Constant::getIntegerValue(VTy, Known.One);
256 // If all of the demanded bits are known zero on one side, return the other.
257 // These bits cannot contribute to the result of the 'or'.
258 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
259 return I->getOperand(0);
260 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
261 return I->getOperand(1);
263 // If the RHS is a constant, see if we can simplify it.
264 if (ShrinkDemandedConstant(I, 1, DemandedMask))
265 return I;
267 // Infer disjoint flag if no common bits are set.
268 if (!cast<PossiblyDisjointInst>(I)->isDisjoint()) {
269 WithCache<const Value *> LHSCache(I->getOperand(0), LHSKnown),
270 RHSCache(I->getOperand(1), RHSKnown);
271 if (haveNoCommonBitsSet(LHSCache, RHSCache, SQ.getWithInstruction(I))) {
272 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
273 return I;
277 break;
279 case Instruction::Xor: {
280 if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
281 SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
282 return I;
283 Value *LHS, *RHS;
284 if (DemandedMask == 1 &&
285 match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
286 match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
287 // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
288 IRBuilderBase::InsertPointGuard Guard(Builder);
289 Builder.SetInsertPoint(I);
290 auto *Xor = Builder.CreateXor(LHS, RHS);
291 return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
294 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
295 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
297 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
298 Depth, SQ.getWithInstruction(CxtI));
300 // If the client is only demanding bits that we know, return the known
301 // constant.
302 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
303 return Constant::getIntegerValue(VTy, Known.One);
305 // If all of the demanded bits are known zero on one side, return the other.
306 // These bits cannot contribute to the result of the 'xor'.
307 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
308 return I->getOperand(0);
309 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
310 return I->getOperand(1);
312 // If all of the demanded bits are known to be zero on one side or the
313 // other, turn this into an *inclusive* or.
314 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
315 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
316 Instruction *Or =
317 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1));
318 if (DemandedMask.isAllOnes())
319 cast<PossiblyDisjointInst>(Or)->setIsDisjoint(true);
320 Or->takeName(I);
321 return InsertNewInstWith(Or, I->getIterator());
324 // If all of the demanded bits on one side are known, and all of the set
325 // bits on that side are also known to be set on the other side, turn this
326 // into an AND, as we know the bits will be cleared.
327 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
328 if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
329 RHSKnown.One.isSubsetOf(LHSKnown.One)) {
330 Constant *AndC = Constant::getIntegerValue(VTy,
331 ~RHSKnown.One & DemandedMask);
332 Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
333 return InsertNewInstWith(And, I->getIterator());
336 // If the RHS is a constant, see if we can change it. Don't alter a -1
337 // constant because that's a canonical 'not' op, and that is better for
338 // combining, SCEV, and codegen.
339 const APInt *C;
340 if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
341 if ((*C | ~DemandedMask).isAllOnes()) {
342 // Force bits to 1 to create a 'not' op.
343 I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
344 return I;
346 // If we can't turn this into a 'not', try to shrink the constant.
347 if (ShrinkDemandedConstant(I, 1, DemandedMask))
348 return I;
351 // If our LHS is an 'and' and if it has one use, and if any of the bits we
352 // are flipping are known to be set, then the xor is just resetting those
353 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
354 // simplifying both of them.
355 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
356 ConstantInt *AndRHS, *XorRHS;
357 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
358 match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
359 match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
360 (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
361 APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
363 Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
364 Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
365 InsertNewInstWith(NewAnd, I->getIterator());
367 Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
368 Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
369 return InsertNewInstWith(NewXor, I->getIterator());
372 break;
374 case Instruction::Select: {
375 if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
376 SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
377 return I;
378 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
379 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
381 // If the operands are constants, see if we can simplify them.
382 // This is similar to ShrinkDemandedConstant, but for a select we want to
383 // try to keep the selected constants the same as icmp value constants, if
384 // we can. This helps not break apart (or helps put back together)
385 // canonical patterns like min and max.
386 auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
387 const APInt &DemandedMask) {
388 const APInt *SelC;
389 if (!match(I->getOperand(OpNo), m_APInt(SelC)))
390 return false;
392 // Get the constant out of the ICmp, if there is one.
393 // Only try this when exactly 1 operand is a constant (if both operands
394 // are constant, the icmp should eventually simplify). Otherwise, we may
395 // invert the transform that reduces set bits and infinite-loop.
396 Value *X;
397 const APInt *CmpC;
398 ICmpInst::Predicate Pred;
399 if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
400 isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
401 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
403 // If the constant is already the same as the ICmp, leave it as-is.
404 if (*CmpC == *SelC)
405 return false;
406 // If the constants are not already the same, but can be with the demand
407 // mask, use the constant value from the ICmp.
408 if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
409 I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
410 return true;
412 return ShrinkDemandedConstant(I, OpNo, DemandedMask);
414 if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
415 CanonicalizeSelectConstant(I, 2, DemandedMask))
416 return I;
418 // Only known if known in both the LHS and RHS.
419 Known = LHSKnown.intersectWith(RHSKnown);
420 break;
422 case Instruction::Trunc: {
423 // If we do not demand the high bits of a right-shifted and truncated value,
424 // then we may be able to truncate it before the shift.
425 Value *X;
426 const APInt *C;
427 if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
428 // The shift amount must be valid (not poison) in the narrow type, and
429 // it must not be greater than the high bits demanded of the result.
430 if (C->ult(VTy->getScalarSizeInBits()) &&
431 C->ule(DemandedMask.countl_zero())) {
432 // trunc (lshr X, C) --> lshr (trunc X), C
433 IRBuilderBase::InsertPointGuard Guard(Builder);
434 Builder.SetInsertPoint(I);
435 Value *Trunc = Builder.CreateTrunc(X, VTy);
436 return Builder.CreateLShr(Trunc, C->getZExtValue());
440 [[fallthrough]];
441 case Instruction::ZExt: {
442 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
444 APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
445 KnownBits InputKnown(SrcBitWidth);
446 if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1)) {
447 // For zext nneg, we may have dropped the instruction which made the
448 // input non-negative.
449 I->dropPoisonGeneratingFlags();
450 return I;
452 assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
453 if (I->getOpcode() == Instruction::ZExt && I->hasNonNeg() &&
454 !InputKnown.isNegative())
455 InputKnown.makeNonNegative();
456 Known = InputKnown.zextOrTrunc(BitWidth);
458 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
459 break;
461 case Instruction::SExt: {
462 // Compute the bits in the result that are not present in the input.
463 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
465 APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
467 // If any of the sign extended bits are demanded, we know that the sign
468 // bit is demanded.
469 if (DemandedMask.getActiveBits() > SrcBitWidth)
470 InputDemandedBits.setBit(SrcBitWidth-1);
472 KnownBits InputKnown(SrcBitWidth);
473 if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
474 return I;
476 // If the input sign bit is known zero, or if the NewBits are not demanded
477 // convert this into a zero extension.
478 if (InputKnown.isNonNegative() ||
479 DemandedMask.getActiveBits() <= SrcBitWidth) {
480 // Convert to ZExt cast.
481 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy);
482 NewCast->takeName(I);
483 return InsertNewInstWith(NewCast, I->getIterator());
486 // If the sign bit of the input is known set or clear, then we know the
487 // top bits of the result.
488 Known = InputKnown.sext(BitWidth);
489 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
490 break;
492 case Instruction::Add: {
493 if ((DemandedMask & 1) == 0) {
494 // If we do not need the low bit, try to convert bool math to logic:
495 // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
496 Value *X, *Y;
497 if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
498 m_OneUse(m_SExt(m_Value(Y))))) &&
499 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
500 // Truth table for inputs and output signbits:
501 // X:0 | X:1
502 // ----------
503 // Y:0 | 0 | 0 |
504 // Y:1 | -1 | 0 |
505 // ----------
506 IRBuilderBase::InsertPointGuard Guard(Builder);
507 Builder.SetInsertPoint(I);
508 Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
509 return Builder.CreateSExt(AndNot, VTy);
512 // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
513 // TODO: Relax the one-use checks because we are removing an instruction?
514 if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))),
515 m_OneUse(m_SExt(m_Value(Y))))) &&
516 X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
517 // Truth table for inputs and output signbits:
518 // X:0 | X:1
519 // -----------
520 // Y:0 | -1 | -1 |
521 // Y:1 | -1 | 0 |
522 // -----------
523 IRBuilderBase::InsertPointGuard Guard(Builder);
524 Builder.SetInsertPoint(I);
525 Value *Or = Builder.CreateOr(X, Y);
526 return Builder.CreateSExt(Or, VTy);
530 // Right fill the mask of bits for the operands to demand the most
531 // significant bit and all those below it.
532 unsigned NLZ = DemandedMask.countl_zero();
533 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
534 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
535 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
536 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
538 // If low order bits are not demanded and known to be zero in one operand,
539 // then we don't need to demand them from the other operand, since they
540 // can't cause overflow into any bits that are demanded in the result.
541 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
542 APInt DemandedFromLHS = DemandedFromOps;
543 DemandedFromLHS.clearLowBits(NTZ);
544 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
545 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
546 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
548 // If we are known to be adding zeros to every bit below
549 // the highest demanded bit, we just return the other side.
550 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
551 return I->getOperand(0);
552 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
553 return I->getOperand(1);
555 // (add X, C) --> (xor X, C) IFF C is equal to the top bit of the DemandMask
557 const APInt *C;
558 if (match(I->getOperand(1), m_APInt(C)) &&
559 C->isOneBitSet(DemandedMask.getActiveBits() - 1)) {
560 IRBuilderBase::InsertPointGuard Guard(Builder);
561 Builder.SetInsertPoint(I);
562 return Builder.CreateXor(I->getOperand(0), ConstantInt::get(VTy, *C));
566 // Otherwise just compute the known bits of the result.
567 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
568 Known = KnownBits::computeForAddSub(true, NSW, LHSKnown, RHSKnown);
569 break;
571 case Instruction::Sub: {
572 // Right fill the mask of bits for the operands to demand the most
573 // significant bit and all those below it.
574 unsigned NLZ = DemandedMask.countl_zero();
575 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
576 if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
577 SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
578 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
580 // If low order bits are not demanded and are known to be zero in RHS,
581 // then we don't need to demand them from LHS, since they can't cause a
582 // borrow from any bits that are demanded in the result.
583 unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countr_one();
584 APInt DemandedFromLHS = DemandedFromOps;
585 DemandedFromLHS.clearLowBits(NTZ);
586 if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
587 SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
588 return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
590 // If we are known to be subtracting zeros from every bit below
591 // the highest demanded bit, we just return the other side.
592 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
593 return I->getOperand(0);
594 // We can't do this with the LHS for subtraction, unless we are only
595 // demanding the LSB.
596 if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
597 return I->getOperand(1);
599 // Otherwise just compute the known bits of the result.
600 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
601 Known = KnownBits::computeForAddSub(false, NSW, LHSKnown, RHSKnown);
602 break;
604 case Instruction::Mul: {
605 APInt DemandedFromOps;
606 if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
607 return I;
609 if (DemandedMask.isPowerOf2()) {
610 // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
611 // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
612 // odd (has LSB set), then the left-shifted low bit of X is the answer.
613 unsigned CTZ = DemandedMask.countr_zero();
614 const APInt *C;
615 if (match(I->getOperand(1), m_APInt(C)) && C->countr_zero() == CTZ) {
616 Constant *ShiftC = ConstantInt::get(VTy, CTZ);
617 Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
618 return InsertNewInstWith(Shl, I->getIterator());
621 // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
622 // X * X is odd iff X is odd.
623 // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
624 if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
625 Constant *One = ConstantInt::get(VTy, 1);
626 Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
627 return InsertNewInstWith(And1, I->getIterator());
630 computeKnownBits(I, Known, Depth, CxtI);
631 break;
633 case Instruction::Shl: {
634 const APInt *SA;
635 if (match(I->getOperand(1), m_APInt(SA))) {
636 const APInt *ShrAmt;
637 if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
638 if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
639 if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
640 DemandedMask, Known))
641 return R;
643 // TODO: If we only want bits that already match the signbit then we don't
644 // need to shift.
646 // If we can pre-shift a right-shifted constant to the left without
647 // losing any high bits amd we don't demand the low bits, then eliminate
648 // the left-shift:
649 // (C >> X) << LeftShiftAmtC --> (C << RightShiftAmtC) >> X
650 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
651 Value *X;
652 Constant *C;
653 if (DemandedMask.countr_zero() >= ShiftAmt &&
654 match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
655 Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
656 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::Shl, C,
657 LeftShiftAmtC, DL);
658 if (ConstantFoldBinaryOpOperands(Instruction::LShr, NewC, LeftShiftAmtC,
659 DL) == C) {
660 Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
661 return InsertNewInstWith(Lshr, I->getIterator());
665 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
667 // If the shift is NUW/NSW, then it does demand the high bits.
668 ShlOperator *IOp = cast<ShlOperator>(I);
669 if (IOp->hasNoSignedWrap())
670 DemandedMaskIn.setHighBits(ShiftAmt+1);
671 else if (IOp->hasNoUnsignedWrap())
672 DemandedMaskIn.setHighBits(ShiftAmt);
674 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
675 return I;
676 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
678 Known = KnownBits::shl(Known,
679 KnownBits::makeConstant(APInt(BitWidth, ShiftAmt)),
680 /* NUW */ IOp->hasNoUnsignedWrap(),
681 /* NSW */ IOp->hasNoSignedWrap());
682 } else {
683 // This is a variable shift, so we can't shift the demand mask by a known
684 // amount. But if we are not demanding high bits, then we are not
685 // demanding those bits from the pre-shifted operand either.
686 if (unsigned CTLZ = DemandedMask.countl_zero()) {
687 APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
688 if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) {
689 // We can't guarantee that nsw/nuw hold after simplifying the operand.
690 I->dropPoisonGeneratingFlags();
691 return I;
694 computeKnownBits(I, Known, Depth, CxtI);
696 break;
698 case Instruction::LShr: {
699 const APInt *SA;
700 if (match(I->getOperand(1), m_APInt(SA))) {
701 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
703 // If we are just demanding the shifted sign bit and below, then this can
704 // be treated as an ASHR in disguise.
705 if (DemandedMask.countl_zero() >= ShiftAmt) {
706 // If we only want bits that already match the signbit then we don't
707 // need to shift.
708 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
709 unsigned SignBits =
710 ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
711 if (SignBits >= NumHiDemandedBits)
712 return I->getOperand(0);
714 // If we can pre-shift a left-shifted constant to the right without
715 // losing any low bits (we already know we don't demand the high bits),
716 // then eliminate the right-shift:
717 // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
718 Value *X;
719 Constant *C;
720 if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
721 Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
722 Constant *NewC = ConstantFoldBinaryOpOperands(Instruction::LShr, C,
723 RightShiftAmtC, DL);
724 if (ConstantFoldBinaryOpOperands(Instruction::Shl, NewC,
725 RightShiftAmtC, DL) == C) {
726 Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
727 return InsertNewInstWith(Shl, I->getIterator());
732 // Unsigned shift right.
733 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
734 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) {
735 // exact flag may not longer hold.
736 I->dropPoisonGeneratingFlags();
737 return I;
739 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
740 Known.Zero.lshrInPlace(ShiftAmt);
741 Known.One.lshrInPlace(ShiftAmt);
742 if (ShiftAmt)
743 Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
744 } else {
745 computeKnownBits(I, Known, Depth, CxtI);
747 break;
749 case Instruction::AShr: {
750 unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
752 // If we only want bits that already match the signbit then we don't need
753 // to shift.
754 unsigned NumHiDemandedBits = BitWidth - DemandedMask.countr_zero();
755 if (SignBits >= NumHiDemandedBits)
756 return I->getOperand(0);
758 // If this is an arithmetic shift right and only the low-bit is set, we can
759 // always convert this into a logical shr, even if the shift amount is
760 // variable. The low bit of the shift cannot be an input sign bit unless
761 // the shift amount is >= the size of the datatype, which is undefined.
762 if (DemandedMask.isOne()) {
763 // Perform the logical shift right.
764 Instruction *NewVal = BinaryOperator::CreateLShr(
765 I->getOperand(0), I->getOperand(1), I->getName());
766 return InsertNewInstWith(NewVal, I->getIterator());
769 const APInt *SA;
770 if (match(I->getOperand(1), m_APInt(SA))) {
771 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
773 // Signed shift right.
774 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
775 // If any of the high bits are demanded, we should set the sign bit as
776 // demanded.
777 if (DemandedMask.countl_zero() <= ShiftAmt)
778 DemandedMaskIn.setSignBit();
780 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1)) {
781 // exact flag may not longer hold.
782 I->dropPoisonGeneratingFlags();
783 return I;
786 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
787 // Compute the new bits that are at the top now plus sign bits.
788 APInt HighBits(APInt::getHighBitsSet(
789 BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
790 Known.Zero.lshrInPlace(ShiftAmt);
791 Known.One.lshrInPlace(ShiftAmt);
793 // If the input sign bit is known to be zero, or if none of the top bits
794 // are demanded, turn this into an unsigned shift right.
795 assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
796 if (Known.Zero[BitWidth-ShiftAmt-1] ||
797 !DemandedMask.intersects(HighBits)) {
798 BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
799 I->getOperand(1));
800 LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
801 LShr->takeName(I);
802 return InsertNewInstWith(LShr, I->getIterator());
803 } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
804 Known.One |= HighBits;
805 // SignBits may be out-of-sync with Known.countMinSignBits(). Mask out
806 // high bits of Known.Zero to avoid conflicts.
807 Known.Zero &= ~HighBits;
809 } else {
810 computeKnownBits(I, Known, Depth, CxtI);
812 break;
814 case Instruction::UDiv: {
815 // UDiv doesn't demand low bits that are zero in the divisor.
816 const APInt *SA;
817 if (match(I->getOperand(1), m_APInt(SA))) {
818 // TODO: Take the demanded mask of the result into account.
819 unsigned RHSTrailingZeros = SA->countr_zero();
820 APInt DemandedMaskIn =
821 APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
822 if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1)) {
823 // We can't guarantee that "exact" is still true after changing the
824 // the dividend.
825 I->dropPoisonGeneratingFlags();
826 return I;
829 Known = KnownBits::udiv(LHSKnown, KnownBits::makeConstant(*SA),
830 cast<BinaryOperator>(I)->isExact());
831 } else {
832 computeKnownBits(I, Known, Depth, CxtI);
834 break;
836 case Instruction::SRem: {
837 const APInt *Rem;
838 if (match(I->getOperand(1), m_APInt(Rem))) {
839 // X % -1 demands all the bits because we don't want to introduce
840 // INT_MIN % -1 (== undef) by accident.
841 if (Rem->isAllOnes())
842 break;
843 APInt RA = Rem->abs();
844 if (RA.isPowerOf2()) {
845 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
846 return I->getOperand(0);
848 APInt LowBits = RA - 1;
849 APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
850 if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
851 return I;
853 // The low bits of LHS are unchanged by the srem.
854 Known.Zero = LHSKnown.Zero & LowBits;
855 Known.One = LHSKnown.One & LowBits;
857 // If LHS is non-negative or has all low bits zero, then the upper bits
858 // are all zero.
859 if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
860 Known.Zero |= ~LowBits;
862 // If LHS is negative and not all low bits are zero, then the upper bits
863 // are all one.
864 if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
865 Known.One |= ~LowBits;
867 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
868 break;
872 computeKnownBits(I, Known, Depth, CxtI);
873 break;
875 case Instruction::URem: {
876 APInt AllOnes = APInt::getAllOnes(BitWidth);
877 if (SimplifyDemandedBits(I, 0, AllOnes, LHSKnown, Depth + 1) ||
878 SimplifyDemandedBits(I, 1, AllOnes, RHSKnown, Depth + 1))
879 return I;
881 Known = KnownBits::urem(LHSKnown, RHSKnown);
882 break;
884 case Instruction::Call: {
885 bool KnownBitsComputed = false;
886 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
887 switch (II->getIntrinsicID()) {
888 case Intrinsic::abs: {
889 if (DemandedMask == 1)
890 return II->getArgOperand(0);
891 break;
893 case Intrinsic::ctpop: {
894 // Checking if the number of clear bits is odd (parity)? If the type has
895 // an even number of bits, that's the same as checking if the number of
896 // set bits is odd, so we can eliminate the 'not' op.
897 Value *X;
898 if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
899 match(II->getArgOperand(0), m_Not(m_Value(X)))) {
900 Function *Ctpop = Intrinsic::getDeclaration(
901 II->getModule(), Intrinsic::ctpop, VTy);
902 return InsertNewInstWith(CallInst::Create(Ctpop, {X}), I->getIterator());
904 break;
906 case Intrinsic::bswap: {
907 // If the only bits demanded come from one byte of the bswap result,
908 // just shift the input byte into position to eliminate the bswap.
909 unsigned NLZ = DemandedMask.countl_zero();
910 unsigned NTZ = DemandedMask.countr_zero();
912 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
913 // we need all the bits down to bit 8. Likewise, round NLZ. If we
914 // have 14 leading zeros, round to 8.
915 NLZ = alignDown(NLZ, 8);
916 NTZ = alignDown(NTZ, 8);
917 // If we need exactly one byte, we can do this transformation.
918 if (BitWidth - NLZ - NTZ == 8) {
919 // Replace this with either a left or right shift to get the byte into
920 // the right place.
921 Instruction *NewVal;
922 if (NLZ > NTZ)
923 NewVal = BinaryOperator::CreateLShr(
924 II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
925 else
926 NewVal = BinaryOperator::CreateShl(
927 II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
928 NewVal->takeName(I);
929 return InsertNewInstWith(NewVal, I->getIterator());
931 break;
933 case Intrinsic::ptrmask: {
934 unsigned MaskWidth = I->getOperand(1)->getType()->getScalarSizeInBits();
935 RHSKnown = KnownBits(MaskWidth);
936 // If either the LHS or the RHS are Zero, the result is zero.
937 if (SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1) ||
938 SimplifyDemandedBits(
939 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth),
940 RHSKnown, Depth + 1))
941 return I;
943 // TODO: Should be 1-extend
944 RHSKnown = RHSKnown.anyextOrTrunc(BitWidth);
945 assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
946 assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
948 Known = LHSKnown & RHSKnown;
949 KnownBitsComputed = true;
951 // If the client is only demanding bits we know to be zero, return
952 // `llvm.ptrmask(p, 0)`. We can't return `null` here due to pointer
953 // provenance, but making the mask zero will be easily optimizable in
954 // the backend.
955 if (DemandedMask.isSubsetOf(Known.Zero) &&
956 !match(I->getOperand(1), m_Zero()))
957 return replaceOperand(
958 *I, 1, Constant::getNullValue(I->getOperand(1)->getType()));
960 // Mask in demanded space does nothing.
961 // NOTE: We may have attributes associated with the return value of the
962 // llvm.ptrmask intrinsic that will be lost when we just return the
963 // operand. We should try to preserve them.
964 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
965 return I->getOperand(0);
967 // If the RHS is a constant, see if we can simplify it.
968 if (ShrinkDemandedConstant(
969 I, 1, (DemandedMask & ~LHSKnown.Zero).zextOrTrunc(MaskWidth)))
970 return I;
972 break;
975 case Intrinsic::fshr:
976 case Intrinsic::fshl: {
977 const APInt *SA;
978 if (!match(I->getOperand(2), m_APInt(SA)))
979 break;
981 // Normalize to funnel shift left. APInt shifts of BitWidth are well-
982 // defined, so no need to special-case zero shifts here.
983 uint64_t ShiftAmt = SA->urem(BitWidth);
984 if (II->getIntrinsicID() == Intrinsic::fshr)
985 ShiftAmt = BitWidth - ShiftAmt;
987 APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
988 APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
989 if (I->getOperand(0) != I->getOperand(1)) {
990 if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown,
991 Depth + 1) ||
992 SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
993 return I;
994 } else { // fshl is a rotate
995 // Avoid converting rotate into funnel shift.
996 // Only simplify if one operand is constant.
997 LHSKnown = computeKnownBits(I->getOperand(0), Depth + 1, I);
998 if (DemandedMaskLHS.isSubsetOf(LHSKnown.Zero | LHSKnown.One) &&
999 !match(I->getOperand(0), m_SpecificInt(LHSKnown.One))) {
1000 replaceOperand(*I, 0, Constant::getIntegerValue(VTy, LHSKnown.One));
1001 return I;
1004 RHSKnown = computeKnownBits(I->getOperand(1), Depth + 1, I);
1005 if (DemandedMaskRHS.isSubsetOf(RHSKnown.Zero | RHSKnown.One) &&
1006 !match(I->getOperand(1), m_SpecificInt(RHSKnown.One))) {
1007 replaceOperand(*I, 1, Constant::getIntegerValue(VTy, RHSKnown.One));
1008 return I;
1012 Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
1013 RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
1014 Known.One = LHSKnown.One.shl(ShiftAmt) |
1015 RHSKnown.One.lshr(BitWidth - ShiftAmt);
1016 KnownBitsComputed = true;
1017 break;
1019 case Intrinsic::umax: {
1020 // UMax(A, C) == A if ...
1021 // The lowest non-zero bit of DemandMask is higher than the highest
1022 // non-zero bit of C.
1023 const APInt *C;
1024 unsigned CTZ = DemandedMask.countr_zero();
1025 if (match(II->getArgOperand(1), m_APInt(C)) &&
1026 CTZ >= C->getActiveBits())
1027 return II->getArgOperand(0);
1028 break;
1030 case Intrinsic::umin: {
1031 // UMin(A, C) == A if ...
1032 // The lowest non-zero bit of DemandMask is higher than the highest
1033 // non-one bit of C.
1034 // This comes from using DeMorgans on the above umax example.
1035 const APInt *C;
1036 unsigned CTZ = DemandedMask.countr_zero();
1037 if (match(II->getArgOperand(1), m_APInt(C)) &&
1038 CTZ >= C->getBitWidth() - C->countl_one())
1039 return II->getArgOperand(0);
1040 break;
1042 default: {
1043 // Handle target specific intrinsics
1044 std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
1045 *II, DemandedMask, Known, KnownBitsComputed);
1046 if (V)
1047 return *V;
1048 break;
1053 if (!KnownBitsComputed)
1054 computeKnownBits(V, Known, Depth, CxtI);
1055 break;
1059 if (V->getType()->isPointerTy()) {
1060 Align Alignment = V->getPointerAlignment(DL);
1061 Known.Zero.setLowBits(Log2(Alignment));
1064 // If the client is only demanding bits that we know, return the known
1065 // constant. We can't directly simplify pointers as a constant because of
1066 // pointer provenance.
1067 // TODO: We could return `(inttoptr const)` for pointers.
1068 if (!V->getType()->isPointerTy() && DemandedMask.isSubsetOf(Known.Zero | Known.One))
1069 return Constant::getIntegerValue(VTy, Known.One);
1071 if (VerifyKnownBits) {
1072 KnownBits ReferenceKnown = computeKnownBits(V, Depth, CxtI);
1073 if (Known != ReferenceKnown) {
1074 errs() << "Mismatched known bits for " << *V << " in "
1075 << I->getFunction()->getName() << "\n";
1076 errs() << "computeKnownBits(): " << ReferenceKnown << "\n";
1077 errs() << "SimplifyDemandedBits(): " << Known << "\n";
1078 std::abort();
1082 return nullptr;
1085 /// Helper routine of SimplifyDemandedUseBits. It computes Known
1086 /// bits. It also tries to handle simplifications that can be done based on
1087 /// DemandedMask, but without modifying the Instruction.
1088 Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits(
1089 Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
1090 Instruction *CxtI) {
1091 unsigned BitWidth = DemandedMask.getBitWidth();
1092 Type *ITy = I->getType();
1094 KnownBits LHSKnown(BitWidth);
1095 KnownBits RHSKnown(BitWidth);
1097 // Despite the fact that we can't simplify this instruction in all User's
1098 // context, we can at least compute the known bits, and we can
1099 // do simplifications that apply to *just* the one user if we know that
1100 // this instruction has a simpler value in that context.
1101 switch (I->getOpcode()) {
1102 case Instruction::And: {
1103 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1104 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1105 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1106 Depth, SQ.getWithInstruction(CxtI));
1107 computeKnownBitsFromContext(I, Known, Depth, SQ.getWithInstruction(CxtI));
1109 // If the client is only demanding bits that we know, return the known
1110 // constant.
1111 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1112 return Constant::getIntegerValue(ITy, Known.One);
1114 // If all of the demanded bits are known 1 on one side, return the other.
1115 // These bits cannot contribute to the result of the 'and' in this context.
1116 if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
1117 return I->getOperand(0);
1118 if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
1119 return I->getOperand(1);
1121 break;
1123 case Instruction::Or: {
1124 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1125 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1126 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1127 Depth, SQ.getWithInstruction(CxtI));
1128 computeKnownBitsFromContext(I, Known, Depth, SQ.getWithInstruction(CxtI));
1130 // If the client is only demanding bits that we know, return the known
1131 // constant.
1132 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1133 return Constant::getIntegerValue(ITy, Known.One);
1135 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1136 // only bits from X or Y are demanded.
1137 // If all of the demanded bits are known zero on one side, return the other.
1138 // These bits cannot contribute to the result of the 'or' in this context.
1139 if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
1140 return I->getOperand(0);
1141 if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
1142 return I->getOperand(1);
1144 break;
1146 case Instruction::Xor: {
1147 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1148 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1149 Known = analyzeKnownBitsFromAndXorOr(cast<Operator>(I), LHSKnown, RHSKnown,
1150 Depth, SQ.getWithInstruction(CxtI));
1151 computeKnownBitsFromContext(I, Known, Depth, SQ.getWithInstruction(CxtI));
1153 // If the client is only demanding bits that we know, return the known
1154 // constant.
1155 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1156 return Constant::getIntegerValue(ITy, Known.One);
1158 // We can simplify (X^Y) -> X or Y in the user's context if we know that
1159 // only bits from X or Y are demanded.
1160 // If all of the demanded bits are known zero on one side, return the other.
1161 if (DemandedMask.isSubsetOf(RHSKnown.Zero))
1162 return I->getOperand(0);
1163 if (DemandedMask.isSubsetOf(LHSKnown.Zero))
1164 return I->getOperand(1);
1166 break;
1168 case Instruction::Add: {
1169 unsigned NLZ = DemandedMask.countl_zero();
1170 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1172 // If an operand adds zeros to every bit below the highest demanded bit,
1173 // that operand doesn't change the result. Return the other side.
1174 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1175 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1176 return I->getOperand(0);
1178 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1179 if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1180 return I->getOperand(1);
1182 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1183 Known = KnownBits::computeForAddSub(/*Add*/ true, NSW, LHSKnown, RHSKnown);
1184 computeKnownBitsFromContext(I, Known, Depth, SQ.getWithInstruction(CxtI));
1185 break;
1187 case Instruction::Sub: {
1188 unsigned NLZ = DemandedMask.countl_zero();
1189 APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1191 // If an operand subtracts zeros from every bit below the highest demanded
1192 // bit, that operand doesn't change the result. Return the other side.
1193 computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1194 if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1195 return I->getOperand(0);
1197 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
1198 computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1199 Known = KnownBits::computeForAddSub(/*Add*/ false, NSW, LHSKnown, RHSKnown);
1200 computeKnownBitsFromContext(I, Known, Depth, SQ.getWithInstruction(CxtI));
1201 break;
1203 case Instruction::AShr: {
1204 // Compute the Known bits to simplify things downstream.
1205 computeKnownBits(I, Known, Depth, CxtI);
1207 // If this user is only demanding bits that we know, return the known
1208 // constant.
1209 if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1210 return Constant::getIntegerValue(ITy, Known.One);
1212 // If the right shift operand 0 is a result of a left shift by the same
1213 // amount, this is probably a zero/sign extension, which may be unnecessary,
1214 // if we do not demand any of the new sign bits. So, return the original
1215 // operand instead.
1216 const APInt *ShiftRC;
1217 const APInt *ShiftLC;
1218 Value *X;
1219 unsigned BitWidth = DemandedMask.getBitWidth();
1220 if (match(I,
1221 m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
1222 ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
1223 DemandedMask.isSubsetOf(APInt::getLowBitsSet(
1224 BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
1225 return X;
1228 break;
1230 default:
1231 // Compute the Known bits to simplify things downstream.
1232 computeKnownBits(I, Known, Depth, CxtI);
1234 // If this user is only demanding bits that we know, return the known
1235 // constant.
1236 if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
1237 return Constant::getIntegerValue(ITy, Known.One);
1239 break;
1242 return nullptr;
1245 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
1246 /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
1247 /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
1248 /// of "C2-C1".
1250 /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
1251 /// ..., bn}, without considering the specific value X is holding.
1252 /// This transformation is legal iff one of following conditions is hold:
1253 /// 1) All the bit in S are 0, in this case E1 == E2.
1254 /// 2) We don't care those bits in S, per the input DemandedMask.
1255 /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
1256 /// rest bits.
1258 /// Currently we only test condition 2).
1260 /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
1261 /// not successful.
1262 Value *InstCombinerImpl::simplifyShrShlDemandedBits(
1263 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
1264 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
1265 if (!ShlOp1 || !ShrOp1)
1266 return nullptr; // No-op.
1268 Value *VarX = Shr->getOperand(0);
1269 Type *Ty = VarX->getType();
1270 unsigned BitWidth = Ty->getScalarSizeInBits();
1271 if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
1272 return nullptr; // Undef.
1274 unsigned ShlAmt = ShlOp1.getZExtValue();
1275 unsigned ShrAmt = ShrOp1.getZExtValue();
1277 Known.One.clearAllBits();
1278 Known.Zero.setLowBits(ShlAmt - 1);
1279 Known.Zero &= DemandedMask;
1281 APInt BitMask1(APInt::getAllOnes(BitWidth));
1282 APInt BitMask2(APInt::getAllOnes(BitWidth));
1284 bool isLshr = (Shr->getOpcode() == Instruction::LShr);
1285 BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
1286 (BitMask1.ashr(ShrAmt) << ShlAmt);
1288 if (ShrAmt <= ShlAmt) {
1289 BitMask2 <<= (ShlAmt - ShrAmt);
1290 } else {
1291 BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
1292 BitMask2.ashr(ShrAmt - ShlAmt);
1295 // Check if condition-2 (see the comment to this function) is satified.
1296 if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
1297 if (ShrAmt == ShlAmt)
1298 return VarX;
1300 if (!Shr->hasOneUse())
1301 return nullptr;
1303 BinaryOperator *New;
1304 if (ShrAmt < ShlAmt) {
1305 Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
1306 New = BinaryOperator::CreateShl(VarX, Amt);
1307 BinaryOperator *Orig = cast<BinaryOperator>(Shl);
1308 New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
1309 New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
1310 } else {
1311 Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
1312 New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
1313 BinaryOperator::CreateAShr(VarX, Amt);
1314 if (cast<BinaryOperator>(Shr)->isExact())
1315 New->setIsExact(true);
1318 return InsertNewInstWith(New, Shl->getIterator());
1321 return nullptr;
1324 /// The specified value produces a vector with any number of elements.
1325 /// This method analyzes which elements of the operand are poison and
1326 /// returns that information in PoisonElts.
1328 /// DemandedElts contains the set of elements that are actually used by the
1329 /// caller, and by default (AllowMultipleUsers equals false) the value is
1330 /// simplified only if it has a single caller. If AllowMultipleUsers is set
1331 /// to true, DemandedElts refers to the union of sets of elements that are
1332 /// used by all callers.
1334 /// If the information about demanded elements can be used to simplify the
1335 /// operation, the operation is simplified, then the resultant value is
1336 /// returned. This returns null if no change was made.
1337 Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V,
1338 APInt DemandedElts,
1339 APInt &PoisonElts,
1340 unsigned Depth,
1341 bool AllowMultipleUsers) {
1342 // Cannot analyze scalable type. The number of vector elements is not a
1343 // compile-time constant.
1344 if (isa<ScalableVectorType>(V->getType()))
1345 return nullptr;
1347 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1348 APInt EltMask(APInt::getAllOnes(VWidth));
1349 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1351 if (match(V, m_Poison())) {
1352 // If the entire vector is poison, just return this info.
1353 PoisonElts = EltMask;
1354 return nullptr;
1357 if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
1358 PoisonElts = EltMask;
1359 return PoisonValue::get(V->getType());
1362 PoisonElts = 0;
1364 if (auto *C = dyn_cast<Constant>(V)) {
1365 // Check if this is identity. If so, return 0 since we are not simplifying
1366 // anything.
1367 if (DemandedElts.isAllOnes())
1368 return nullptr;
1370 Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1371 Constant *Poison = PoisonValue::get(EltTy);
1372 SmallVector<Constant*, 16> Elts;
1373 for (unsigned i = 0; i != VWidth; ++i) {
1374 if (!DemandedElts[i]) { // If not demanded, set to poison.
1375 Elts.push_back(Poison);
1376 PoisonElts.setBit(i);
1377 continue;
1380 Constant *Elt = C->getAggregateElement(i);
1381 if (!Elt) return nullptr;
1383 Elts.push_back(Elt);
1384 if (isa<PoisonValue>(Elt)) // Already poison.
1385 PoisonElts.setBit(i);
1388 // If we changed the constant, return it.
1389 Constant *NewCV = ConstantVector::get(Elts);
1390 return NewCV != C ? NewCV : nullptr;
1393 // Limit search depth.
1394 if (Depth == 10)
1395 return nullptr;
1397 if (!AllowMultipleUsers) {
1398 // If multiple users are using the root value, proceed with
1399 // simplification conservatively assuming that all elements
1400 // are needed.
1401 if (!V->hasOneUse()) {
1402 // Quit if we find multiple users of a non-root value though.
1403 // They'll be handled when it's their turn to be visited by
1404 // the main instcombine process.
1405 if (Depth != 0)
1406 // TODO: Just compute the PoisonElts information recursively.
1407 return nullptr;
1409 // Conservatively assume that all elements are needed.
1410 DemandedElts = EltMask;
1414 Instruction *I = dyn_cast<Instruction>(V);
1415 if (!I) return nullptr; // Only analyze instructions.
1417 bool MadeChange = false;
1418 auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
1419 APInt Demanded, APInt &Undef) {
1420 auto *II = dyn_cast<IntrinsicInst>(Inst);
1421 Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
1422 if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1423 replaceOperand(*Inst, OpNum, V);
1424 MadeChange = true;
1428 APInt PoisonElts2(VWidth, 0);
1429 APInt PoisonElts3(VWidth, 0);
1430 switch (I->getOpcode()) {
1431 default: break;
1433 case Instruction::GetElementPtr: {
1434 // The LangRef requires that struct geps have all constant indices. As
1435 // such, we can't convert any operand to partial undef.
1436 auto mayIndexStructType = [](GetElementPtrInst &GEP) {
1437 for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
1438 I != E; I++)
1439 if (I.isStruct())
1440 return true;
1441 return false;
1443 if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
1444 break;
1446 // Conservatively track the demanded elements back through any vector
1447 // operands we may have. We know there must be at least one, or we
1448 // wouldn't have a vector result to get here. Note that we intentionally
1449 // merge the undef bits here since gepping with either an poison base or
1450 // index results in poison.
1451 for (unsigned i = 0; i < I->getNumOperands(); i++) {
1452 if (i == 0 ? match(I->getOperand(i), m_Undef())
1453 : match(I->getOperand(i), m_Poison())) {
1454 // If the entire vector is undefined, just return this info.
1455 PoisonElts = EltMask;
1456 return nullptr;
1458 if (I->getOperand(i)->getType()->isVectorTy()) {
1459 APInt PoisonEltsOp(VWidth, 0);
1460 simplifyAndSetOp(I, i, DemandedElts, PoisonEltsOp);
1461 // gep(x, undef) is not undef, so skip considering idx ops here
1462 // Note that we could propagate poison, but we can't distinguish between
1463 // undef & poison bits ATM
1464 if (i == 0)
1465 PoisonElts |= PoisonEltsOp;
1469 break;
1471 case Instruction::InsertElement: {
1472 // If this is a variable index, we don't know which element it overwrites.
1473 // demand exactly the same input as we produce.
1474 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1475 if (!Idx) {
1476 // Note that we can't propagate undef elt info, because we don't know
1477 // which elt is getting updated.
1478 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts2);
1479 break;
1482 // The element inserted overwrites whatever was there, so the input demanded
1483 // set is simpler than the output set.
1484 unsigned IdxNo = Idx->getZExtValue();
1485 APInt PreInsertDemandedElts = DemandedElts;
1486 if (IdxNo < VWidth)
1487 PreInsertDemandedElts.clearBit(IdxNo);
1489 // If we only demand the element that is being inserted and that element
1490 // was extracted from the same index in another vector with the same type,
1491 // replace this insert with that other vector.
1492 // Note: This is attempted before the call to simplifyAndSetOp because that
1493 // may change PoisonElts to a value that does not match with Vec.
1494 Value *Vec;
1495 if (PreInsertDemandedElts == 0 &&
1496 match(I->getOperand(1),
1497 m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
1498 Vec->getType() == I->getType()) {
1499 return Vec;
1502 simplifyAndSetOp(I, 0, PreInsertDemandedElts, PoisonElts);
1504 // If this is inserting an element that isn't demanded, remove this
1505 // insertelement.
1506 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1507 Worklist.push(I);
1508 return I->getOperand(0);
1511 // The inserted element is defined.
1512 PoisonElts.clearBit(IdxNo);
1513 break;
1515 case Instruction::ShuffleVector: {
1516 auto *Shuffle = cast<ShuffleVectorInst>(I);
1517 assert(Shuffle->getOperand(0)->getType() ==
1518 Shuffle->getOperand(1)->getType() &&
1519 "Expected shuffle operands to have same type");
1520 unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
1521 ->getNumElements();
1522 // Handle trivial case of a splat. Only check the first element of LHS
1523 // operand.
1524 if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1525 DemandedElts.isAllOnes()) {
1526 if (!isa<PoisonValue>(I->getOperand(1))) {
1527 I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1528 MadeChange = true;
1530 APInt LeftDemanded(OpWidth, 1);
1531 APInt LHSPoisonElts(OpWidth, 0);
1532 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1533 if (LHSPoisonElts[0])
1534 PoisonElts = EltMask;
1535 else
1536 PoisonElts.clearAllBits();
1537 break;
1540 APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
1541 for (unsigned i = 0; i < VWidth; i++) {
1542 if (DemandedElts[i]) {
1543 unsigned MaskVal = Shuffle->getMaskValue(i);
1544 if (MaskVal != -1u) {
1545 assert(MaskVal < OpWidth * 2 &&
1546 "shufflevector mask index out of range!");
1547 if (MaskVal < OpWidth)
1548 LeftDemanded.setBit(MaskVal);
1549 else
1550 RightDemanded.setBit(MaskVal - OpWidth);
1555 APInt LHSPoisonElts(OpWidth, 0);
1556 simplifyAndSetOp(I, 0, LeftDemanded, LHSPoisonElts);
1558 APInt RHSPoisonElts(OpWidth, 0);
1559 simplifyAndSetOp(I, 1, RightDemanded, RHSPoisonElts);
1561 // If this shuffle does not change the vector length and the elements
1562 // demanded by this shuffle are an identity mask, then this shuffle is
1563 // unnecessary.
1565 // We are assuming canonical form for the mask, so the source vector is
1566 // operand 0 and operand 1 is not used.
1568 // Note that if an element is demanded and this shuffle mask is undefined
1569 // for that element, then the shuffle is not considered an identity
1570 // operation. The shuffle prevents poison from the operand vector from
1571 // leaking to the result by replacing poison with an undefined value.
1572 if (VWidth == OpWidth) {
1573 bool IsIdentityShuffle = true;
1574 for (unsigned i = 0; i < VWidth; i++) {
1575 unsigned MaskVal = Shuffle->getMaskValue(i);
1576 if (DemandedElts[i] && i != MaskVal) {
1577 IsIdentityShuffle = false;
1578 break;
1581 if (IsIdentityShuffle)
1582 return Shuffle->getOperand(0);
1585 bool NewPoisonElts = false;
1586 unsigned LHSIdx = -1u, LHSValIdx = -1u;
1587 unsigned RHSIdx = -1u, RHSValIdx = -1u;
1588 bool LHSUniform = true;
1589 bool RHSUniform = true;
1590 for (unsigned i = 0; i < VWidth; i++) {
1591 unsigned MaskVal = Shuffle->getMaskValue(i);
1592 if (MaskVal == -1u) {
1593 PoisonElts.setBit(i);
1594 } else if (!DemandedElts[i]) {
1595 NewPoisonElts = true;
1596 PoisonElts.setBit(i);
1597 } else if (MaskVal < OpWidth) {
1598 if (LHSPoisonElts[MaskVal]) {
1599 NewPoisonElts = true;
1600 PoisonElts.setBit(i);
1601 } else {
1602 LHSIdx = LHSIdx == -1u ? i : OpWidth;
1603 LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
1604 LHSUniform = LHSUniform && (MaskVal == i);
1606 } else {
1607 if (RHSPoisonElts[MaskVal - OpWidth]) {
1608 NewPoisonElts = true;
1609 PoisonElts.setBit(i);
1610 } else {
1611 RHSIdx = RHSIdx == -1u ? i : OpWidth;
1612 RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
1613 RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
1618 // Try to transform shuffle with constant vector and single element from
1619 // this constant vector to single insertelement instruction.
1620 // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
1621 // insertelement V, C[ci], ci-n
1622 if (OpWidth ==
1623 cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
1624 Value *Op = nullptr;
1625 Constant *Value = nullptr;
1626 unsigned Idx = -1u;
1628 // Find constant vector with the single element in shuffle (LHS or RHS).
1629 if (LHSIdx < OpWidth && RHSUniform) {
1630 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
1631 Op = Shuffle->getOperand(1);
1632 Value = CV->getOperand(LHSValIdx);
1633 Idx = LHSIdx;
1636 if (RHSIdx < OpWidth && LHSUniform) {
1637 if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
1638 Op = Shuffle->getOperand(0);
1639 Value = CV->getOperand(RHSValIdx);
1640 Idx = RHSIdx;
1643 // Found constant vector with single element - convert to insertelement.
1644 if (Op && Value) {
1645 Instruction *New = InsertElementInst::Create(
1646 Op, Value, ConstantInt::get(Type::getInt64Ty(I->getContext()), Idx),
1647 Shuffle->getName());
1648 InsertNewInstWith(New, Shuffle->getIterator());
1649 return New;
1652 if (NewPoisonElts) {
1653 // Add additional discovered undefs.
1654 SmallVector<int, 16> Elts;
1655 for (unsigned i = 0; i < VWidth; ++i) {
1656 if (PoisonElts[i])
1657 Elts.push_back(PoisonMaskElem);
1658 else
1659 Elts.push_back(Shuffle->getMaskValue(i));
1661 Shuffle->setShuffleMask(Elts);
1662 MadeChange = true;
1664 break;
1666 case Instruction::Select: {
1667 // If this is a vector select, try to transform the select condition based
1668 // on the current demanded elements.
1669 SelectInst *Sel = cast<SelectInst>(I);
1670 if (Sel->getCondition()->getType()->isVectorTy()) {
1671 // TODO: We are not doing anything with PoisonElts based on this call.
1672 // It is overwritten below based on the other select operands. If an
1673 // element of the select condition is known undef, then we are free to
1674 // choose the output value from either arm of the select. If we know that
1675 // one of those values is undef, then the output can be undef.
1676 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1679 // Next, see if we can transform the arms of the select.
1680 APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
1681 if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
1682 for (unsigned i = 0; i < VWidth; i++) {
1683 // isNullValue() always returns false when called on a ConstantExpr.
1684 // Skip constant expressions to avoid propagating incorrect information.
1685 Constant *CElt = CV->getAggregateElement(i);
1686 if (isa<ConstantExpr>(CElt))
1687 continue;
1688 // TODO: If a select condition element is undef, we can demand from
1689 // either side. If one side is known undef, choosing that side would
1690 // propagate undef.
1691 if (CElt->isNullValue())
1692 DemandedLHS.clearBit(i);
1693 else
1694 DemandedRHS.clearBit(i);
1698 simplifyAndSetOp(I, 1, DemandedLHS, PoisonElts2);
1699 simplifyAndSetOp(I, 2, DemandedRHS, PoisonElts3);
1701 // Output elements are undefined if the element from each arm is undefined.
1702 // TODO: This can be improved. See comment in select condition handling.
1703 PoisonElts = PoisonElts2 & PoisonElts3;
1704 break;
1706 case Instruction::BitCast: {
1707 // Vector->vector casts only.
1708 VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1709 if (!VTy) break;
1710 unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
1711 APInt InputDemandedElts(InVWidth, 0);
1712 PoisonElts2 = APInt(InVWidth, 0);
1713 unsigned Ratio;
1715 if (VWidth == InVWidth) {
1716 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1717 // elements as are demanded of us.
1718 Ratio = 1;
1719 InputDemandedElts = DemandedElts;
1720 } else if ((VWidth % InVWidth) == 0) {
1721 // If the number of elements in the output is a multiple of the number of
1722 // elements in the input then an input element is live if any of the
1723 // corresponding output elements are live.
1724 Ratio = VWidth / InVWidth;
1725 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1726 if (DemandedElts[OutIdx])
1727 InputDemandedElts.setBit(OutIdx / Ratio);
1728 } else if ((InVWidth % VWidth) == 0) {
1729 // If the number of elements in the input is a multiple of the number of
1730 // elements in the output then an input element is live if the
1731 // corresponding output element is live.
1732 Ratio = InVWidth / VWidth;
1733 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1734 if (DemandedElts[InIdx / Ratio])
1735 InputDemandedElts.setBit(InIdx);
1736 } else {
1737 // Unsupported so far.
1738 break;
1741 simplifyAndSetOp(I, 0, InputDemandedElts, PoisonElts2);
1743 if (VWidth == InVWidth) {
1744 PoisonElts = PoisonElts2;
1745 } else if ((VWidth % InVWidth) == 0) {
1746 // If the number of elements in the output is a multiple of the number of
1747 // elements in the input then an output element is undef if the
1748 // corresponding input element is undef.
1749 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1750 if (PoisonElts2[OutIdx / Ratio])
1751 PoisonElts.setBit(OutIdx);
1752 } else if ((InVWidth % VWidth) == 0) {
1753 // If the number of elements in the input is a multiple of the number of
1754 // elements in the output then an output element is undef if all of the
1755 // corresponding input elements are undef.
1756 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1757 APInt SubUndef = PoisonElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
1758 if (SubUndef.popcount() == Ratio)
1759 PoisonElts.setBit(OutIdx);
1761 } else {
1762 llvm_unreachable("Unimp");
1764 break;
1766 case Instruction::FPTrunc:
1767 case Instruction::FPExt:
1768 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1769 break;
1771 case Instruction::Call: {
1772 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1773 if (!II) break;
1774 switch (II->getIntrinsicID()) {
1775 case Intrinsic::masked_gather: // fallthrough
1776 case Intrinsic::masked_load: {
1777 // Subtlety: If we load from a pointer, the pointer must be valid
1778 // regardless of whether the element is demanded. Doing otherwise risks
1779 // segfaults which didn't exist in the original program.
1780 APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
1781 DemandedPassThrough(DemandedElts);
1782 if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
1783 for (unsigned i = 0; i < VWidth; i++) {
1784 Constant *CElt = CV->getAggregateElement(i);
1785 if (CElt->isNullValue())
1786 DemandedPtrs.clearBit(i);
1787 else if (CElt->isAllOnesValue())
1788 DemandedPassThrough.clearBit(i);
1790 if (II->getIntrinsicID() == Intrinsic::masked_gather)
1791 simplifyAndSetOp(II, 0, DemandedPtrs, PoisonElts2);
1792 simplifyAndSetOp(II, 3, DemandedPassThrough, PoisonElts3);
1794 // Output elements are undefined if the element from both sources are.
1795 // TODO: can strengthen via mask as well.
1796 PoisonElts = PoisonElts2 & PoisonElts3;
1797 break;
1799 default: {
1800 // Handle target specific intrinsics
1801 std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
1802 *II, DemandedElts, PoisonElts, PoisonElts2, PoisonElts3,
1803 simplifyAndSetOp);
1804 if (V)
1805 return *V;
1806 break;
1808 } // switch on IntrinsicID
1809 break;
1810 } // case Call
1811 } // switch on Opcode
1813 // TODO: We bail completely on integer div/rem and shifts because they have
1814 // UB/poison potential, but that should be refined.
1815 BinaryOperator *BO;
1816 if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
1817 Value *X = BO->getOperand(0);
1818 Value *Y = BO->getOperand(1);
1820 // Look for an equivalent binop except that one operand has been shuffled.
1821 // If the demand for this binop only includes elements that are the same as
1822 // the other binop, then we may be able to replace this binop with a use of
1823 // the earlier one.
1825 // Example:
1826 // %other_bo = bo (shuf X, {0}), Y
1827 // %this_extracted_bo = extelt (bo X, Y), 0
1828 // -->
1829 // %other_bo = bo (shuf X, {0}), Y
1830 // %this_extracted_bo = extelt %other_bo, 0
1832 // TODO: Handle demand of an arbitrary single element or more than one
1833 // element instead of just element 0.
1834 // TODO: Unlike general demanded elements transforms, this should be safe
1835 // for any (div/rem/shift) opcode too.
1836 if (DemandedElts == 1 && !X->hasOneUse() && !Y->hasOneUse() &&
1837 BO->hasOneUse() ) {
1839 auto findShufBO = [&](bool MatchShufAsOp0) -> User * {
1840 // Try to use shuffle-of-operand in place of an operand:
1841 // bo X, Y --> bo (shuf X), Y
1842 // bo X, Y --> bo X, (shuf Y)
1843 BinaryOperator::BinaryOps Opcode = BO->getOpcode();
1844 Value *ShufOp = MatchShufAsOp0 ? X : Y;
1845 Value *OtherOp = MatchShufAsOp0 ? Y : X;
1846 for (User *U : OtherOp->users()) {
1847 auto Shuf = m_Shuffle(m_Specific(ShufOp), m_Value(), m_ZeroMask());
1848 if (BO->isCommutative()
1849 ? match(U, m_c_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1850 : MatchShufAsOp0
1851 ? match(U, m_BinOp(Opcode, Shuf, m_Specific(OtherOp)))
1852 : match(U, m_BinOp(Opcode, m_Specific(OtherOp), Shuf)))
1853 if (DT.dominates(U, I))
1854 return U;
1856 return nullptr;
1859 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ true))
1860 return ShufBO;
1861 if (User *ShufBO = findShufBO(/* MatchShufAsOp0 */ false))
1862 return ShufBO;
1865 simplifyAndSetOp(I, 0, DemandedElts, PoisonElts);
1866 simplifyAndSetOp(I, 1, DemandedElts, PoisonElts2);
1868 // Output elements are undefined if both are undefined. Consider things
1869 // like undef & 0. The result is known zero, not undef.
1870 PoisonElts &= PoisonElts2;
1873 // If we've proven all of the lanes poison, return a poison value.
1874 // TODO: Intersect w/demanded lanes
1875 if (PoisonElts.isAllOnes())
1876 return PoisonValue::get(I->getType());
1878 return MadeChange ? I : nullptr;