109467b48Spatrick //===- InstCombineSimplifyDemanded.cpp ------------------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file contains logic for simplifying instructions based on information
1009467b48Spatrick // about how they are used.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick
1409467b48Spatrick #include "InstCombineInternal.h"
1509467b48Spatrick #include "llvm/Analysis/ValueTracking.h"
16*d415bd75Srobert #include "llvm/IR/GetElementPtrTypeIterator.h"
1709467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
1809467b48Spatrick #include "llvm/IR/PatternMatch.h"
1909467b48Spatrick #include "llvm/Support/KnownBits.h"
2073471bf0Spatrick #include "llvm/Transforms/InstCombine/InstCombiner.h"
2109467b48Spatrick
2209467b48Spatrick using namespace llvm;
2309467b48Spatrick using namespace llvm::PatternMatch;
2409467b48Spatrick
2509467b48Spatrick #define DEBUG_TYPE "instcombine"
2609467b48Spatrick
2709467b48Spatrick /// Check to see if the specified operand of the specified instruction is a
2809467b48Spatrick /// constant integer. If so, check to see if there are any bits set in the
2909467b48Spatrick /// constant that are not demanded. If so, shrink the constant and return true.
ShrinkDemandedConstant(Instruction * I,unsigned OpNo,const APInt & Demanded)3009467b48Spatrick static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
3109467b48Spatrick const APInt &Demanded) {
3209467b48Spatrick assert(I && "No instruction?");
3309467b48Spatrick assert(OpNo < I->getNumOperands() && "Operand index too large");
3409467b48Spatrick
3509467b48Spatrick // The operand must be a constant integer or splat integer.
3609467b48Spatrick Value *Op = I->getOperand(OpNo);
3709467b48Spatrick const APInt *C;
3809467b48Spatrick if (!match(Op, m_APInt(C)))
3909467b48Spatrick return false;
4009467b48Spatrick
4109467b48Spatrick // If there are no bits set that aren't demanded, nothing to do.
4209467b48Spatrick if (C->isSubsetOf(Demanded))
4309467b48Spatrick return false;
4409467b48Spatrick
4509467b48Spatrick // This instruction is producing bits that are not demanded. Shrink the RHS.
4609467b48Spatrick I->setOperand(OpNo, ConstantInt::get(Op->getType(), *C & Demanded));
4709467b48Spatrick
4809467b48Spatrick return true;
4909467b48Spatrick }
5009467b48Spatrick
5109467b48Spatrick
5209467b48Spatrick
5309467b48Spatrick /// Inst is an integer instruction that SimplifyDemandedBits knows about. See if
5409467b48Spatrick /// the instruction has any properties that allow us to simplify its operands.
SimplifyDemandedInstructionBits(Instruction & Inst)5573471bf0Spatrick bool InstCombinerImpl::SimplifyDemandedInstructionBits(Instruction &Inst) {
5609467b48Spatrick unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
5709467b48Spatrick KnownBits Known(BitWidth);
58*d415bd75Srobert APInt DemandedMask(APInt::getAllOnes(BitWidth));
5909467b48Spatrick
6009467b48Spatrick Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, Known,
6109467b48Spatrick 0, &Inst);
6209467b48Spatrick if (!V) return false;
6309467b48Spatrick if (V == &Inst) return true;
6409467b48Spatrick replaceInstUsesWith(Inst, V);
6509467b48Spatrick return true;
6609467b48Spatrick }
6709467b48Spatrick
6809467b48Spatrick /// This form of SimplifyDemandedBits simplifies the specified instruction
6909467b48Spatrick /// operand if possible, updating it in place. It returns true if it made any
7009467b48Spatrick /// change and false otherwise.
SimplifyDemandedBits(Instruction * I,unsigned OpNo,const APInt & DemandedMask,KnownBits & Known,unsigned Depth)7173471bf0Spatrick bool InstCombinerImpl::SimplifyDemandedBits(Instruction *I, unsigned OpNo,
7209467b48Spatrick const APInt &DemandedMask,
7373471bf0Spatrick KnownBits &Known, unsigned Depth) {
7409467b48Spatrick Use &U = I->getOperandUse(OpNo);
7509467b48Spatrick Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask, Known,
7609467b48Spatrick Depth, I);
7709467b48Spatrick if (!NewVal) return false;
78097a140dSpatrick if (Instruction* OpInst = dyn_cast<Instruction>(U))
79097a140dSpatrick salvageDebugInfo(*OpInst);
80097a140dSpatrick
81097a140dSpatrick replaceUse(U, NewVal);
8209467b48Spatrick return true;
8309467b48Spatrick }
8409467b48Spatrick
8509467b48Spatrick /// This function attempts to replace V with a simpler value based on the
8609467b48Spatrick /// demanded bits. When this function is called, it is known that only the bits
8709467b48Spatrick /// set in DemandedMask of the result of V are ever used downstream.
8809467b48Spatrick /// Consequently, depending on the mask and V, it may be possible to replace V
8909467b48Spatrick /// with a constant or one of its operands. In such cases, this function does
9009467b48Spatrick /// the replacement and returns true. In all other cases, it returns false after
9109467b48Spatrick /// analyzing the expression and setting KnownOne and known to be one in the
9209467b48Spatrick /// expression. Known.Zero contains all the bits that are known to be zero in
9309467b48Spatrick /// the expression. These are provided to potentially allow the caller (which
9409467b48Spatrick /// might recursively be SimplifyDemandedBits itself) to simplify the
9509467b48Spatrick /// expression.
9609467b48Spatrick /// Known.One and Known.Zero always follow the invariant that:
9709467b48Spatrick /// Known.One & Known.Zero == 0.
9809467b48Spatrick /// That is, a bit can't be both 1 and 0. Note that the bits in Known.One and
9909467b48Spatrick /// Known.Zero may only be accurate for those bits set in DemandedMask. Note
10009467b48Spatrick /// also that the bitwidth of V, DemandedMask, Known.Zero and Known.One must all
10109467b48Spatrick /// be the same.
10209467b48Spatrick ///
10309467b48Spatrick /// This returns null if it did not change anything and it permits no
10409467b48Spatrick /// simplification. This returns V itself if it did some simplification of V's
10509467b48Spatrick /// operands based on the information about what bits are demanded. This returns
10609467b48Spatrick /// some other non-null value if it found out that V is equal to another value
10709467b48Spatrick /// in the context where the specified bits are demanded, but not for all users.
SimplifyDemandedUseBits(Value * V,APInt DemandedMask,KnownBits & Known,unsigned Depth,Instruction * CxtI)10873471bf0Spatrick Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
10973471bf0Spatrick KnownBits &Known,
11073471bf0Spatrick unsigned Depth,
11109467b48Spatrick Instruction *CxtI) {
11209467b48Spatrick assert(V != nullptr && "Null pointer of Value???");
11373471bf0Spatrick assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
11409467b48Spatrick uint32_t BitWidth = DemandedMask.getBitWidth();
11509467b48Spatrick Type *VTy = V->getType();
11609467b48Spatrick assert(
11709467b48Spatrick (!VTy->isIntOrIntVectorTy() || VTy->getScalarSizeInBits() == BitWidth) &&
11809467b48Spatrick Known.getBitWidth() == BitWidth &&
11909467b48Spatrick "Value *V, DemandedMask and Known must have same BitWidth");
12009467b48Spatrick
12109467b48Spatrick if (isa<Constant>(V)) {
12209467b48Spatrick computeKnownBits(V, Known, Depth, CxtI);
12309467b48Spatrick return nullptr;
12409467b48Spatrick }
12509467b48Spatrick
12609467b48Spatrick Known.resetAll();
127*d415bd75Srobert if (DemandedMask.isZero()) // Not demanding any bits from V.
12809467b48Spatrick return UndefValue::get(VTy);
12909467b48Spatrick
13073471bf0Spatrick if (Depth == MaxAnalysisRecursionDepth)
13173471bf0Spatrick return nullptr;
13273471bf0Spatrick
13309467b48Spatrick Instruction *I = dyn_cast<Instruction>(V);
13409467b48Spatrick if (!I) {
13509467b48Spatrick computeKnownBits(V, Known, Depth, CxtI);
13609467b48Spatrick return nullptr; // Only analyze instructions.
13709467b48Spatrick }
13809467b48Spatrick
13909467b48Spatrick // If there are multiple uses of this value and we aren't at the root, then
14009467b48Spatrick // we can't do any simplifications of the operands, because DemandedMask
14109467b48Spatrick // only reflects the bits demanded by *one* of the users.
14209467b48Spatrick if (Depth != 0 && !I->hasOneUse())
14309467b48Spatrick return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, CxtI);
14409467b48Spatrick
14509467b48Spatrick KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
14609467b48Spatrick
14709467b48Spatrick // If this is the root being simplified, allow it to have multiple uses,
14809467b48Spatrick // just set the DemandedMask to all bits so that we can try to simplify the
14909467b48Spatrick // operands. This allows visitTruncInst (for example) to simplify the
15009467b48Spatrick // operand of a trunc without duplicating all the logic below.
15109467b48Spatrick if (Depth == 0 && !V->hasOneUse())
15209467b48Spatrick DemandedMask.setAllBits();
15309467b48Spatrick
154*d415bd75Srobert // Update flags after simplifying an operand based on the fact that some high
155*d415bd75Srobert // order bits are not demanded.
156*d415bd75Srobert auto disableWrapFlagsBasedOnUnusedHighBits = [](Instruction *I,
157*d415bd75Srobert unsigned NLZ) {
158*d415bd75Srobert if (NLZ > 0) {
159*d415bd75Srobert // Disable the nsw and nuw flags here: We can no longer guarantee that
160*d415bd75Srobert // we won't wrap after simplification. Removing the nsw/nuw flags is
161*d415bd75Srobert // legal here because the top bit is not demanded.
162*d415bd75Srobert I->setHasNoSignedWrap(false);
163*d415bd75Srobert I->setHasNoUnsignedWrap(false);
164*d415bd75Srobert }
165*d415bd75Srobert return I;
166*d415bd75Srobert };
167*d415bd75Srobert
168*d415bd75Srobert // If the high-bits of an ADD/SUB/MUL are not demanded, then we do not care
169*d415bd75Srobert // about the high bits of the operands.
170*d415bd75Srobert auto simplifyOperandsBasedOnUnusedHighBits = [&](APInt &DemandedFromOps) {
171*d415bd75Srobert unsigned NLZ = DemandedMask.countLeadingZeros();
172*d415bd75Srobert // Right fill the mask of bits for the operands to demand the most
173*d415bd75Srobert // significant bit and all those below it.
174*d415bd75Srobert DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
175*d415bd75Srobert if (ShrinkDemandedConstant(I, 0, DemandedFromOps) ||
176*d415bd75Srobert SimplifyDemandedBits(I, 0, DemandedFromOps, LHSKnown, Depth + 1) ||
177*d415bd75Srobert ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
178*d415bd75Srobert SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1)) {
179*d415bd75Srobert disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
180*d415bd75Srobert return true;
181*d415bd75Srobert }
182*d415bd75Srobert return false;
183*d415bd75Srobert };
184*d415bd75Srobert
18509467b48Spatrick switch (I->getOpcode()) {
18609467b48Spatrick default:
18709467b48Spatrick computeKnownBits(I, Known, Depth, CxtI);
18809467b48Spatrick break;
18909467b48Spatrick case Instruction::And: {
19009467b48Spatrick // If either the LHS or the RHS are Zero, the result is zero.
19109467b48Spatrick if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
19209467b48Spatrick SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.Zero, LHSKnown,
19309467b48Spatrick Depth + 1))
19409467b48Spatrick return I;
19509467b48Spatrick assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
19609467b48Spatrick assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
19709467b48Spatrick
198097a140dSpatrick Known = LHSKnown & RHSKnown;
19909467b48Spatrick
20009467b48Spatrick // If the client is only demanding bits that we know, return the known
20109467b48Spatrick // constant.
202097a140dSpatrick if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
203097a140dSpatrick return Constant::getIntegerValue(VTy, Known.One);
20409467b48Spatrick
20509467b48Spatrick // If all of the demanded bits are known 1 on one side, return the other.
20609467b48Spatrick // These bits cannot contribute to the result of the 'and'.
20709467b48Spatrick if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
20809467b48Spatrick return I->getOperand(0);
20909467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
21009467b48Spatrick return I->getOperand(1);
21109467b48Spatrick
21209467b48Spatrick // If the RHS is a constant, see if we can simplify it.
21309467b48Spatrick if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnown.Zero))
21409467b48Spatrick return I;
21509467b48Spatrick
21609467b48Spatrick break;
21709467b48Spatrick }
21809467b48Spatrick case Instruction::Or: {
21909467b48Spatrick // If either the LHS or the RHS are One, the result is One.
22009467b48Spatrick if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
22109467b48Spatrick SimplifyDemandedBits(I, 0, DemandedMask & ~RHSKnown.One, LHSKnown,
22209467b48Spatrick Depth + 1))
22309467b48Spatrick return I;
22409467b48Spatrick assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
22509467b48Spatrick assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
22609467b48Spatrick
227097a140dSpatrick Known = LHSKnown | RHSKnown;
22809467b48Spatrick
22909467b48Spatrick // If the client is only demanding bits that we know, return the known
23009467b48Spatrick // constant.
231097a140dSpatrick if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
232097a140dSpatrick return Constant::getIntegerValue(VTy, Known.One);
23309467b48Spatrick
23409467b48Spatrick // If all of the demanded bits are known zero on one side, return the other.
23509467b48Spatrick // These bits cannot contribute to the result of the 'or'.
23609467b48Spatrick if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
23709467b48Spatrick return I->getOperand(0);
23809467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
23909467b48Spatrick return I->getOperand(1);
24009467b48Spatrick
24109467b48Spatrick // If the RHS is a constant, see if we can simplify it.
24209467b48Spatrick if (ShrinkDemandedConstant(I, 1, DemandedMask))
24309467b48Spatrick return I;
24409467b48Spatrick
24509467b48Spatrick break;
24609467b48Spatrick }
24709467b48Spatrick case Instruction::Xor: {
24809467b48Spatrick if (SimplifyDemandedBits(I, 1, DemandedMask, RHSKnown, Depth + 1) ||
24909467b48Spatrick SimplifyDemandedBits(I, 0, DemandedMask, LHSKnown, Depth + 1))
25009467b48Spatrick return I;
25173471bf0Spatrick Value *LHS, *RHS;
25273471bf0Spatrick if (DemandedMask == 1 &&
25373471bf0Spatrick match(I->getOperand(0), m_Intrinsic<Intrinsic::ctpop>(m_Value(LHS))) &&
25473471bf0Spatrick match(I->getOperand(1), m_Intrinsic<Intrinsic::ctpop>(m_Value(RHS)))) {
25573471bf0Spatrick // (ctpop(X) ^ ctpop(Y)) & 1 --> ctpop(X^Y) & 1
25673471bf0Spatrick IRBuilderBase::InsertPointGuard Guard(Builder);
25773471bf0Spatrick Builder.SetInsertPoint(I);
25873471bf0Spatrick auto *Xor = Builder.CreateXor(LHS, RHS);
25973471bf0Spatrick return Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, Xor);
26073471bf0Spatrick }
26173471bf0Spatrick
26209467b48Spatrick assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
26309467b48Spatrick assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
26409467b48Spatrick
265097a140dSpatrick Known = LHSKnown ^ RHSKnown;
26609467b48Spatrick
26709467b48Spatrick // If the client is only demanding bits that we know, return the known
26809467b48Spatrick // constant.
269097a140dSpatrick if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
270097a140dSpatrick return Constant::getIntegerValue(VTy, Known.One);
27109467b48Spatrick
27209467b48Spatrick // If all of the demanded bits are known zero on one side, return the other.
27309467b48Spatrick // These bits cannot contribute to the result of the 'xor'.
27409467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.Zero))
27509467b48Spatrick return I->getOperand(0);
27609467b48Spatrick if (DemandedMask.isSubsetOf(LHSKnown.Zero))
27709467b48Spatrick return I->getOperand(1);
27809467b48Spatrick
27909467b48Spatrick // If all of the demanded bits are known to be zero on one side or the
28009467b48Spatrick // other, turn this into an *inclusive* or.
28109467b48Spatrick // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
28209467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero)) {
28309467b48Spatrick Instruction *Or =
28409467b48Spatrick BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
28509467b48Spatrick I->getName());
28609467b48Spatrick return InsertNewInstWith(Or, *I);
28709467b48Spatrick }
28809467b48Spatrick
28909467b48Spatrick // If all of the demanded bits on one side are known, and all of the set
29009467b48Spatrick // bits on that side are also known to be set on the other side, turn this
29109467b48Spatrick // into an AND, as we know the bits will be cleared.
29209467b48Spatrick // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
29309467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.Zero|RHSKnown.One) &&
29409467b48Spatrick RHSKnown.One.isSubsetOf(LHSKnown.One)) {
29509467b48Spatrick Constant *AndC = Constant::getIntegerValue(VTy,
29609467b48Spatrick ~RHSKnown.One & DemandedMask);
29709467b48Spatrick Instruction *And = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
29809467b48Spatrick return InsertNewInstWith(And, *I);
29909467b48Spatrick }
30009467b48Spatrick
30173471bf0Spatrick // If the RHS is a constant, see if we can change it. Don't alter a -1
30273471bf0Spatrick // constant because that's a canonical 'not' op, and that is better for
30373471bf0Spatrick // combining, SCEV, and codegen.
30473471bf0Spatrick const APInt *C;
305*d415bd75Srobert if (match(I->getOperand(1), m_APInt(C)) && !C->isAllOnes()) {
306*d415bd75Srobert if ((*C | ~DemandedMask).isAllOnes()) {
30773471bf0Spatrick // Force bits to 1 to create a 'not' op.
30873471bf0Spatrick I->setOperand(1, ConstantInt::getAllOnesValue(VTy));
30973471bf0Spatrick return I;
31073471bf0Spatrick }
31173471bf0Spatrick // If we can't turn this into a 'not', try to shrink the constant.
31209467b48Spatrick if (ShrinkDemandedConstant(I, 1, DemandedMask))
31309467b48Spatrick return I;
31473471bf0Spatrick }
31509467b48Spatrick
31609467b48Spatrick // If our LHS is an 'and' and if it has one use, and if any of the bits we
31709467b48Spatrick // are flipping are known to be set, then the xor is just resetting those
31809467b48Spatrick // bits to zero. We can just knock out bits from the 'and' and the 'xor',
31909467b48Spatrick // simplifying both of them.
32073471bf0Spatrick if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0))) {
32173471bf0Spatrick ConstantInt *AndRHS, *XorRHS;
32209467b48Spatrick if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
32373471bf0Spatrick match(I->getOperand(1), m_ConstantInt(XorRHS)) &&
32473471bf0Spatrick match(LHSInst->getOperand(1), m_ConstantInt(AndRHS)) &&
32509467b48Spatrick (LHSKnown.One & RHSKnown.One & DemandedMask) != 0) {
32609467b48Spatrick APInt NewMask = ~(LHSKnown.One & RHSKnown.One & DemandedMask);
32709467b48Spatrick
328*d415bd75Srobert Constant *AndC = ConstantInt::get(VTy, NewMask & AndRHS->getValue());
32909467b48Spatrick Instruction *NewAnd = BinaryOperator::CreateAnd(I->getOperand(0), AndC);
33009467b48Spatrick InsertNewInstWith(NewAnd, *I);
33109467b48Spatrick
332*d415bd75Srobert Constant *XorC = ConstantInt::get(VTy, NewMask & XorRHS->getValue());
33309467b48Spatrick Instruction *NewXor = BinaryOperator::CreateXor(NewAnd, XorC);
33409467b48Spatrick return InsertNewInstWith(NewXor, *I);
33509467b48Spatrick }
33673471bf0Spatrick }
33709467b48Spatrick break;
33809467b48Spatrick }
33909467b48Spatrick case Instruction::Select: {
34009467b48Spatrick if (SimplifyDemandedBits(I, 2, DemandedMask, RHSKnown, Depth + 1) ||
34109467b48Spatrick SimplifyDemandedBits(I, 1, DemandedMask, LHSKnown, Depth + 1))
34209467b48Spatrick return I;
34309467b48Spatrick assert(!RHSKnown.hasConflict() && "Bits known to be one AND zero?");
34409467b48Spatrick assert(!LHSKnown.hasConflict() && "Bits known to be one AND zero?");
34509467b48Spatrick
34609467b48Spatrick // If the operands are constants, see if we can simplify them.
34709467b48Spatrick // This is similar to ShrinkDemandedConstant, but for a select we want to
34809467b48Spatrick // try to keep the selected constants the same as icmp value constants, if
34909467b48Spatrick // we can. This helps not break apart (or helps put back together)
35009467b48Spatrick // canonical patterns like min and max.
35109467b48Spatrick auto CanonicalizeSelectConstant = [](Instruction *I, unsigned OpNo,
35273471bf0Spatrick const APInt &DemandedMask) {
35309467b48Spatrick const APInt *SelC;
35409467b48Spatrick if (!match(I->getOperand(OpNo), m_APInt(SelC)))
35509467b48Spatrick return false;
35609467b48Spatrick
35709467b48Spatrick // Get the constant out of the ICmp, if there is one.
35873471bf0Spatrick // Only try this when exactly 1 operand is a constant (if both operands
35973471bf0Spatrick // are constant, the icmp should eventually simplify). Otherwise, we may
36073471bf0Spatrick // invert the transform that reduces set bits and infinite-loop.
36173471bf0Spatrick Value *X;
36209467b48Spatrick const APInt *CmpC;
36309467b48Spatrick ICmpInst::Predicate Pred;
36473471bf0Spatrick if (!match(I->getOperand(0), m_ICmp(Pred, m_Value(X), m_APInt(CmpC))) ||
36573471bf0Spatrick isa<Constant>(X) || CmpC->getBitWidth() != SelC->getBitWidth())
36609467b48Spatrick return ShrinkDemandedConstant(I, OpNo, DemandedMask);
36709467b48Spatrick
36809467b48Spatrick // If the constant is already the same as the ICmp, leave it as-is.
36909467b48Spatrick if (*CmpC == *SelC)
37009467b48Spatrick return false;
37109467b48Spatrick // If the constants are not already the same, but can be with the demand
37209467b48Spatrick // mask, use the constant value from the ICmp.
37309467b48Spatrick if ((*CmpC & DemandedMask) == (*SelC & DemandedMask)) {
37409467b48Spatrick I->setOperand(OpNo, ConstantInt::get(I->getType(), *CmpC));
37509467b48Spatrick return true;
37609467b48Spatrick }
37709467b48Spatrick return ShrinkDemandedConstant(I, OpNo, DemandedMask);
37809467b48Spatrick };
37909467b48Spatrick if (CanonicalizeSelectConstant(I, 1, DemandedMask) ||
38009467b48Spatrick CanonicalizeSelectConstant(I, 2, DemandedMask))
38109467b48Spatrick return I;
38209467b48Spatrick
38309467b48Spatrick // Only known if known in both the LHS and RHS.
38473471bf0Spatrick Known = KnownBits::commonBits(LHSKnown, RHSKnown);
38509467b48Spatrick break;
38609467b48Spatrick }
38709467b48Spatrick case Instruction::Trunc: {
388*d415bd75Srobert // If we do not demand the high bits of a right-shifted and truncated value,
389*d415bd75Srobert // then we may be able to truncate it before the shift.
390*d415bd75Srobert Value *X;
391*d415bd75Srobert const APInt *C;
392*d415bd75Srobert if (match(I->getOperand(0), m_OneUse(m_LShr(m_Value(X), m_APInt(C))))) {
393*d415bd75Srobert // The shift amount must be valid (not poison) in the narrow type, and
394*d415bd75Srobert // it must not be greater than the high bits demanded of the result.
395*d415bd75Srobert if (C->ult(VTy->getScalarSizeInBits()) &&
396*d415bd75Srobert C->ule(DemandedMask.countLeadingZeros())) {
397*d415bd75Srobert // trunc (lshr X, C) --> lshr (trunc X), C
398*d415bd75Srobert IRBuilderBase::InsertPointGuard Guard(Builder);
399*d415bd75Srobert Builder.SetInsertPoint(I);
400*d415bd75Srobert Value *Trunc = Builder.CreateTrunc(X, VTy);
401*d415bd75Srobert return Builder.CreateLShr(Trunc, C->getZExtValue());
402*d415bd75Srobert }
403*d415bd75Srobert }
404*d415bd75Srobert }
405*d415bd75Srobert [[fallthrough]];
406*d415bd75Srobert case Instruction::ZExt: {
40709467b48Spatrick unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
40809467b48Spatrick
40909467b48Spatrick APInt InputDemandedMask = DemandedMask.zextOrTrunc(SrcBitWidth);
41009467b48Spatrick KnownBits InputKnown(SrcBitWidth);
41109467b48Spatrick if (SimplifyDemandedBits(I, 0, InputDemandedMask, InputKnown, Depth + 1))
41209467b48Spatrick return I;
41309467b48Spatrick assert(InputKnown.getBitWidth() == SrcBitWidth && "Src width changed?");
414097a140dSpatrick Known = InputKnown.zextOrTrunc(BitWidth);
41509467b48Spatrick assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41609467b48Spatrick break;
41709467b48Spatrick }
41809467b48Spatrick case Instruction::BitCast:
41909467b48Spatrick if (!I->getOperand(0)->getType()->isIntOrIntVectorTy())
42009467b48Spatrick return nullptr; // vector->int or fp->int?
42109467b48Spatrick
422*d415bd75Srobert if (auto *DstVTy = dyn_cast<VectorType>(VTy)) {
423*d415bd75Srobert if (auto *SrcVTy = dyn_cast<VectorType>(I->getOperand(0)->getType())) {
424*d415bd75Srobert if (isa<ScalableVectorType>(DstVTy) ||
425*d415bd75Srobert isa<ScalableVectorType>(SrcVTy) ||
426*d415bd75Srobert cast<FixedVectorType>(DstVTy)->getNumElements() !=
42773471bf0Spatrick cast<FixedVectorType>(SrcVTy)->getNumElements())
42809467b48Spatrick // Don't touch a bitcast between vectors of different element counts.
42909467b48Spatrick return nullptr;
43009467b48Spatrick } else
43109467b48Spatrick // Don't touch a scalar-to-vector bitcast.
43209467b48Spatrick return nullptr;
43309467b48Spatrick } else if (I->getOperand(0)->getType()->isVectorTy())
43409467b48Spatrick // Don't touch a vector-to-scalar bitcast.
43509467b48Spatrick return nullptr;
43609467b48Spatrick
43709467b48Spatrick if (SimplifyDemandedBits(I, 0, DemandedMask, Known, Depth + 1))
43809467b48Spatrick return I;
43909467b48Spatrick assert(!Known.hasConflict() && "Bits known to be one AND zero?");
44009467b48Spatrick break;
44109467b48Spatrick case Instruction::SExt: {
44209467b48Spatrick // Compute the bits in the result that are not present in the input.
44309467b48Spatrick unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
44409467b48Spatrick
44509467b48Spatrick APInt InputDemandedBits = DemandedMask.trunc(SrcBitWidth);
44609467b48Spatrick
44709467b48Spatrick // If any of the sign extended bits are demanded, we know that the sign
44809467b48Spatrick // bit is demanded.
44909467b48Spatrick if (DemandedMask.getActiveBits() > SrcBitWidth)
45009467b48Spatrick InputDemandedBits.setBit(SrcBitWidth-1);
45109467b48Spatrick
45209467b48Spatrick KnownBits InputKnown(SrcBitWidth);
45309467b48Spatrick if (SimplifyDemandedBits(I, 0, InputDemandedBits, InputKnown, Depth + 1))
45409467b48Spatrick return I;
45509467b48Spatrick
45609467b48Spatrick // If the input sign bit is known zero, or if the NewBits are not demanded
45709467b48Spatrick // convert this into a zero extension.
45809467b48Spatrick if (InputKnown.isNonNegative() ||
45909467b48Spatrick DemandedMask.getActiveBits() <= SrcBitWidth) {
46009467b48Spatrick // Convert to ZExt cast.
46109467b48Spatrick CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
46209467b48Spatrick return InsertNewInstWith(NewCast, *I);
46309467b48Spatrick }
46409467b48Spatrick
46509467b48Spatrick // If the sign bit of the input is known set or clear, then we know the
46609467b48Spatrick // top bits of the result.
46709467b48Spatrick Known = InputKnown.sext(BitWidth);
46809467b48Spatrick assert(!Known.hasConflict() && "Bits known to be one AND zero?");
46909467b48Spatrick break;
47009467b48Spatrick }
471*d415bd75Srobert case Instruction::Add: {
472097a140dSpatrick if ((DemandedMask & 1) == 0) {
473097a140dSpatrick // If we do not need the low bit, try to convert bool math to logic:
474097a140dSpatrick // add iN (zext i1 X), (sext i1 Y) --> sext (~X & Y) to iN
475097a140dSpatrick Value *X, *Y;
476097a140dSpatrick if (match(I, m_c_Add(m_OneUse(m_ZExt(m_Value(X))),
477097a140dSpatrick m_OneUse(m_SExt(m_Value(Y))))) &&
478097a140dSpatrick X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
479097a140dSpatrick // Truth table for inputs and output signbits:
480097a140dSpatrick // X:0 | X:1
481097a140dSpatrick // ----------
482097a140dSpatrick // Y:0 | 0 | 0 |
483097a140dSpatrick // Y:1 | -1 | 0 |
484097a140dSpatrick // ----------
485097a140dSpatrick IRBuilderBase::InsertPointGuard Guard(Builder);
486097a140dSpatrick Builder.SetInsertPoint(I);
487097a140dSpatrick Value *AndNot = Builder.CreateAnd(Builder.CreateNot(X), Y);
488097a140dSpatrick return Builder.CreateSExt(AndNot, VTy);
489097a140dSpatrick }
490097a140dSpatrick
491097a140dSpatrick // add iN (sext i1 X), (sext i1 Y) --> sext (X | Y) to iN
492097a140dSpatrick // TODO: Relax the one-use checks because we are removing an instruction?
493097a140dSpatrick if (match(I, m_Add(m_OneUse(m_SExt(m_Value(X))),
494097a140dSpatrick m_OneUse(m_SExt(m_Value(Y))))) &&
495097a140dSpatrick X->getType()->isIntOrIntVectorTy(1) && X->getType() == Y->getType()) {
496097a140dSpatrick // Truth table for inputs and output signbits:
497097a140dSpatrick // X:0 | X:1
498097a140dSpatrick // -----------
499097a140dSpatrick // Y:0 | -1 | -1 |
500097a140dSpatrick // Y:1 | -1 | 0 |
501097a140dSpatrick // -----------
502097a140dSpatrick IRBuilderBase::InsertPointGuard Guard(Builder);
503097a140dSpatrick Builder.SetInsertPoint(I);
504097a140dSpatrick Value *Or = Builder.CreateOr(X, Y);
505097a140dSpatrick return Builder.CreateSExt(Or, VTy);
506097a140dSpatrick }
507097a140dSpatrick }
50809467b48Spatrick
509*d415bd75Srobert // Right fill the mask of bits for the operands to demand the most
510*d415bd75Srobert // significant bit and all those below it.
511*d415bd75Srobert unsigned NLZ = DemandedMask.countLeadingZeros();
512*d415bd75Srobert APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
513*d415bd75Srobert if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
514*d415bd75Srobert SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
515*d415bd75Srobert return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
516*d415bd75Srobert
517*d415bd75Srobert // If low order bits are not demanded and known to be zero in one operand,
518*d415bd75Srobert // then we don't need to demand them from the other operand, since they
519*d415bd75Srobert // can't cause overflow into any bits that are demanded in the result.
520*d415bd75Srobert unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countTrailingOnes();
521*d415bd75Srobert APInt DemandedFromLHS = DemandedFromOps;
522*d415bd75Srobert DemandedFromLHS.clearLowBits(NTZ);
523*d415bd75Srobert if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
524*d415bd75Srobert SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
525*d415bd75Srobert return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
526*d415bd75Srobert
527*d415bd75Srobert // If we are known to be adding zeros to every bit below
528*d415bd75Srobert // the highest demanded bit, we just return the other side.
529*d415bd75Srobert if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
530*d415bd75Srobert return I->getOperand(0);
531*d415bd75Srobert if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
532*d415bd75Srobert return I->getOperand(1);
533*d415bd75Srobert
534*d415bd75Srobert // Otherwise just compute the known bits of the result.
535*d415bd75Srobert bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
536*d415bd75Srobert Known = KnownBits::computeForAddSub(true, NSW, LHSKnown, RHSKnown);
537*d415bd75Srobert break;
538*d415bd75Srobert }
539*d415bd75Srobert case Instruction::Sub: {
540*d415bd75Srobert // Right fill the mask of bits for the operands to demand the most
541*d415bd75Srobert // significant bit and all those below it.
542*d415bd75Srobert unsigned NLZ = DemandedMask.countLeadingZeros();
543*d415bd75Srobert APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
544*d415bd75Srobert if (ShrinkDemandedConstant(I, 1, DemandedFromOps) ||
545*d415bd75Srobert SimplifyDemandedBits(I, 1, DemandedFromOps, RHSKnown, Depth + 1))
546*d415bd75Srobert return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
547*d415bd75Srobert
548*d415bd75Srobert // If low order bits are not demanded and are known to be zero in RHS,
549*d415bd75Srobert // then we don't need to demand them from LHS, since they can't cause a
550*d415bd75Srobert // borrow from any bits that are demanded in the result.
551*d415bd75Srobert unsigned NTZ = (~DemandedMask & RHSKnown.Zero).countTrailingOnes();
552*d415bd75Srobert APInt DemandedFromLHS = DemandedFromOps;
553*d415bd75Srobert DemandedFromLHS.clearLowBits(NTZ);
554*d415bd75Srobert if (ShrinkDemandedConstant(I, 0, DemandedFromLHS) ||
555*d415bd75Srobert SimplifyDemandedBits(I, 0, DemandedFromLHS, LHSKnown, Depth + 1))
556*d415bd75Srobert return disableWrapFlagsBasedOnUnusedHighBits(I, NLZ);
557*d415bd75Srobert
558*d415bd75Srobert // If we are known to be subtracting zeros from every bit below
55909467b48Spatrick // the highest demanded bit, we just return the other side.
56009467b48Spatrick if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
56109467b48Spatrick return I->getOperand(0);
56209467b48Spatrick // We can't do this with the LHS for subtraction, unless we are only
56309467b48Spatrick // demanding the LSB.
564*d415bd75Srobert if (DemandedFromOps.isOne() && DemandedFromOps.isSubsetOf(LHSKnown.Zero))
56509467b48Spatrick return I->getOperand(1);
56609467b48Spatrick
56709467b48Spatrick // Otherwise just compute the known bits of the result.
56809467b48Spatrick bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
569*d415bd75Srobert Known = KnownBits::computeForAddSub(false, NSW, LHSKnown, RHSKnown);
570*d415bd75Srobert break;
571*d415bd75Srobert }
572*d415bd75Srobert case Instruction::Mul: {
573*d415bd75Srobert APInt DemandedFromOps;
574*d415bd75Srobert if (simplifyOperandsBasedOnUnusedHighBits(DemandedFromOps))
575*d415bd75Srobert return I;
576*d415bd75Srobert
577*d415bd75Srobert if (DemandedMask.isPowerOf2()) {
578*d415bd75Srobert // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
579*d415bd75Srobert // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
580*d415bd75Srobert // odd (has LSB set), then the left-shifted low bit of X is the answer.
581*d415bd75Srobert unsigned CTZ = DemandedMask.countTrailingZeros();
582*d415bd75Srobert const APInt *C;
583*d415bd75Srobert if (match(I->getOperand(1), m_APInt(C)) &&
584*d415bd75Srobert C->countTrailingZeros() == CTZ) {
585*d415bd75Srobert Constant *ShiftC = ConstantInt::get(VTy, CTZ);
586*d415bd75Srobert Instruction *Shl = BinaryOperator::CreateShl(I->getOperand(0), ShiftC);
587*d415bd75Srobert return InsertNewInstWith(Shl, *I);
588*d415bd75Srobert }
589*d415bd75Srobert }
590*d415bd75Srobert // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
591*d415bd75Srobert // X * X is odd iff X is odd.
592*d415bd75Srobert // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
593*d415bd75Srobert if (I->getOperand(0) == I->getOperand(1) && DemandedMask.ult(4)) {
594*d415bd75Srobert Constant *One = ConstantInt::get(VTy, 1);
595*d415bd75Srobert Instruction *And1 = BinaryOperator::CreateAnd(I->getOperand(0), One);
596*d415bd75Srobert return InsertNewInstWith(And1, *I);
597*d415bd75Srobert }
598*d415bd75Srobert
599*d415bd75Srobert computeKnownBits(I, Known, Depth, CxtI);
60009467b48Spatrick break;
60109467b48Spatrick }
60209467b48Spatrick case Instruction::Shl: {
60309467b48Spatrick const APInt *SA;
60409467b48Spatrick if (match(I->getOperand(1), m_APInt(SA))) {
60509467b48Spatrick const APInt *ShrAmt;
60609467b48Spatrick if (match(I->getOperand(0), m_Shr(m_Value(), m_APInt(ShrAmt))))
60709467b48Spatrick if (Instruction *Shr = dyn_cast<Instruction>(I->getOperand(0)))
60809467b48Spatrick if (Value *R = simplifyShrShlDemandedBits(Shr, *ShrAmt, I, *SA,
60909467b48Spatrick DemandedMask, Known))
61009467b48Spatrick return R;
61109467b48Spatrick
612*d415bd75Srobert // TODO: If we only want bits that already match the signbit then we don't
613*d415bd75Srobert // need to shift.
614*d415bd75Srobert
615*d415bd75Srobert // If we can pre-shift a right-shifted constant to the left without
616*d415bd75Srobert // losing any high bits amd we don't demand the low bits, then eliminate
617*d415bd75Srobert // the left-shift:
618*d415bd75Srobert // (C >> X) << LeftShiftAmtC --> (C << RightShiftAmtC) >> X
61909467b48Spatrick uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
620*d415bd75Srobert Value *X;
621*d415bd75Srobert Constant *C;
622*d415bd75Srobert if (DemandedMask.countTrailingZeros() >= ShiftAmt &&
623*d415bd75Srobert match(I->getOperand(0), m_LShr(m_ImmConstant(C), m_Value(X)))) {
624*d415bd75Srobert Constant *LeftShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
625*d415bd75Srobert Constant *NewC = ConstantExpr::getShl(C, LeftShiftAmtC);
626*d415bd75Srobert if (ConstantExpr::getLShr(NewC, LeftShiftAmtC) == C) {
627*d415bd75Srobert Instruction *Lshr = BinaryOperator::CreateLShr(NewC, X);
628*d415bd75Srobert return InsertNewInstWith(Lshr, *I);
629*d415bd75Srobert }
630*d415bd75Srobert }
631*d415bd75Srobert
63209467b48Spatrick APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
63309467b48Spatrick
63409467b48Spatrick // If the shift is NUW/NSW, then it does demand the high bits.
63509467b48Spatrick ShlOperator *IOp = cast<ShlOperator>(I);
63609467b48Spatrick if (IOp->hasNoSignedWrap())
63709467b48Spatrick DemandedMaskIn.setHighBits(ShiftAmt+1);
63809467b48Spatrick else if (IOp->hasNoUnsignedWrap())
63909467b48Spatrick DemandedMaskIn.setHighBits(ShiftAmt);
64009467b48Spatrick
64109467b48Spatrick if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
64209467b48Spatrick return I;
64309467b48Spatrick assert(!Known.hasConflict() && "Bits known to be one AND zero?");
644097a140dSpatrick
645097a140dSpatrick bool SignBitZero = Known.Zero.isSignBitSet();
646097a140dSpatrick bool SignBitOne = Known.One.isSignBitSet();
64709467b48Spatrick Known.Zero <<= ShiftAmt;
64809467b48Spatrick Known.One <<= ShiftAmt;
64909467b48Spatrick // low bits known zero.
65009467b48Spatrick if (ShiftAmt)
65109467b48Spatrick Known.Zero.setLowBits(ShiftAmt);
652097a140dSpatrick
653097a140dSpatrick // If this shift has "nsw" keyword, then the result is either a poison
654097a140dSpatrick // value or has the same sign bit as the first operand.
655097a140dSpatrick if (IOp->hasNoSignedWrap()) {
656097a140dSpatrick if (SignBitZero)
657097a140dSpatrick Known.Zero.setSignBit();
658097a140dSpatrick else if (SignBitOne)
659097a140dSpatrick Known.One.setSignBit();
660097a140dSpatrick if (Known.hasConflict())
661*d415bd75Srobert return UndefValue::get(VTy);
662097a140dSpatrick }
663097a140dSpatrick } else {
66473471bf0Spatrick // This is a variable shift, so we can't shift the demand mask by a known
66573471bf0Spatrick // amount. But if we are not demanding high bits, then we are not
66673471bf0Spatrick // demanding those bits from the pre-shifted operand either.
66773471bf0Spatrick if (unsigned CTLZ = DemandedMask.countLeadingZeros()) {
66873471bf0Spatrick APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
66973471bf0Spatrick if (SimplifyDemandedBits(I, 0, DemandedFromOp, Known, Depth + 1)) {
67073471bf0Spatrick // We can't guarantee that nsw/nuw hold after simplifying the operand.
67173471bf0Spatrick I->dropPoisonGeneratingFlags();
67273471bf0Spatrick return I;
67373471bf0Spatrick }
67473471bf0Spatrick }
675097a140dSpatrick computeKnownBits(I, Known, Depth, CxtI);
67609467b48Spatrick }
67709467b48Spatrick break;
67809467b48Spatrick }
67909467b48Spatrick case Instruction::LShr: {
68009467b48Spatrick const APInt *SA;
68109467b48Spatrick if (match(I->getOperand(1), m_APInt(SA))) {
68209467b48Spatrick uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
68309467b48Spatrick
684*d415bd75Srobert // If we are just demanding the shifted sign bit and below, then this can
685*d415bd75Srobert // be treated as an ASHR in disguise.
686*d415bd75Srobert if (DemandedMask.countLeadingZeros() >= ShiftAmt) {
687*d415bd75Srobert // If we only want bits that already match the signbit then we don't
688*d415bd75Srobert // need to shift.
689*d415bd75Srobert unsigned NumHiDemandedBits =
690*d415bd75Srobert BitWidth - DemandedMask.countTrailingZeros();
691*d415bd75Srobert unsigned SignBits =
692*d415bd75Srobert ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
693*d415bd75Srobert if (SignBits >= NumHiDemandedBits)
694*d415bd75Srobert return I->getOperand(0);
695*d415bd75Srobert
696*d415bd75Srobert // If we can pre-shift a left-shifted constant to the right without
697*d415bd75Srobert // losing any low bits (we already know we don't demand the high bits),
698*d415bd75Srobert // then eliminate the right-shift:
699*d415bd75Srobert // (C << X) >> RightShiftAmtC --> (C >> RightShiftAmtC) << X
700*d415bd75Srobert Value *X;
701*d415bd75Srobert Constant *C;
702*d415bd75Srobert if (match(I->getOperand(0), m_Shl(m_ImmConstant(C), m_Value(X)))) {
703*d415bd75Srobert Constant *RightShiftAmtC = ConstantInt::get(VTy, ShiftAmt);
704*d415bd75Srobert Constant *NewC = ConstantExpr::getLShr(C, RightShiftAmtC);
705*d415bd75Srobert if (ConstantExpr::getShl(NewC, RightShiftAmtC) == C) {
706*d415bd75Srobert Instruction *Shl = BinaryOperator::CreateShl(NewC, X);
707*d415bd75Srobert return InsertNewInstWith(Shl, *I);
708*d415bd75Srobert }
709*d415bd75Srobert }
710*d415bd75Srobert }
711*d415bd75Srobert
71209467b48Spatrick // Unsigned shift right.
71309467b48Spatrick APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
71409467b48Spatrick
71509467b48Spatrick // If the shift is exact, then it does demand the low bits (and knows that
71609467b48Spatrick // they are zero).
71709467b48Spatrick if (cast<LShrOperator>(I)->isExact())
71809467b48Spatrick DemandedMaskIn.setLowBits(ShiftAmt);
71909467b48Spatrick
72009467b48Spatrick if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
72109467b48Spatrick return I;
72209467b48Spatrick assert(!Known.hasConflict() && "Bits known to be one AND zero?");
72309467b48Spatrick Known.Zero.lshrInPlace(ShiftAmt);
72409467b48Spatrick Known.One.lshrInPlace(ShiftAmt);
72509467b48Spatrick if (ShiftAmt)
72609467b48Spatrick Known.Zero.setHighBits(ShiftAmt); // high bits known zero.
727097a140dSpatrick } else {
728097a140dSpatrick computeKnownBits(I, Known, Depth, CxtI);
72909467b48Spatrick }
73009467b48Spatrick break;
73109467b48Spatrick }
73209467b48Spatrick case Instruction::AShr: {
733*d415bd75Srobert unsigned SignBits = ComputeNumSignBits(I->getOperand(0), Depth + 1, CxtI);
734*d415bd75Srobert
735*d415bd75Srobert // If we only want bits that already match the signbit then we don't need
736*d415bd75Srobert // to shift.
737*d415bd75Srobert unsigned NumHiDemandedBits = BitWidth - DemandedMask.countTrailingZeros();
738*d415bd75Srobert if (SignBits >= NumHiDemandedBits)
739*d415bd75Srobert return I->getOperand(0);
740*d415bd75Srobert
74109467b48Spatrick // If this is an arithmetic shift right and only the low-bit is set, we can
74209467b48Spatrick // always convert this into a logical shr, even if the shift amount is
74309467b48Spatrick // variable. The low bit of the shift cannot be an input sign bit unless
74409467b48Spatrick // the shift amount is >= the size of the datatype, which is undefined.
745*d415bd75Srobert if (DemandedMask.isOne()) {
74609467b48Spatrick // Perform the logical shift right.
74709467b48Spatrick Instruction *NewVal = BinaryOperator::CreateLShr(
74809467b48Spatrick I->getOperand(0), I->getOperand(1), I->getName());
74909467b48Spatrick return InsertNewInstWith(NewVal, *I);
75009467b48Spatrick }
75109467b48Spatrick
75209467b48Spatrick const APInt *SA;
75309467b48Spatrick if (match(I->getOperand(1), m_APInt(SA))) {
75409467b48Spatrick uint32_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
75509467b48Spatrick
75609467b48Spatrick // Signed shift right.
75709467b48Spatrick APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
75809467b48Spatrick // If any of the high bits are demanded, we should set the sign bit as
75909467b48Spatrick // demanded.
76009467b48Spatrick if (DemandedMask.countLeadingZeros() <= ShiftAmt)
76109467b48Spatrick DemandedMaskIn.setSignBit();
76209467b48Spatrick
76309467b48Spatrick // If the shift is exact, then it does demand the low bits (and knows that
76409467b48Spatrick // they are zero).
76509467b48Spatrick if (cast<AShrOperator>(I)->isExact())
76609467b48Spatrick DemandedMaskIn.setLowBits(ShiftAmt);
76709467b48Spatrick
76809467b48Spatrick if (SimplifyDemandedBits(I, 0, DemandedMaskIn, Known, Depth + 1))
76909467b48Spatrick return I;
77009467b48Spatrick
77109467b48Spatrick assert(!Known.hasConflict() && "Bits known to be one AND zero?");
77209467b48Spatrick // Compute the new bits that are at the top now plus sign bits.
77309467b48Spatrick APInt HighBits(APInt::getHighBitsSet(
77409467b48Spatrick BitWidth, std::min(SignBits + ShiftAmt - 1, BitWidth)));
77509467b48Spatrick Known.Zero.lshrInPlace(ShiftAmt);
77609467b48Spatrick Known.One.lshrInPlace(ShiftAmt);
77709467b48Spatrick
77809467b48Spatrick // If the input sign bit is known to be zero, or if none of the top bits
77909467b48Spatrick // are demanded, turn this into an unsigned shift right.
78009467b48Spatrick assert(BitWidth > ShiftAmt && "Shift amount not saturated?");
78109467b48Spatrick if (Known.Zero[BitWidth-ShiftAmt-1] ||
78209467b48Spatrick !DemandedMask.intersects(HighBits)) {
78309467b48Spatrick BinaryOperator *LShr = BinaryOperator::CreateLShr(I->getOperand(0),
78409467b48Spatrick I->getOperand(1));
78509467b48Spatrick LShr->setIsExact(cast<BinaryOperator>(I)->isExact());
78609467b48Spatrick return InsertNewInstWith(LShr, *I);
78709467b48Spatrick } else if (Known.One[BitWidth-ShiftAmt-1]) { // New bits are known one.
78809467b48Spatrick Known.One |= HighBits;
78909467b48Spatrick }
790097a140dSpatrick } else {
791097a140dSpatrick computeKnownBits(I, Known, Depth, CxtI);
79209467b48Spatrick }
79309467b48Spatrick break;
79409467b48Spatrick }
79509467b48Spatrick case Instruction::UDiv: {
79609467b48Spatrick // UDiv doesn't demand low bits that are zero in the divisor.
79709467b48Spatrick const APInt *SA;
79809467b48Spatrick if (match(I->getOperand(1), m_APInt(SA))) {
799*d415bd75Srobert // TODO: Take the demanded mask of the result into account.
80009467b48Spatrick unsigned RHSTrailingZeros = SA->countTrailingZeros();
80109467b48Spatrick APInt DemandedMaskIn =
80209467b48Spatrick APInt::getHighBitsSet(BitWidth, BitWidth - RHSTrailingZeros);
803*d415bd75Srobert if (SimplifyDemandedBits(I, 0, DemandedMaskIn, LHSKnown, Depth + 1)) {
804*d415bd75Srobert // We can't guarantee that "exact" is still true after changing the
805*d415bd75Srobert // the dividend.
806*d415bd75Srobert I->dropPoisonGeneratingFlags();
80709467b48Spatrick return I;
808*d415bd75Srobert }
80909467b48Spatrick
810*d415bd75Srobert // Increase high zero bits from the input.
81109467b48Spatrick Known.Zero.setHighBits(std::min(
81209467b48Spatrick BitWidth, LHSKnown.Zero.countLeadingOnes() + RHSTrailingZeros));
813097a140dSpatrick } else {
814097a140dSpatrick computeKnownBits(I, Known, Depth, CxtI);
81509467b48Spatrick }
81609467b48Spatrick break;
81709467b48Spatrick }
81873471bf0Spatrick case Instruction::SRem: {
819*d415bd75Srobert const APInt *Rem;
820*d415bd75Srobert if (match(I->getOperand(1), m_APInt(Rem))) {
82109467b48Spatrick // X % -1 demands all the bits because we don't want to introduce
82209467b48Spatrick // INT_MIN % -1 (== undef) by accident.
823*d415bd75Srobert if (Rem->isAllOnes())
82409467b48Spatrick break;
825*d415bd75Srobert APInt RA = Rem->abs();
82609467b48Spatrick if (RA.isPowerOf2()) {
82709467b48Spatrick if (DemandedMask.ult(RA)) // srem won't affect demanded bits
82809467b48Spatrick return I->getOperand(0);
82909467b48Spatrick
83009467b48Spatrick APInt LowBits = RA - 1;
83109467b48Spatrick APInt Mask2 = LowBits | APInt::getSignMask(BitWidth);
83209467b48Spatrick if (SimplifyDemandedBits(I, 0, Mask2, LHSKnown, Depth + 1))
83309467b48Spatrick return I;
83409467b48Spatrick
83509467b48Spatrick // The low bits of LHS are unchanged by the srem.
83609467b48Spatrick Known.Zero = LHSKnown.Zero & LowBits;
83709467b48Spatrick Known.One = LHSKnown.One & LowBits;
83809467b48Spatrick
83909467b48Spatrick // If LHS is non-negative or has all low bits zero, then the upper bits
84009467b48Spatrick // are all zero.
84109467b48Spatrick if (LHSKnown.isNonNegative() || LowBits.isSubsetOf(LHSKnown.Zero))
84209467b48Spatrick Known.Zero |= ~LowBits;
84309467b48Spatrick
84409467b48Spatrick // If LHS is negative and not all low bits are zero, then the upper bits
84509467b48Spatrick // are all one.
84609467b48Spatrick if (LHSKnown.isNegative() && LowBits.intersects(LHSKnown.One))
84709467b48Spatrick Known.One |= ~LowBits;
84809467b48Spatrick
84909467b48Spatrick assert(!Known.hasConflict() && "Bits known to be one AND zero?");
85009467b48Spatrick break;
85109467b48Spatrick }
85209467b48Spatrick }
85309467b48Spatrick
85409467b48Spatrick // The sign bit is the LHS's sign bit, except when the result of the
85509467b48Spatrick // remainder is zero.
85609467b48Spatrick if (DemandedMask.isSignBitSet()) {
85709467b48Spatrick computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
85809467b48Spatrick // If it's known zero, our sign bit is also zero.
85909467b48Spatrick if (LHSKnown.isNonNegative())
86009467b48Spatrick Known.makeNonNegative();
86109467b48Spatrick }
86209467b48Spatrick break;
86373471bf0Spatrick }
86409467b48Spatrick case Instruction::URem: {
86509467b48Spatrick KnownBits Known2(BitWidth);
866*d415bd75Srobert APInt AllOnes = APInt::getAllOnes(BitWidth);
86709467b48Spatrick if (SimplifyDemandedBits(I, 0, AllOnes, Known2, Depth + 1) ||
86809467b48Spatrick SimplifyDemandedBits(I, 1, AllOnes, Known2, Depth + 1))
86909467b48Spatrick return I;
87009467b48Spatrick
87109467b48Spatrick unsigned Leaders = Known2.countMinLeadingZeros();
87209467b48Spatrick Known.Zero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
87309467b48Spatrick break;
87409467b48Spatrick }
875097a140dSpatrick case Instruction::Call: {
876097a140dSpatrick bool KnownBitsComputed = false;
87709467b48Spatrick if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
87809467b48Spatrick switch (II->getIntrinsicID()) {
87973471bf0Spatrick case Intrinsic::abs: {
88073471bf0Spatrick if (DemandedMask == 1)
88173471bf0Spatrick return II->getArgOperand(0);
88273471bf0Spatrick break;
88373471bf0Spatrick }
88473471bf0Spatrick case Intrinsic::ctpop: {
88573471bf0Spatrick // Checking if the number of clear bits is odd (parity)? If the type has
88673471bf0Spatrick // an even number of bits, that's the same as checking if the number of
88773471bf0Spatrick // set bits is odd, so we can eliminate the 'not' op.
88873471bf0Spatrick Value *X;
88973471bf0Spatrick if (DemandedMask == 1 && VTy->getScalarSizeInBits() % 2 == 0 &&
89073471bf0Spatrick match(II->getArgOperand(0), m_Not(m_Value(X)))) {
89173471bf0Spatrick Function *Ctpop = Intrinsic::getDeclaration(
892*d415bd75Srobert II->getModule(), Intrinsic::ctpop, VTy);
89373471bf0Spatrick return InsertNewInstWith(CallInst::Create(Ctpop, {X}), *I);
89473471bf0Spatrick }
89573471bf0Spatrick break;
89673471bf0Spatrick }
89709467b48Spatrick case Intrinsic::bswap: {
89809467b48Spatrick // If the only bits demanded come from one byte of the bswap result,
89909467b48Spatrick // just shift the input byte into position to eliminate the bswap.
90009467b48Spatrick unsigned NLZ = DemandedMask.countLeadingZeros();
90109467b48Spatrick unsigned NTZ = DemandedMask.countTrailingZeros();
90209467b48Spatrick
90309467b48Spatrick // Round NTZ down to the next byte. If we have 11 trailing zeros, then
90409467b48Spatrick // we need all the bits down to bit 8. Likewise, round NLZ. If we
90509467b48Spatrick // have 14 leading zeros, round to 8.
906*d415bd75Srobert NLZ = alignDown(NLZ, 8);
907*d415bd75Srobert NTZ = alignDown(NTZ, 8);
90809467b48Spatrick // If we need exactly one byte, we can do this transformation.
90909467b48Spatrick if (BitWidth - NLZ - NTZ == 8) {
91009467b48Spatrick // Replace this with either a left or right shift to get the byte into
91109467b48Spatrick // the right place.
91209467b48Spatrick Instruction *NewVal;
913*d415bd75Srobert if (NLZ > NTZ)
914*d415bd75Srobert NewVal = BinaryOperator::CreateLShr(
915*d415bd75Srobert II->getArgOperand(0), ConstantInt::get(VTy, NLZ - NTZ));
91609467b48Spatrick else
917*d415bd75Srobert NewVal = BinaryOperator::CreateShl(
918*d415bd75Srobert II->getArgOperand(0), ConstantInt::get(VTy, NTZ - NLZ));
91909467b48Spatrick NewVal->takeName(I);
92009467b48Spatrick return InsertNewInstWith(NewVal, *I);
92109467b48Spatrick }
92209467b48Spatrick break;
92309467b48Spatrick }
92409467b48Spatrick case Intrinsic::fshr:
92509467b48Spatrick case Intrinsic::fshl: {
92609467b48Spatrick const APInt *SA;
92709467b48Spatrick if (!match(I->getOperand(2), m_APInt(SA)))
92809467b48Spatrick break;
92909467b48Spatrick
93009467b48Spatrick // Normalize to funnel shift left. APInt shifts of BitWidth are well-
93109467b48Spatrick // defined, so no need to special-case zero shifts here.
93209467b48Spatrick uint64_t ShiftAmt = SA->urem(BitWidth);
93309467b48Spatrick if (II->getIntrinsicID() == Intrinsic::fshr)
93409467b48Spatrick ShiftAmt = BitWidth - ShiftAmt;
93509467b48Spatrick
93609467b48Spatrick APInt DemandedMaskLHS(DemandedMask.lshr(ShiftAmt));
93709467b48Spatrick APInt DemandedMaskRHS(DemandedMask.shl(BitWidth - ShiftAmt));
93809467b48Spatrick if (SimplifyDemandedBits(I, 0, DemandedMaskLHS, LHSKnown, Depth + 1) ||
93909467b48Spatrick SimplifyDemandedBits(I, 1, DemandedMaskRHS, RHSKnown, Depth + 1))
94009467b48Spatrick return I;
94109467b48Spatrick
94209467b48Spatrick Known.Zero = LHSKnown.Zero.shl(ShiftAmt) |
94309467b48Spatrick RHSKnown.Zero.lshr(BitWidth - ShiftAmt);
94409467b48Spatrick Known.One = LHSKnown.One.shl(ShiftAmt) |
94509467b48Spatrick RHSKnown.One.lshr(BitWidth - ShiftAmt);
946097a140dSpatrick KnownBitsComputed = true;
94709467b48Spatrick break;
94809467b48Spatrick }
949*d415bd75Srobert case Intrinsic::umax: {
950*d415bd75Srobert // UMax(A, C) == A if ...
951*d415bd75Srobert // The lowest non-zero bit of DemandMask is higher than the highest
952*d415bd75Srobert // non-zero bit of C.
953*d415bd75Srobert const APInt *C;
954*d415bd75Srobert unsigned CTZ = DemandedMask.countTrailingZeros();
955*d415bd75Srobert if (match(II->getArgOperand(1), m_APInt(C)) &&
956*d415bd75Srobert CTZ >= C->getActiveBits())
957*d415bd75Srobert return II->getArgOperand(0);
958*d415bd75Srobert break;
959*d415bd75Srobert }
960*d415bd75Srobert case Intrinsic::umin: {
961*d415bd75Srobert // UMin(A, C) == A if ...
962*d415bd75Srobert // The lowest non-zero bit of DemandMask is higher than the highest
963*d415bd75Srobert // non-one bit of C.
964*d415bd75Srobert // This comes from using DeMorgans on the above umax example.
965*d415bd75Srobert const APInt *C;
966*d415bd75Srobert unsigned CTZ = DemandedMask.countTrailingZeros();
967*d415bd75Srobert if (match(II->getArgOperand(1), m_APInt(C)) &&
968*d415bd75Srobert CTZ >= C->getBitWidth() - C->countLeadingOnes())
969*d415bd75Srobert return II->getArgOperand(0);
970*d415bd75Srobert break;
971*d415bd75Srobert }
97273471bf0Spatrick default: {
97373471bf0Spatrick // Handle target specific intrinsics
974*d415bd75Srobert std::optional<Value *> V = targetSimplifyDemandedUseBitsIntrinsic(
97573471bf0Spatrick *II, DemandedMask, Known, KnownBitsComputed);
976*d415bd75Srobert if (V)
977*d415bd75Srobert return *V;
978097a140dSpatrick break;
97909467b48Spatrick }
98009467b48Spatrick }
98109467b48Spatrick }
982097a140dSpatrick
983097a140dSpatrick if (!KnownBitsComputed)
98409467b48Spatrick computeKnownBits(V, Known, Depth, CxtI);
98509467b48Spatrick break;
98609467b48Spatrick }
987097a140dSpatrick }
98809467b48Spatrick
98909467b48Spatrick // If the client is only demanding bits that we know, return the known
99009467b48Spatrick // constant.
99109467b48Spatrick if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
99209467b48Spatrick return Constant::getIntegerValue(VTy, Known.One);
99309467b48Spatrick return nullptr;
99409467b48Spatrick }
99509467b48Spatrick
99609467b48Spatrick /// Helper routine of SimplifyDemandedUseBits. It computes Known
99709467b48Spatrick /// bits. It also tries to handle simplifications that can be done based on
99809467b48Spatrick /// DemandedMask, but without modifying the Instruction.
SimplifyMultipleUseDemandedBits(Instruction * I,const APInt & DemandedMask,KnownBits & Known,unsigned Depth,Instruction * CxtI)99973471bf0Spatrick Value *InstCombinerImpl::SimplifyMultipleUseDemandedBits(
100073471bf0Spatrick Instruction *I, const APInt &DemandedMask, KnownBits &Known, unsigned Depth,
100109467b48Spatrick Instruction *CxtI) {
100209467b48Spatrick unsigned BitWidth = DemandedMask.getBitWidth();
100309467b48Spatrick Type *ITy = I->getType();
100409467b48Spatrick
100509467b48Spatrick KnownBits LHSKnown(BitWidth);
100609467b48Spatrick KnownBits RHSKnown(BitWidth);
100709467b48Spatrick
100809467b48Spatrick // Despite the fact that we can't simplify this instruction in all User's
100909467b48Spatrick // context, we can at least compute the known bits, and we can
101009467b48Spatrick // do simplifications that apply to *just* the one user if we know that
101109467b48Spatrick // this instruction has a simpler value in that context.
101209467b48Spatrick switch (I->getOpcode()) {
101309467b48Spatrick case Instruction::And: {
101409467b48Spatrick computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1015*d415bd75Srobert computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1016097a140dSpatrick Known = LHSKnown & RHSKnown;
101709467b48Spatrick
101809467b48Spatrick // If the client is only demanding bits that we know, return the known
101909467b48Spatrick // constant.
1020097a140dSpatrick if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1021097a140dSpatrick return Constant::getIntegerValue(ITy, Known.One);
102209467b48Spatrick
102309467b48Spatrick // If all of the demanded bits are known 1 on one side, return the other.
1024*d415bd75Srobert // These bits cannot contribute to the result of the 'and' in this context.
102509467b48Spatrick if (DemandedMask.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
102609467b48Spatrick return I->getOperand(0);
102709467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
102809467b48Spatrick return I->getOperand(1);
102909467b48Spatrick
103009467b48Spatrick break;
103109467b48Spatrick }
103209467b48Spatrick case Instruction::Or: {
103309467b48Spatrick computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1034*d415bd75Srobert computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1035097a140dSpatrick Known = LHSKnown | RHSKnown;
103609467b48Spatrick
103709467b48Spatrick // If the client is only demanding bits that we know, return the known
103809467b48Spatrick // constant.
1039097a140dSpatrick if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1040097a140dSpatrick return Constant::getIntegerValue(ITy, Known.One);
104109467b48Spatrick
1042*d415bd75Srobert // We can simplify (X|Y) -> X or Y in the user's context if we know that
1043*d415bd75Srobert // only bits from X or Y are demanded.
1044*d415bd75Srobert // If all of the demanded bits are known zero on one side, return the other.
1045*d415bd75Srobert // These bits cannot contribute to the result of the 'or' in this context.
104609467b48Spatrick if (DemandedMask.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
104709467b48Spatrick return I->getOperand(0);
104809467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
104909467b48Spatrick return I->getOperand(1);
105009467b48Spatrick
105109467b48Spatrick break;
105209467b48Spatrick }
105309467b48Spatrick case Instruction::Xor: {
105409467b48Spatrick computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1055*d415bd75Srobert computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1056097a140dSpatrick Known = LHSKnown ^ RHSKnown;
105709467b48Spatrick
105809467b48Spatrick // If the client is only demanding bits that we know, return the known
105909467b48Spatrick // constant.
1060097a140dSpatrick if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
1061097a140dSpatrick return Constant::getIntegerValue(ITy, Known.One);
106209467b48Spatrick
1063*d415bd75Srobert // We can simplify (X^Y) -> X or Y in the user's context if we know that
1064*d415bd75Srobert // only bits from X or Y are demanded.
1065*d415bd75Srobert // If all of the demanded bits are known zero on one side, return the other.
106609467b48Spatrick if (DemandedMask.isSubsetOf(RHSKnown.Zero))
106709467b48Spatrick return I->getOperand(0);
106809467b48Spatrick if (DemandedMask.isSubsetOf(LHSKnown.Zero))
106909467b48Spatrick return I->getOperand(1);
107009467b48Spatrick
107109467b48Spatrick break;
107209467b48Spatrick }
1073*d415bd75Srobert case Instruction::Add: {
1074*d415bd75Srobert unsigned NLZ = DemandedMask.countLeadingZeros();
1075*d415bd75Srobert APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1076*d415bd75Srobert
1077*d415bd75Srobert // If an operand adds zeros to every bit below the highest demanded bit,
1078*d415bd75Srobert // that operand doesn't change the result. Return the other side.
1079*d415bd75Srobert computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1080*d415bd75Srobert if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1081*d415bd75Srobert return I->getOperand(0);
1082*d415bd75Srobert
1083*d415bd75Srobert computeKnownBits(I->getOperand(0), LHSKnown, Depth + 1, CxtI);
1084*d415bd75Srobert if (DemandedFromOps.isSubsetOf(LHSKnown.Zero))
1085*d415bd75Srobert return I->getOperand(1);
1086*d415bd75Srobert
1087*d415bd75Srobert break;
1088*d415bd75Srobert }
1089*d415bd75Srobert case Instruction::Sub: {
1090*d415bd75Srobert unsigned NLZ = DemandedMask.countLeadingZeros();
1091*d415bd75Srobert APInt DemandedFromOps = APInt::getLowBitsSet(BitWidth, BitWidth - NLZ);
1092*d415bd75Srobert
1093*d415bd75Srobert // If an operand subtracts zeros from every bit below the highest demanded
1094*d415bd75Srobert // bit, that operand doesn't change the result. Return the other side.
1095*d415bd75Srobert computeKnownBits(I->getOperand(1), RHSKnown, Depth + 1, CxtI);
1096*d415bd75Srobert if (DemandedFromOps.isSubsetOf(RHSKnown.Zero))
1097*d415bd75Srobert return I->getOperand(0);
1098*d415bd75Srobert
1099*d415bd75Srobert break;
1100*d415bd75Srobert }
110173471bf0Spatrick case Instruction::AShr: {
110273471bf0Spatrick // Compute the Known bits to simplify things downstream.
110373471bf0Spatrick computeKnownBits(I, Known, Depth, CxtI);
110473471bf0Spatrick
110573471bf0Spatrick // If this user is only demanding bits that we know, return the known
110673471bf0Spatrick // constant.
110773471bf0Spatrick if (DemandedMask.isSubsetOf(Known.Zero | Known.One))
110873471bf0Spatrick return Constant::getIntegerValue(ITy, Known.One);
110973471bf0Spatrick
111073471bf0Spatrick // If the right shift operand 0 is a result of a left shift by the same
111173471bf0Spatrick // amount, this is probably a zero/sign extension, which may be unnecessary,
111273471bf0Spatrick // if we do not demand any of the new sign bits. So, return the original
111373471bf0Spatrick // operand instead.
111473471bf0Spatrick const APInt *ShiftRC;
111573471bf0Spatrick const APInt *ShiftLC;
111673471bf0Spatrick Value *X;
111773471bf0Spatrick unsigned BitWidth = DemandedMask.getBitWidth();
111873471bf0Spatrick if (match(I,
111973471bf0Spatrick m_AShr(m_Shl(m_Value(X), m_APInt(ShiftLC)), m_APInt(ShiftRC))) &&
112073471bf0Spatrick ShiftLC == ShiftRC && ShiftLC->ult(BitWidth) &&
112173471bf0Spatrick DemandedMask.isSubsetOf(APInt::getLowBitsSet(
112273471bf0Spatrick BitWidth, BitWidth - ShiftRC->getZExtValue()))) {
112373471bf0Spatrick return X;
112473471bf0Spatrick }
112573471bf0Spatrick
112673471bf0Spatrick break;
112773471bf0Spatrick }
112809467b48Spatrick default:
112909467b48Spatrick // Compute the Known bits to simplify things downstream.
113009467b48Spatrick computeKnownBits(I, Known, Depth, CxtI);
113109467b48Spatrick
113209467b48Spatrick // If this user is only demanding bits that we know, return the known
113309467b48Spatrick // constant.
113409467b48Spatrick if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
113509467b48Spatrick return Constant::getIntegerValue(ITy, Known.One);
113609467b48Spatrick
113709467b48Spatrick break;
113809467b48Spatrick }
113909467b48Spatrick
114009467b48Spatrick return nullptr;
114109467b48Spatrick }
114209467b48Spatrick
114309467b48Spatrick /// Helper routine of SimplifyDemandedUseBits. It tries to simplify
114409467b48Spatrick /// "E1 = (X lsr C1) << C2", where the C1 and C2 are constant, into
114509467b48Spatrick /// "E2 = X << (C2 - C1)" or "E2 = X >> (C1 - C2)", depending on the sign
114609467b48Spatrick /// of "C2-C1".
114709467b48Spatrick ///
114809467b48Spatrick /// Suppose E1 and E2 are generally different in bits S={bm, bm+1,
114909467b48Spatrick /// ..., bn}, without considering the specific value X is holding.
115009467b48Spatrick /// This transformation is legal iff one of following conditions is hold:
115109467b48Spatrick /// 1) All the bit in S are 0, in this case E1 == E2.
115209467b48Spatrick /// 2) We don't care those bits in S, per the input DemandedMask.
115309467b48Spatrick /// 3) Combination of 1) and 2). Some bits in S are 0, and we don't care the
115409467b48Spatrick /// rest bits.
115509467b48Spatrick ///
115609467b48Spatrick /// Currently we only test condition 2).
115709467b48Spatrick ///
115809467b48Spatrick /// As with SimplifyDemandedUseBits, it returns NULL if the simplification was
115909467b48Spatrick /// not successful.
simplifyShrShlDemandedBits(Instruction * Shr,const APInt & ShrOp1,Instruction * Shl,const APInt & ShlOp1,const APInt & DemandedMask,KnownBits & Known)116073471bf0Spatrick Value *InstCombinerImpl::simplifyShrShlDemandedBits(
116173471bf0Spatrick Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
116273471bf0Spatrick const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known) {
116309467b48Spatrick if (!ShlOp1 || !ShrOp1)
116409467b48Spatrick return nullptr; // No-op.
116509467b48Spatrick
116609467b48Spatrick Value *VarX = Shr->getOperand(0);
116709467b48Spatrick Type *Ty = VarX->getType();
116809467b48Spatrick unsigned BitWidth = Ty->getScalarSizeInBits();
116909467b48Spatrick if (ShlOp1.uge(BitWidth) || ShrOp1.uge(BitWidth))
117009467b48Spatrick return nullptr; // Undef.
117109467b48Spatrick
117209467b48Spatrick unsigned ShlAmt = ShlOp1.getZExtValue();
117309467b48Spatrick unsigned ShrAmt = ShrOp1.getZExtValue();
117409467b48Spatrick
117509467b48Spatrick Known.One.clearAllBits();
117609467b48Spatrick Known.Zero.setLowBits(ShlAmt - 1);
117709467b48Spatrick Known.Zero &= DemandedMask;
117809467b48Spatrick
1179*d415bd75Srobert APInt BitMask1(APInt::getAllOnes(BitWidth));
1180*d415bd75Srobert APInt BitMask2(APInt::getAllOnes(BitWidth));
118109467b48Spatrick
118209467b48Spatrick bool isLshr = (Shr->getOpcode() == Instruction::LShr);
118309467b48Spatrick BitMask1 = isLshr ? (BitMask1.lshr(ShrAmt) << ShlAmt) :
118409467b48Spatrick (BitMask1.ashr(ShrAmt) << ShlAmt);
118509467b48Spatrick
118609467b48Spatrick if (ShrAmt <= ShlAmt) {
118709467b48Spatrick BitMask2 <<= (ShlAmt - ShrAmt);
118809467b48Spatrick } else {
118909467b48Spatrick BitMask2 = isLshr ? BitMask2.lshr(ShrAmt - ShlAmt):
119009467b48Spatrick BitMask2.ashr(ShrAmt - ShlAmt);
119109467b48Spatrick }
119209467b48Spatrick
119309467b48Spatrick // Check if condition-2 (see the comment to this function) is satified.
119409467b48Spatrick if ((BitMask1 & DemandedMask) == (BitMask2 & DemandedMask)) {
119509467b48Spatrick if (ShrAmt == ShlAmt)
119609467b48Spatrick return VarX;
119709467b48Spatrick
119809467b48Spatrick if (!Shr->hasOneUse())
119909467b48Spatrick return nullptr;
120009467b48Spatrick
120109467b48Spatrick BinaryOperator *New;
120209467b48Spatrick if (ShrAmt < ShlAmt) {
120309467b48Spatrick Constant *Amt = ConstantInt::get(VarX->getType(), ShlAmt - ShrAmt);
120409467b48Spatrick New = BinaryOperator::CreateShl(VarX, Amt);
120509467b48Spatrick BinaryOperator *Orig = cast<BinaryOperator>(Shl);
120609467b48Spatrick New->setHasNoSignedWrap(Orig->hasNoSignedWrap());
120709467b48Spatrick New->setHasNoUnsignedWrap(Orig->hasNoUnsignedWrap());
120809467b48Spatrick } else {
120909467b48Spatrick Constant *Amt = ConstantInt::get(VarX->getType(), ShrAmt - ShlAmt);
121009467b48Spatrick New = isLshr ? BinaryOperator::CreateLShr(VarX, Amt) :
121109467b48Spatrick BinaryOperator::CreateAShr(VarX, Amt);
121209467b48Spatrick if (cast<BinaryOperator>(Shr)->isExact())
121309467b48Spatrick New->setIsExact(true);
121409467b48Spatrick }
121509467b48Spatrick
121609467b48Spatrick return InsertNewInstWith(New, *Shl);
121709467b48Spatrick }
121809467b48Spatrick
121909467b48Spatrick return nullptr;
122009467b48Spatrick }
122109467b48Spatrick
122209467b48Spatrick /// The specified value produces a vector with any number of elements.
122373471bf0Spatrick /// This method analyzes which elements of the operand are undef or poison and
122473471bf0Spatrick /// returns that information in UndefElts.
122509467b48Spatrick ///
122609467b48Spatrick /// DemandedElts contains the set of elements that are actually used by the
122709467b48Spatrick /// caller, and by default (AllowMultipleUsers equals false) the value is
122809467b48Spatrick /// simplified only if it has a single caller. If AllowMultipleUsers is set
122909467b48Spatrick /// to true, DemandedElts refers to the union of sets of elements that are
123009467b48Spatrick /// used by all callers.
123109467b48Spatrick ///
123209467b48Spatrick /// If the information about demanded elements can be used to simplify the
123309467b48Spatrick /// operation, the operation is simplified, then the resultant value is
123409467b48Spatrick /// returned. This returns null if no change was made.
SimplifyDemandedVectorElts(Value * V,APInt DemandedElts,APInt & UndefElts,unsigned Depth,bool AllowMultipleUsers)123573471bf0Spatrick Value *InstCombinerImpl::SimplifyDemandedVectorElts(Value *V,
123673471bf0Spatrick APInt DemandedElts,
123709467b48Spatrick APInt &UndefElts,
123809467b48Spatrick unsigned Depth,
123909467b48Spatrick bool AllowMultipleUsers) {
1240097a140dSpatrick // Cannot analyze scalable type. The number of vector elements is not a
1241097a140dSpatrick // compile-time constant.
1242097a140dSpatrick if (isa<ScalableVectorType>(V->getType()))
1243097a140dSpatrick return nullptr;
1244097a140dSpatrick
1245097a140dSpatrick unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
1246*d415bd75Srobert APInt EltMask(APInt::getAllOnes(VWidth));
124709467b48Spatrick assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
124809467b48Spatrick
124973471bf0Spatrick if (match(V, m_Undef())) {
125073471bf0Spatrick // If the entire vector is undef or poison, just return this info.
125109467b48Spatrick UndefElts = EltMask;
125209467b48Spatrick return nullptr;
125309467b48Spatrick }
125409467b48Spatrick
1255*d415bd75Srobert if (DemandedElts.isZero()) { // If nothing is demanded, provide poison.
125609467b48Spatrick UndefElts = EltMask;
125773471bf0Spatrick return PoisonValue::get(V->getType());
125809467b48Spatrick }
125909467b48Spatrick
126009467b48Spatrick UndefElts = 0;
126109467b48Spatrick
126209467b48Spatrick if (auto *C = dyn_cast<Constant>(V)) {
126309467b48Spatrick // Check if this is identity. If so, return 0 since we are not simplifying
126409467b48Spatrick // anything.
1265*d415bd75Srobert if (DemandedElts.isAllOnes())
126609467b48Spatrick return nullptr;
126709467b48Spatrick
126809467b48Spatrick Type *EltTy = cast<VectorType>(V->getType())->getElementType();
126973471bf0Spatrick Constant *Poison = PoisonValue::get(EltTy);
127009467b48Spatrick SmallVector<Constant*, 16> Elts;
127109467b48Spatrick for (unsigned i = 0; i != VWidth; ++i) {
127273471bf0Spatrick if (!DemandedElts[i]) { // If not demanded, set to poison.
127373471bf0Spatrick Elts.push_back(Poison);
127409467b48Spatrick UndefElts.setBit(i);
127509467b48Spatrick continue;
127609467b48Spatrick }
127709467b48Spatrick
127809467b48Spatrick Constant *Elt = C->getAggregateElement(i);
127909467b48Spatrick if (!Elt) return nullptr;
128009467b48Spatrick
128109467b48Spatrick Elts.push_back(Elt);
128273471bf0Spatrick if (isa<UndefValue>(Elt)) // Already undef or poison.
128373471bf0Spatrick UndefElts.setBit(i);
128409467b48Spatrick }
128509467b48Spatrick
128609467b48Spatrick // If we changed the constant, return it.
128709467b48Spatrick Constant *NewCV = ConstantVector::get(Elts);
128809467b48Spatrick return NewCV != C ? NewCV : nullptr;
128909467b48Spatrick }
129009467b48Spatrick
129109467b48Spatrick // Limit search depth.
129209467b48Spatrick if (Depth == 10)
129309467b48Spatrick return nullptr;
129409467b48Spatrick
129509467b48Spatrick if (!AllowMultipleUsers) {
129609467b48Spatrick // If multiple users are using the root value, proceed with
129709467b48Spatrick // simplification conservatively assuming that all elements
129809467b48Spatrick // are needed.
129909467b48Spatrick if (!V->hasOneUse()) {
130009467b48Spatrick // Quit if we find multiple users of a non-root value though.
130109467b48Spatrick // They'll be handled when it's their turn to be visited by
130209467b48Spatrick // the main instcombine process.
130309467b48Spatrick if (Depth != 0)
130409467b48Spatrick // TODO: Just compute the UndefElts information recursively.
130509467b48Spatrick return nullptr;
130609467b48Spatrick
130709467b48Spatrick // Conservatively assume that all elements are needed.
130809467b48Spatrick DemandedElts = EltMask;
130909467b48Spatrick }
131009467b48Spatrick }
131109467b48Spatrick
131209467b48Spatrick Instruction *I = dyn_cast<Instruction>(V);
131309467b48Spatrick if (!I) return nullptr; // Only analyze instructions.
131409467b48Spatrick
131509467b48Spatrick bool MadeChange = false;
131609467b48Spatrick auto simplifyAndSetOp = [&](Instruction *Inst, unsigned OpNum,
131709467b48Spatrick APInt Demanded, APInt &Undef) {
131809467b48Spatrick auto *II = dyn_cast<IntrinsicInst>(Inst);
131909467b48Spatrick Value *Op = II ? II->getArgOperand(OpNum) : Inst->getOperand(OpNum);
132009467b48Spatrick if (Value *V = SimplifyDemandedVectorElts(Op, Demanded, Undef, Depth + 1)) {
1321097a140dSpatrick replaceOperand(*Inst, OpNum, V);
132209467b48Spatrick MadeChange = true;
132309467b48Spatrick }
132409467b48Spatrick };
132509467b48Spatrick
132609467b48Spatrick APInt UndefElts2(VWidth, 0);
132709467b48Spatrick APInt UndefElts3(VWidth, 0);
132809467b48Spatrick switch (I->getOpcode()) {
132909467b48Spatrick default: break;
133009467b48Spatrick
133109467b48Spatrick case Instruction::GetElementPtr: {
133209467b48Spatrick // The LangRef requires that struct geps have all constant indices. As
133309467b48Spatrick // such, we can't convert any operand to partial undef.
133409467b48Spatrick auto mayIndexStructType = [](GetElementPtrInst &GEP) {
133509467b48Spatrick for (auto I = gep_type_begin(GEP), E = gep_type_end(GEP);
133609467b48Spatrick I != E; I++)
133709467b48Spatrick if (I.isStruct())
1338*d415bd75Srobert return true;
133909467b48Spatrick return false;
134009467b48Spatrick };
134109467b48Spatrick if (mayIndexStructType(cast<GetElementPtrInst>(*I)))
134209467b48Spatrick break;
134309467b48Spatrick
134409467b48Spatrick // Conservatively track the demanded elements back through any vector
134509467b48Spatrick // operands we may have. We know there must be at least one, or we
134609467b48Spatrick // wouldn't have a vector result to get here. Note that we intentionally
1347*d415bd75Srobert // merge the undef bits here since gepping with either an poison base or
1348*d415bd75Srobert // index results in poison.
134909467b48Spatrick for (unsigned i = 0; i < I->getNumOperands(); i++) {
1350*d415bd75Srobert if (i == 0 ? match(I->getOperand(i), m_Undef())
1351*d415bd75Srobert : match(I->getOperand(i), m_Poison())) {
135209467b48Spatrick // If the entire vector is undefined, just return this info.
135309467b48Spatrick UndefElts = EltMask;
135409467b48Spatrick return nullptr;
135509467b48Spatrick }
135609467b48Spatrick if (I->getOperand(i)->getType()->isVectorTy()) {
135709467b48Spatrick APInt UndefEltsOp(VWidth, 0);
135809467b48Spatrick simplifyAndSetOp(I, i, DemandedElts, UndefEltsOp);
1359*d415bd75Srobert // gep(x, undef) is not undef, so skip considering idx ops here
1360*d415bd75Srobert // Note that we could propagate poison, but we can't distinguish between
1361*d415bd75Srobert // undef & poison bits ATM
1362*d415bd75Srobert if (i == 0)
136309467b48Spatrick UndefElts |= UndefEltsOp;
136409467b48Spatrick }
136509467b48Spatrick }
136609467b48Spatrick
136709467b48Spatrick break;
136809467b48Spatrick }
136909467b48Spatrick case Instruction::InsertElement: {
137009467b48Spatrick // If this is a variable index, we don't know which element it overwrites.
137109467b48Spatrick // demand exactly the same input as we produce.
137209467b48Spatrick ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
137309467b48Spatrick if (!Idx) {
137409467b48Spatrick // Note that we can't propagate undef elt info, because we don't know
137509467b48Spatrick // which elt is getting updated.
137609467b48Spatrick simplifyAndSetOp(I, 0, DemandedElts, UndefElts2);
137709467b48Spatrick break;
137809467b48Spatrick }
137909467b48Spatrick
138009467b48Spatrick // The element inserted overwrites whatever was there, so the input demanded
138109467b48Spatrick // set is simpler than the output set.
138209467b48Spatrick unsigned IdxNo = Idx->getZExtValue();
138309467b48Spatrick APInt PreInsertDemandedElts = DemandedElts;
138409467b48Spatrick if (IdxNo < VWidth)
138509467b48Spatrick PreInsertDemandedElts.clearBit(IdxNo);
138609467b48Spatrick
138773471bf0Spatrick // If we only demand the element that is being inserted and that element
138873471bf0Spatrick // was extracted from the same index in another vector with the same type,
138973471bf0Spatrick // replace this insert with that other vector.
139073471bf0Spatrick // Note: This is attempted before the call to simplifyAndSetOp because that
139173471bf0Spatrick // may change UndefElts to a value that does not match with Vec.
139273471bf0Spatrick Value *Vec;
139373471bf0Spatrick if (PreInsertDemandedElts == 0 &&
139473471bf0Spatrick match(I->getOperand(1),
139573471bf0Spatrick m_ExtractElt(m_Value(Vec), m_SpecificInt(IdxNo))) &&
139673471bf0Spatrick Vec->getType() == I->getType()) {
139773471bf0Spatrick return Vec;
139873471bf0Spatrick }
139973471bf0Spatrick
140009467b48Spatrick simplifyAndSetOp(I, 0, PreInsertDemandedElts, UndefElts);
140109467b48Spatrick
140209467b48Spatrick // If this is inserting an element that isn't demanded, remove this
140309467b48Spatrick // insertelement.
140409467b48Spatrick if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1405097a140dSpatrick Worklist.push(I);
140609467b48Spatrick return I->getOperand(0);
140709467b48Spatrick }
140809467b48Spatrick
140909467b48Spatrick // The inserted element is defined.
141009467b48Spatrick UndefElts.clearBit(IdxNo);
141109467b48Spatrick break;
141209467b48Spatrick }
141309467b48Spatrick case Instruction::ShuffleVector: {
141409467b48Spatrick auto *Shuffle = cast<ShuffleVectorInst>(I);
141509467b48Spatrick assert(Shuffle->getOperand(0)->getType() ==
141609467b48Spatrick Shuffle->getOperand(1)->getType() &&
141709467b48Spatrick "Expected shuffle operands to have same type");
141873471bf0Spatrick unsigned OpWidth = cast<FixedVectorType>(Shuffle->getOperand(0)->getType())
141973471bf0Spatrick ->getNumElements();
1420097a140dSpatrick // Handle trivial case of a splat. Only check the first element of LHS
1421097a140dSpatrick // operand.
1422097a140dSpatrick if (all_of(Shuffle->getShuffleMask(), [](int Elt) { return Elt == 0; }) &&
1423*d415bd75Srobert DemandedElts.isAllOnes()) {
142473471bf0Spatrick if (!match(I->getOperand(1), m_Undef())) {
142573471bf0Spatrick I->setOperand(1, PoisonValue::get(I->getOperand(1)->getType()));
1426097a140dSpatrick MadeChange = true;
1427097a140dSpatrick }
1428097a140dSpatrick APInt LeftDemanded(OpWidth, 1);
1429097a140dSpatrick APInt LHSUndefElts(OpWidth, 0);
1430097a140dSpatrick simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
1431097a140dSpatrick if (LHSUndefElts[0])
1432097a140dSpatrick UndefElts = EltMask;
1433097a140dSpatrick else
1434097a140dSpatrick UndefElts.clearAllBits();
1435097a140dSpatrick break;
1436097a140dSpatrick }
1437097a140dSpatrick
143809467b48Spatrick APInt LeftDemanded(OpWidth, 0), RightDemanded(OpWidth, 0);
143909467b48Spatrick for (unsigned i = 0; i < VWidth; i++) {
144009467b48Spatrick if (DemandedElts[i]) {
144109467b48Spatrick unsigned MaskVal = Shuffle->getMaskValue(i);
144209467b48Spatrick if (MaskVal != -1u) {
144309467b48Spatrick assert(MaskVal < OpWidth * 2 &&
144409467b48Spatrick "shufflevector mask index out of range!");
144509467b48Spatrick if (MaskVal < OpWidth)
144609467b48Spatrick LeftDemanded.setBit(MaskVal);
144709467b48Spatrick else
144809467b48Spatrick RightDemanded.setBit(MaskVal - OpWidth);
144909467b48Spatrick }
145009467b48Spatrick }
145109467b48Spatrick }
145209467b48Spatrick
145309467b48Spatrick APInt LHSUndefElts(OpWidth, 0);
145409467b48Spatrick simplifyAndSetOp(I, 0, LeftDemanded, LHSUndefElts);
145509467b48Spatrick
145609467b48Spatrick APInt RHSUndefElts(OpWidth, 0);
145709467b48Spatrick simplifyAndSetOp(I, 1, RightDemanded, RHSUndefElts);
145809467b48Spatrick
145909467b48Spatrick // If this shuffle does not change the vector length and the elements
146009467b48Spatrick // demanded by this shuffle are an identity mask, then this shuffle is
146109467b48Spatrick // unnecessary.
146209467b48Spatrick //
146309467b48Spatrick // We are assuming canonical form for the mask, so the source vector is
146409467b48Spatrick // operand 0 and operand 1 is not used.
146509467b48Spatrick //
146609467b48Spatrick // Note that if an element is demanded and this shuffle mask is undefined
146709467b48Spatrick // for that element, then the shuffle is not considered an identity
146809467b48Spatrick // operation. The shuffle prevents poison from the operand vector from
146909467b48Spatrick // leaking to the result by replacing poison with an undefined value.
147009467b48Spatrick if (VWidth == OpWidth) {
147109467b48Spatrick bool IsIdentityShuffle = true;
147209467b48Spatrick for (unsigned i = 0; i < VWidth; i++) {
147309467b48Spatrick unsigned MaskVal = Shuffle->getMaskValue(i);
147409467b48Spatrick if (DemandedElts[i] && i != MaskVal) {
147509467b48Spatrick IsIdentityShuffle = false;
147609467b48Spatrick break;
147709467b48Spatrick }
147809467b48Spatrick }
147909467b48Spatrick if (IsIdentityShuffle)
148009467b48Spatrick return Shuffle->getOperand(0);
148109467b48Spatrick }
148209467b48Spatrick
148309467b48Spatrick bool NewUndefElts = false;
148409467b48Spatrick unsigned LHSIdx = -1u, LHSValIdx = -1u;
148509467b48Spatrick unsigned RHSIdx = -1u, RHSValIdx = -1u;
148609467b48Spatrick bool LHSUniform = true;
148709467b48Spatrick bool RHSUniform = true;
148809467b48Spatrick for (unsigned i = 0; i < VWidth; i++) {
148909467b48Spatrick unsigned MaskVal = Shuffle->getMaskValue(i);
149009467b48Spatrick if (MaskVal == -1u) {
149109467b48Spatrick UndefElts.setBit(i);
149209467b48Spatrick } else if (!DemandedElts[i]) {
149309467b48Spatrick NewUndefElts = true;
149409467b48Spatrick UndefElts.setBit(i);
149509467b48Spatrick } else if (MaskVal < OpWidth) {
149609467b48Spatrick if (LHSUndefElts[MaskVal]) {
149709467b48Spatrick NewUndefElts = true;
149809467b48Spatrick UndefElts.setBit(i);
149909467b48Spatrick } else {
150009467b48Spatrick LHSIdx = LHSIdx == -1u ? i : OpWidth;
150109467b48Spatrick LHSValIdx = LHSValIdx == -1u ? MaskVal : OpWidth;
150209467b48Spatrick LHSUniform = LHSUniform && (MaskVal == i);
150309467b48Spatrick }
150409467b48Spatrick } else {
150509467b48Spatrick if (RHSUndefElts[MaskVal - OpWidth]) {
150609467b48Spatrick NewUndefElts = true;
150709467b48Spatrick UndefElts.setBit(i);
150809467b48Spatrick } else {
150909467b48Spatrick RHSIdx = RHSIdx == -1u ? i : OpWidth;
151009467b48Spatrick RHSValIdx = RHSValIdx == -1u ? MaskVal - OpWidth : OpWidth;
151109467b48Spatrick RHSUniform = RHSUniform && (MaskVal - OpWidth == i);
151209467b48Spatrick }
151309467b48Spatrick }
151409467b48Spatrick }
151509467b48Spatrick
151609467b48Spatrick // Try to transform shuffle with constant vector and single element from
151709467b48Spatrick // this constant vector to single insertelement instruction.
151809467b48Spatrick // shufflevector V, C, <v1, v2, .., ci, .., vm> ->
151909467b48Spatrick // insertelement V, C[ci], ci-n
152073471bf0Spatrick if (OpWidth ==
152173471bf0Spatrick cast<FixedVectorType>(Shuffle->getType())->getNumElements()) {
152209467b48Spatrick Value *Op = nullptr;
152309467b48Spatrick Constant *Value = nullptr;
152409467b48Spatrick unsigned Idx = -1u;
152509467b48Spatrick
152609467b48Spatrick // Find constant vector with the single element in shuffle (LHS or RHS).
152709467b48Spatrick if (LHSIdx < OpWidth && RHSUniform) {
152809467b48Spatrick if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(0))) {
152909467b48Spatrick Op = Shuffle->getOperand(1);
153009467b48Spatrick Value = CV->getOperand(LHSValIdx);
153109467b48Spatrick Idx = LHSIdx;
153209467b48Spatrick }
153309467b48Spatrick }
153409467b48Spatrick if (RHSIdx < OpWidth && LHSUniform) {
153509467b48Spatrick if (auto *CV = dyn_cast<ConstantVector>(Shuffle->getOperand(1))) {
153609467b48Spatrick Op = Shuffle->getOperand(0);
153709467b48Spatrick Value = CV->getOperand(RHSValIdx);
153809467b48Spatrick Idx = RHSIdx;
153909467b48Spatrick }
154009467b48Spatrick }
154109467b48Spatrick // Found constant vector with single element - convert to insertelement.
154209467b48Spatrick if (Op && Value) {
154309467b48Spatrick Instruction *New = InsertElementInst::Create(
154409467b48Spatrick Op, Value, ConstantInt::get(Type::getInt32Ty(I->getContext()), Idx),
154509467b48Spatrick Shuffle->getName());
154609467b48Spatrick InsertNewInstWith(New, *Shuffle);
154709467b48Spatrick return New;
154809467b48Spatrick }
154909467b48Spatrick }
155009467b48Spatrick if (NewUndefElts) {
155109467b48Spatrick // Add additional discovered undefs.
1552097a140dSpatrick SmallVector<int, 16> Elts;
155309467b48Spatrick for (unsigned i = 0; i < VWidth; ++i) {
155409467b48Spatrick if (UndefElts[i])
1555097a140dSpatrick Elts.push_back(UndefMaskElem);
155609467b48Spatrick else
1557097a140dSpatrick Elts.push_back(Shuffle->getMaskValue(i));
155809467b48Spatrick }
1559097a140dSpatrick Shuffle->setShuffleMask(Elts);
156009467b48Spatrick MadeChange = true;
156109467b48Spatrick }
156209467b48Spatrick break;
156309467b48Spatrick }
156409467b48Spatrick case Instruction::Select: {
156509467b48Spatrick // If this is a vector select, try to transform the select condition based
156609467b48Spatrick // on the current demanded elements.
156709467b48Spatrick SelectInst *Sel = cast<SelectInst>(I);
156809467b48Spatrick if (Sel->getCondition()->getType()->isVectorTy()) {
156909467b48Spatrick // TODO: We are not doing anything with UndefElts based on this call.
157009467b48Spatrick // It is overwritten below based on the other select operands. If an
157109467b48Spatrick // element of the select condition is known undef, then we are free to
157209467b48Spatrick // choose the output value from either arm of the select. If we know that
157309467b48Spatrick // one of those values is undef, then the output can be undef.
157409467b48Spatrick simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
157509467b48Spatrick }
157609467b48Spatrick
157709467b48Spatrick // Next, see if we can transform the arms of the select.
157809467b48Spatrick APInt DemandedLHS(DemandedElts), DemandedRHS(DemandedElts);
157909467b48Spatrick if (auto *CV = dyn_cast<ConstantVector>(Sel->getCondition())) {
158009467b48Spatrick for (unsigned i = 0; i < VWidth; i++) {
158109467b48Spatrick // isNullValue() always returns false when called on a ConstantExpr.
158209467b48Spatrick // Skip constant expressions to avoid propagating incorrect information.
158309467b48Spatrick Constant *CElt = CV->getAggregateElement(i);
158409467b48Spatrick if (isa<ConstantExpr>(CElt))
158509467b48Spatrick continue;
158609467b48Spatrick // TODO: If a select condition element is undef, we can demand from
158709467b48Spatrick // either side. If one side is known undef, choosing that side would
158809467b48Spatrick // propagate undef.
158909467b48Spatrick if (CElt->isNullValue())
159009467b48Spatrick DemandedLHS.clearBit(i);
159109467b48Spatrick else
159209467b48Spatrick DemandedRHS.clearBit(i);
159309467b48Spatrick }
159409467b48Spatrick }
159509467b48Spatrick
159609467b48Spatrick simplifyAndSetOp(I, 1, DemandedLHS, UndefElts2);
159709467b48Spatrick simplifyAndSetOp(I, 2, DemandedRHS, UndefElts3);
159809467b48Spatrick
159909467b48Spatrick // Output elements are undefined if the element from each arm is undefined.
160009467b48Spatrick // TODO: This can be improved. See comment in select condition handling.
160109467b48Spatrick UndefElts = UndefElts2 & UndefElts3;
160209467b48Spatrick break;
160309467b48Spatrick }
160409467b48Spatrick case Instruction::BitCast: {
160509467b48Spatrick // Vector->vector casts only.
160609467b48Spatrick VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
160709467b48Spatrick if (!VTy) break;
160873471bf0Spatrick unsigned InVWidth = cast<FixedVectorType>(VTy)->getNumElements();
160909467b48Spatrick APInt InputDemandedElts(InVWidth, 0);
161009467b48Spatrick UndefElts2 = APInt(InVWidth, 0);
161109467b48Spatrick unsigned Ratio;
161209467b48Spatrick
161309467b48Spatrick if (VWidth == InVWidth) {
161409467b48Spatrick // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
161509467b48Spatrick // elements as are demanded of us.
161609467b48Spatrick Ratio = 1;
161709467b48Spatrick InputDemandedElts = DemandedElts;
161809467b48Spatrick } else if ((VWidth % InVWidth) == 0) {
161909467b48Spatrick // If the number of elements in the output is a multiple of the number of
162009467b48Spatrick // elements in the input then an input element is live if any of the
162109467b48Spatrick // corresponding output elements are live.
162209467b48Spatrick Ratio = VWidth / InVWidth;
162309467b48Spatrick for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
162409467b48Spatrick if (DemandedElts[OutIdx])
162509467b48Spatrick InputDemandedElts.setBit(OutIdx / Ratio);
162609467b48Spatrick } else if ((InVWidth % VWidth) == 0) {
162709467b48Spatrick // If the number of elements in the input is a multiple of the number of
162809467b48Spatrick // elements in the output then an input element is live if the
162909467b48Spatrick // corresponding output element is live.
163009467b48Spatrick Ratio = InVWidth / VWidth;
163109467b48Spatrick for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
163209467b48Spatrick if (DemandedElts[InIdx / Ratio])
163309467b48Spatrick InputDemandedElts.setBit(InIdx);
163409467b48Spatrick } else {
163509467b48Spatrick // Unsupported so far.
163609467b48Spatrick break;
163709467b48Spatrick }
163809467b48Spatrick
163909467b48Spatrick simplifyAndSetOp(I, 0, InputDemandedElts, UndefElts2);
164009467b48Spatrick
164109467b48Spatrick if (VWidth == InVWidth) {
164209467b48Spatrick UndefElts = UndefElts2;
164309467b48Spatrick } else if ((VWidth % InVWidth) == 0) {
164409467b48Spatrick // If the number of elements in the output is a multiple of the number of
164509467b48Spatrick // elements in the input then an output element is undef if the
164609467b48Spatrick // corresponding input element is undef.
164709467b48Spatrick for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
164809467b48Spatrick if (UndefElts2[OutIdx / Ratio])
164909467b48Spatrick UndefElts.setBit(OutIdx);
165009467b48Spatrick } else if ((InVWidth % VWidth) == 0) {
165109467b48Spatrick // If the number of elements in the input is a multiple of the number of
165209467b48Spatrick // elements in the output then an output element is undef if all of the
165309467b48Spatrick // corresponding input elements are undef.
165409467b48Spatrick for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
165509467b48Spatrick APInt SubUndef = UndefElts2.lshr(OutIdx * Ratio).zextOrTrunc(Ratio);
165609467b48Spatrick if (SubUndef.countPopulation() == Ratio)
165709467b48Spatrick UndefElts.setBit(OutIdx);
165809467b48Spatrick }
165909467b48Spatrick } else {
166009467b48Spatrick llvm_unreachable("Unimp");
166109467b48Spatrick }
166209467b48Spatrick break;
166309467b48Spatrick }
166409467b48Spatrick case Instruction::FPTrunc:
166509467b48Spatrick case Instruction::FPExt:
166609467b48Spatrick simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
166709467b48Spatrick break;
166809467b48Spatrick
166909467b48Spatrick case Instruction::Call: {
167009467b48Spatrick IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
167109467b48Spatrick if (!II) break;
167209467b48Spatrick switch (II->getIntrinsicID()) {
167309467b48Spatrick case Intrinsic::masked_gather: // fallthrough
167409467b48Spatrick case Intrinsic::masked_load: {
167509467b48Spatrick // Subtlety: If we load from a pointer, the pointer must be valid
167609467b48Spatrick // regardless of whether the element is demanded. Doing otherwise risks
167709467b48Spatrick // segfaults which didn't exist in the original program.
1678*d415bd75Srobert APInt DemandedPtrs(APInt::getAllOnes(VWidth)),
167909467b48Spatrick DemandedPassThrough(DemandedElts);
168009467b48Spatrick if (auto *CV = dyn_cast<ConstantVector>(II->getOperand(2)))
168109467b48Spatrick for (unsigned i = 0; i < VWidth; i++) {
168209467b48Spatrick Constant *CElt = CV->getAggregateElement(i);
168309467b48Spatrick if (CElt->isNullValue())
168409467b48Spatrick DemandedPtrs.clearBit(i);
168509467b48Spatrick else if (CElt->isAllOnesValue())
168609467b48Spatrick DemandedPassThrough.clearBit(i);
168709467b48Spatrick }
168809467b48Spatrick if (II->getIntrinsicID() == Intrinsic::masked_gather)
168909467b48Spatrick simplifyAndSetOp(II, 0, DemandedPtrs, UndefElts2);
169009467b48Spatrick simplifyAndSetOp(II, 3, DemandedPassThrough, UndefElts3);
169109467b48Spatrick
169209467b48Spatrick // Output elements are undefined if the element from both sources are.
169309467b48Spatrick // TODO: can strengthen via mask as well.
169409467b48Spatrick UndefElts = UndefElts2 & UndefElts3;
169509467b48Spatrick break;
169609467b48Spatrick }
169709467b48Spatrick default: {
169873471bf0Spatrick // Handle target specific intrinsics
1699*d415bd75Srobert std::optional<Value *> V = targetSimplifyDemandedVectorEltsIntrinsic(
170073471bf0Spatrick *II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
170173471bf0Spatrick simplifyAndSetOp);
1702*d415bd75Srobert if (V)
1703*d415bd75Srobert return *V;
170409467b48Spatrick break;
170509467b48Spatrick }
170609467b48Spatrick } // switch on IntrinsicID
170709467b48Spatrick break;
170809467b48Spatrick } // case Call
170909467b48Spatrick } // switch on Opcode
171009467b48Spatrick
171109467b48Spatrick // TODO: We bail completely on integer div/rem and shifts because they have
171209467b48Spatrick // UB/poison potential, but that should be refined.
171309467b48Spatrick BinaryOperator *BO;
171409467b48Spatrick if (match(I, m_BinOp(BO)) && !BO->isIntDivRem() && !BO->isShift()) {
171509467b48Spatrick simplifyAndSetOp(I, 0, DemandedElts, UndefElts);
171609467b48Spatrick simplifyAndSetOp(I, 1, DemandedElts, UndefElts2);
171709467b48Spatrick
171809467b48Spatrick // Output elements are undefined if both are undefined. Consider things
171909467b48Spatrick // like undef & 0. The result is known zero, not undef.
172009467b48Spatrick UndefElts &= UndefElts2;
172109467b48Spatrick }
172209467b48Spatrick
172309467b48Spatrick // If we've proven all of the lanes undef, return an undef value.
172409467b48Spatrick // TODO: Intersect w/demanded lanes
1725*d415bd75Srobert if (UndefElts.isAllOnes())
172609467b48Spatrick return UndefValue::get(I->getType());;
172709467b48Spatrick
172809467b48Spatrick return MadeChange ? I : nullptr;
172909467b48Spatrick }
1730