[llvm] [InstCombine] Optimize nested select operators into a simpler form. Added test cases (PR #201453)
via llvm-commits
llvm-commits at lists.llvm.org
Sat Jun 6 06:38:54 PDT 2026
github-actions[bot] wrote:
<!--LLVM CODE FORMAT COMMENT: {clang-format}-->
:warning: C/C++ code formatter, clang-format found issues in your code. :warning:
<details>
<summary>
You can test this locally with the following command:
</summary>
``````````bash
git-clang-format --diff origin/main HEAD --extensions cpp -- llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp --diff_from_common_commit
``````````
:warning:
The reproduction instructions above might return results for more than one PR
in a stack if you are using a stacked PR workflow. You can limit the results by
changing `origin/main` to the base branch/commit you want to compare against.
:warning:
</details>
<details>
<summary>
View the diff from clang-format here.
</summary>
``````````diff
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
index 49d265cc3..2879d3ff3 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
@@ -4871,10 +4871,9 @@ Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
// x = select c1, a, b
// y = select CondVal, x, FalseVal
Value *C1 = X->getCondition();
- Value *A = X->getTrueValue();
- Value *B = X->getFalseValue();
- if (C1->getType()->isIntegerTy(1) &&
- CondVal->getType()->isIntegerTy(1) &&
+ Value *A = X->getTrueValue();
+ Value *B = X->getFalseValue();
+ if (C1->getType()->isIntegerTy(1) && CondVal->getType()->isIntegerTy(1) &&
impliesPoison(C1, CondVal)) {
if (FalseVal == A) {
// y = !c1 && CondVal ? b : a
@@ -4894,10 +4893,9 @@ Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
// x = select c1, a, b
// y = select CondVal, TrueVal, x
Value *C1 = X->getCondition();
- Value *A = X->getTrueValue();
- Value *B = X->getFalseValue();
- if (C1->getType()->isIntegerTy(1) &&
- CondVal->getType()->isIntegerTy(1) &&
+ Value *A = X->getTrueValue();
+ Value *B = X->getFalseValue();
+ if (C1->getType()->isIntegerTy(1) && CondVal->getType()->isIntegerTy(1) &&
impliesPoison(C1, CondVal)) {
if (TrueVal == A) {
// y = !c1 && !CondVal ? b : a
@@ -4913,482 +4911,490 @@ Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
return replaceInstUsesWith(SI, NewSel);
}
}
- }
+ }
- // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
- auto *TI = dyn_cast<Instruction>(TrueVal);
- auto *FI = dyn_cast<Instruction>(FalseVal);
- if (TI && FI && TI->getOpcode() == FI->getOpcode())
- if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
- return IV;
+ // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
+ auto *TI = dyn_cast<Instruction>(TrueVal);
+ auto *FI = dyn_cast<Instruction>(FalseVal);
+ if (TI && FI && TI->getOpcode() == FI->getOpcode())
+ if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
+ return IV;
- if (Instruction *I = foldSelectIntrinsic(SI))
- return I;
+ if (Instruction *I = foldSelectIntrinsic(SI))
+ return I;
- if (Instruction *I = foldSelectExtConst(SI))
- return I;
+ if (Instruction *I = foldSelectExtConst(SI))
+ return I;
- if (Instruction *I = foldSelectWithSRem(SI, *this, Builder))
- return I;
+ if (Instruction *I = foldSelectWithSRem(SI, *this, Builder))
+ return I;
- // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
- // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
- auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
- bool Swap) -> GetElementPtrInst * {
- Value *Ptr = Gep->getPointerOperand();
- if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
- !Gep->hasOneUse())
- return nullptr;
- Value *Idx = Gep->getOperand(1);
- if (isa<VectorType>(CondVal->getType()) && !isa<VectorType>(Idx->getType()))
- return nullptr;
- Type *ElementType = Gep->getSourceElementType();
- Value *NewT = Idx;
- Value *NewF = Constant::getNullValue(Idx->getType());
- if (Swap)
- std::swap(NewT, NewF);
- Value *NewSI =
- Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI);
- return GetElementPtrInst::Create(ElementType, Ptr, NewSI,
- Gep->getNoWrapFlags());
- };
- if (auto *TrueGep = dyn_cast<GetElementPtrInst>(TrueVal))
- if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
- return NewGep;
- if (auto *FalseGep = dyn_cast<GetElementPtrInst>(FalseVal))
- if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
- return NewGep;
-
- // See if we can fold the select into one of our operands.
- if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
- if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
- return FoldI;
+ // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
+ // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
+ auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
+ bool Swap) -> GetElementPtrInst * {
+ Value *Ptr = Gep->getPointerOperand();
+ if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
+ !Gep->hasOneUse())
+ return nullptr;
+ Value *Idx = Gep->getOperand(1);
+ if (isa<VectorType>(CondVal->getType()) &&
+ !isa<VectorType>(Idx->getType()))
+ return nullptr;
+ Type *ElementType = Gep->getSourceElementType();
+ Value *NewT = Idx;
+ Value *NewF = Constant::getNullValue(Idx->getType());
+ if (Swap)
+ std::swap(NewT, NewF);
+ Value *NewSI =
+ Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI);
+ return GetElementPtrInst::Create(ElementType, Ptr, NewSI,
+ Gep->getNoWrapFlags());
+ };
+ if (auto *TrueGep = dyn_cast<GetElementPtrInst>(TrueVal))
+ if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
+ return NewGep;
+ if (auto *FalseGep = dyn_cast<GetElementPtrInst>(FalseVal))
+ if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
+ return NewGep;
+
+ // See if we can fold the select into one of our operands.
+ if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
+ if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
+ return FoldI;
+
+ Value *LHS, *RHS;
+ Instruction::CastOps CastOp;
+ SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
+ auto SPF = SPR.Flavor;
+ if (SPF) {
+ Value *LHS2, *RHS2;
+ if (SelectPatternFlavor SPF2 =
+ matchSelectPattern(LHS, LHS2, RHS2).Flavor)
+ if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
+ RHS2, SI, SPF, RHS))
+ return R;
+ if (SelectPatternFlavor SPF2 =
+ matchSelectPattern(RHS, LHS2, RHS2).Flavor)
+ if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
+ RHS2, SI, SPF, LHS))
+ return R;
+ }
- Value *LHS, *RHS;
- Instruction::CastOps CastOp;
- SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
- auto SPF = SPR.Flavor;
- if (SPF) {
- Value *LHS2, *RHS2;
- if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
- if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
- RHS2, SI, SPF, RHS))
- return R;
- if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
- if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
- RHS2, SI, SPF, LHS))
- return R;
+ if (SelectPatternResult::isMinOrMax(SPF)) {
+ // Canonicalize so that
+ // - type casts are outside select patterns.
+ // - float clamp is transformed to min/max pattern
+
+ bool IsCastNeeded = LHS->getType() != SelType;
+ Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
+ Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
+ if (IsCastNeeded || (LHS->getType()->isFPOrFPVectorTy() &&
+ ((CmpLHS != LHS && CmpLHS != RHS) ||
+ (CmpRHS != LHS && CmpRHS != RHS)))) {
+ CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
+
+ Value *Cmp;
+ if (CmpInst::isIntPredicate(MinMaxPred))
+ Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
+ else
+ Cmp = Builder.CreateFCmpFMF(MinMaxPred, LHS, RHS,
+ cast<Instruction>(SI.getCondition()));
+
+ Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
+ if (!IsCastNeeded)
+ return replaceInstUsesWith(SI, NewSI);
+
+ Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
+ return replaceInstUsesWith(SI, NewCast);
+ }
+ }
}
- if (SelectPatternResult::isMinOrMax(SPF)) {
- // Canonicalize so that
- // - type casts are outside select patterns.
- // - float clamp is transformed to min/max pattern
-
- bool IsCastNeeded = LHS->getType() != SelType;
- Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
- Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
- if (IsCastNeeded ||
- (LHS->getType()->isFPOrFPVectorTy() &&
- ((CmpLHS != LHS && CmpLHS != RHS) ||
- (CmpRHS != LHS && CmpRHS != RHS)))) {
- CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
-
- Value *Cmp;
- if (CmpInst::isIntPredicate(MinMaxPred))
- Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
- else
- Cmp = Builder.CreateFCmpFMF(MinMaxPred, LHS, RHS,
- cast<Instruction>(SI.getCondition()));
-
- Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
- if (!IsCastNeeded)
- return replaceInstUsesWith(SI, NewSI);
-
- Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
- return replaceInstUsesWith(SI, NewCast);
+ // See if we can fold the select into a phi node if the condition is a
+ // select.
+ if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
+ if (Instruction *NV = foldOpIntoPhi(SI, PN))
+ return NV;
+
+ if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
+ if (TrueSI->getCondition()->getType() == CondVal->getType()) {
+ // Fold nested selects if the inner condition can be implied by the
+ // outer condition.
+ if (Value *V = simplifyNestedSelectsUsingImpliedCond(
+ *TrueSI, CondVal, /*CondIsTrue=*/true, DL))
+ return replaceOperand(SI, 1, V);
+
+ // We choose this as normal form to enable folding on the And and
+ // shortening paths for the values (this helps getUnderlyingObjects()
+ // for example).
+ if (TrueSI->hasOneUse()) {
+ Value *And = nullptr, *OtherVal = nullptr;
+ // select(C0, select(C1, a, b), b) -> select(C0&&C1, a, b)
+ if (TrueSI->getFalseValue() == FalseVal) {
+ And = Builder.CreateLogicalAnd(
+ CondVal, TrueSI->getCondition(), "",
+ ProfcheckDisableMetadataFixes ? nullptr : &SI);
+ OtherVal = TrueSI->getTrueValue();
+ }
+ // select(C0, select(C1, b, a), b) -> select(C0&&!C1, a, b)
+ else if (TrueSI->getTrueValue() == FalseVal) {
+ Value *InvertedCond = Builder.CreateNot(TrueSI->getCondition());
+ And = Builder.CreateLogicalAnd(
+ CondVal, InvertedCond, "",
+ ProfcheckDisableMetadataFixes ? nullptr : &SI);
+ OtherVal = TrueSI->getFalseValue();
+ }
+ if (And && OtherVal) {
+ replaceOperand(SI, 0, And);
+ replaceOperand(SI, 1, OtherVal);
+ if (!ProfcheckDisableMetadataFixes)
+ setExplicitlyUnknownBranchWeightsIfProfiled(SI, DEBUG_TYPE);
+ return &SI;
+ }
+ }
}
}
- }
-
- // See if we can fold the select into a phi node if the condition is a select.
- if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
- if (Instruction *NV = foldOpIntoPhi(SI, PN))
- return NV;
-
- if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
- if (TrueSI->getCondition()->getType() == CondVal->getType()) {
- // Fold nested selects if the inner condition can be implied by the outer
- // condition.
- if (Value *V = simplifyNestedSelectsUsingImpliedCond(
- *TrueSI, CondVal, /*CondIsTrue=*/true, DL))
- return replaceOperand(SI, 1, V);
-
- // We choose this as normal form to enable folding on the And and
- // shortening paths for the values (this helps getUnderlyingObjects() for
- // example).
- if (TrueSI->hasOneUse()) {
- Value *And = nullptr, *OtherVal = nullptr;
- // select(C0, select(C1, a, b), b) -> select(C0&&C1, a, b)
- if (TrueSI->getFalseValue() == FalseVal) {
- And = Builder.CreateLogicalAnd(CondVal, TrueSI->getCondition(), "",
+ if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
+ if (FalseSI->getCondition()->getType() == CondVal->getType()) {
+ // Fold nested selects if the inner condition can be implied by the
+ // outer condition.
+ if (Value *V = simplifyNestedSelectsUsingImpliedCond(
+ *FalseSI, CondVal, /*CondIsTrue=*/false, DL))
+ return replaceOperand(SI, 2, V);
+
+ if (FalseSI->hasOneUse()) {
+ Value *Or = nullptr, *OtherVal = nullptr;
+ // select(C0, a, select(C1, a, b)) -> select(C0||C1, a, b)
+ if (FalseSI->getTrueValue() == TrueVal) {
+ Or = Builder.CreateLogicalOr(CondVal, FalseSI->getCondition(), "",
ProfcheckDisableMetadataFixes ? nullptr
: &SI);
- OtherVal = TrueSI->getTrueValue();
- }
- // select(C0, select(C1, b, a), b) -> select(C0&&!C1, a, b)
- else if (TrueSI->getTrueValue() == FalseVal) {
- Value *InvertedCond = Builder.CreateNot(TrueSI->getCondition());
- And = Builder.CreateLogicalAnd(CondVal, InvertedCond, "",
+ OtherVal = FalseSI->getFalseValue();
+ }
+ // select(C0, a, select(C1, b, a)) -> select(C0||!C1, a, b)
+ else if (FalseSI->getFalseValue() == TrueVal) {
+ Value *InvertedCond = Builder.CreateNot(FalseSI->getCondition());
+ Or = Builder.CreateLogicalOr(CondVal, InvertedCond, "",
ProfcheckDisableMetadataFixes ? nullptr
: &SI);
- OtherVal = TrueSI->getFalseValue();
- }
- if (And && OtherVal) {
- replaceOperand(SI, 0, And);
- replaceOperand(SI, 1, OtherVal);
- if (!ProfcheckDisableMetadataFixes)
- setExplicitlyUnknownBranchWeightsIfProfiled(SI, DEBUG_TYPE);
- return &SI;
+ OtherVal = FalseSI->getTrueValue();
+ }
+ if (Or && OtherVal) {
+ replaceOperand(SI, 0, Or);
+ replaceOperand(SI, 2, OtherVal);
+ if (!ProfcheckDisableMetadataFixes)
+ setExplicitlyUnknownBranchWeightsIfProfiled(SI, DEBUG_TYPE);
+ return &SI;
+ }
}
}
}
- }
- if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
- if (FalseSI->getCondition()->getType() == CondVal->getType()) {
- // Fold nested selects if the inner condition can be implied by the outer
- // condition.
- if (Value *V = simplifyNestedSelectsUsingImpliedCond(
- *FalseSI, CondVal, /*CondIsTrue=*/false, DL))
- return replaceOperand(SI, 2, V);
-
- if (FalseSI->hasOneUse()) {
- Value *Or = nullptr, *OtherVal = nullptr;
- // select(C0, a, select(C1, a, b)) -> select(C0||C1, a, b)
- if (FalseSI->getTrueValue() == TrueVal) {
- Or = Builder.CreateLogicalOr(CondVal, FalseSI->getCondition(), "",
- ProfcheckDisableMetadataFixes ? nullptr
- : &SI);
- OtherVal = FalseSI->getFalseValue();
- }
- // select(C0, a, select(C1, b, a)) -> select(C0||!C1, a, b)
- else if (FalseSI->getFalseValue() == TrueVal) {
- Value *InvertedCond = Builder.CreateNot(FalseSI->getCondition());
- Or = Builder.CreateLogicalOr(CondVal, InvertedCond, "",
- ProfcheckDisableMetadataFixes ? nullptr
- : &SI);
- OtherVal = FalseSI->getTrueValue();
+
+ // Try to simplify a binop sandwiched between 2 selects with the same
+ // condition. This is not valid for div/rem because the select might be
+ // preventing a division-by-zero.
+ // TODO: A div/rem restriction is conservative; use something like
+ // isSafeToSpeculativelyExecute().
+ // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
+ BinaryOperator *TrueBO;
+ if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && !TrueBO->isIntDivRem()) {
+ if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
+ if (TrueBOSI->getCondition() == CondVal) {
+ replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
+ Worklist.push(TrueBO);
+ return &SI;
}
- if (Or && OtherVal) {
- replaceOperand(SI, 0, Or);
- replaceOperand(SI, 2, OtherVal);
- if (!ProfcheckDisableMetadataFixes)
- setExplicitlyUnknownBranchWeightsIfProfiled(SI, DEBUG_TYPE);
+ }
+ if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
+ if (TrueBOSI->getCondition() == CondVal) {
+ replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
+ Worklist.push(TrueBO);
return &SI;
}
}
}
- }
- // Try to simplify a binop sandwiched between 2 selects with the same
- // condition. This is not valid for div/rem because the select might be
- // preventing a division-by-zero.
- // TODO: A div/rem restriction is conservative; use something like
- // isSafeToSpeculativelyExecute().
- // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
- BinaryOperator *TrueBO;
- if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && !TrueBO->isIntDivRem()) {
- if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
- if (TrueBOSI->getCondition() == CondVal) {
- replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
- Worklist.push(TrueBO);
- return &SI;
+ // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
+ BinaryOperator *FalseBO;
+ if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
+ !FalseBO->isIntDivRem()) {
+ if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
+ if (FalseBOSI->getCondition() == CondVal) {
+ replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
+ Worklist.push(FalseBO);
+ return &SI;
+ }
}
- }
- if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
- if (TrueBOSI->getCondition() == CondVal) {
- replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
- Worklist.push(TrueBO);
- return &SI;
+ if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
+ if (FalseBOSI->getCondition() == CondVal) {
+ replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
+ Worklist.push(FalseBO);
+ return &SI;
+ }
}
}
- }
- // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
- BinaryOperator *FalseBO;
- if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && !FalseBO->isIntDivRem()) {
- if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
- if (FalseBOSI->getCondition() == CondVal) {
- replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
- Worklist.push(FalseBO);
- return &SI;
- }
- }
- if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
- if (FalseBOSI->getCondition() == CondVal) {
- replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
- Worklist.push(FalseBO);
- return &SI;
- }
+ Value *NotCond;
+ if (match(CondVal, m_Not(m_Value(NotCond))) &&
+ !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) {
+ replaceOperand(SI, 0, NotCond);
+ SI.swapValues();
+ SI.swapProfMetadata();
+ return &SI;
}
- }
- Value *NotCond;
- if (match(CondVal, m_Not(m_Value(NotCond))) &&
- !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) {
- replaceOperand(SI, 0, NotCond);
- SI.swapValues();
- SI.swapProfMetadata();
- return &SI;
- }
+ if (Instruction *I = foldVectorSelect(SI))
+ return I;
- if (Instruction *I = foldVectorSelect(SI))
- return I;
+ // If we can compute the condition, there's no need for a select.
+ // Like the above fold, we are attempting to reduce compile-time cost by
+ // putting this fold here with limitations rather than in InstSimplify.
+ // The motivation for this call into value tracking is to take advantage of
+ // the assumption cache, so make sure that is populated.
+ if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
+ KnownBits Known(1);
+ computeKnownBits(CondVal, Known, &SI);
+ if (Known.One.isOne())
+ return replaceInstUsesWith(SI, TrueVal);
+ if (Known.Zero.isOne())
+ return replaceInstUsesWith(SI, FalseVal);
+ }
- // If we can compute the condition, there's no need for a select.
- // Like the above fold, we are attempting to reduce compile-time cost by
- // putting this fold here with limitations rather than in InstSimplify.
- // The motivation for this call into value tracking is to take advantage of
- // the assumption cache, so make sure that is populated.
- if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
- KnownBits Known(1);
- computeKnownBits(CondVal, Known, &SI);
- if (Known.One.isOne())
- return replaceInstUsesWith(SI, TrueVal);
- if (Known.Zero.isOne())
- return replaceInstUsesWith(SI, FalseVal);
- }
-
- if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
- return BitCastSel;
-
- // Simplify selects that test the returned flag of cmpxchg instructions.
- if (Value *V = foldSelectCmpXchg(SI))
- return replaceInstUsesWith(SI, V);
+ if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
+ return BitCastSel;
- if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
- return Select;
+ // Simplify selects that test the returned flag of cmpxchg instructions.
+ if (Value *V = foldSelectCmpXchg(SI))
+ return replaceInstUsesWith(SI, V);
- if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder))
- return Funnel;
+ if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
+ return Select;
- if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
- return Copysign;
+ if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder))
+ return Funnel;
- if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
- return replaceInstUsesWith(SI, PN);
+ if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
+ return Copysign;
- if (Value *V = foldRoundUpIntegerWithPow2Alignment(SI, Builder))
- return replaceInstUsesWith(SI, V);
+ if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
+ return replaceInstUsesWith(SI, PN);
- if (Value *V = foldSelectIntoAddConstant(SI, Builder))
- return replaceInstUsesWith(SI, V);
+ if (Value *V = foldRoundUpIntegerWithPow2Alignment(SI, Builder))
+ return replaceInstUsesWith(SI, V);
- // select(mask, mload(ptr,mask,0), 0) -> mload(ptr,mask,0)
- // Load inst is intentionally not checked for hasOneUse()
- if (match(FalseVal, m_Zero()) &&
- (match(TrueVal, m_MaskedLoad(m_Value(), m_Specific(CondVal),
- m_CombineOr(m_Undef(), m_Zero()))) ||
- match(TrueVal, m_MaskedGather(m_Value(), m_Specific(CondVal),
- m_CombineOr(m_Undef(), m_Zero()))))) {
- auto *MaskedInst = cast<IntrinsicInst>(TrueVal);
- if (isa<UndefValue>(MaskedInst->getArgOperand(2)))
- MaskedInst->setArgOperand(2, FalseVal /* Zero */);
- return replaceInstUsesWith(SI, MaskedInst);
- }
+ if (Value *V = foldSelectIntoAddConstant(SI, Builder))
+ return replaceInstUsesWith(SI, V);
- Value *Mask;
- if (match(TrueVal, m_Zero()) &&
- (match(FalseVal, m_MaskedLoad(m_Value(), m_Value(Mask),
- m_CombineOr(m_Undef(), m_Zero()))) ||
- match(FalseVal, m_MaskedGather(m_Value(), m_Value(Mask),
- m_CombineOr(m_Undef(), m_Zero())))) &&
- (CondVal->getType() == Mask->getType())) {
- // We can remove the select by ensuring the load zeros all lanes the
- // select would have. We determine this by proving there is no overlap
- // between the load and select masks.
- // (i.e (load_mask & select_mask) == 0 == no overlap)
- bool CanMergeSelectIntoLoad = false;
- if (Value *V = simplifyAndInst(CondVal, Mask, SQ.getWithInstruction(&SI)))
- CanMergeSelectIntoLoad = match(V, m_Zero());
-
- if (CanMergeSelectIntoLoad) {
- auto *MaskedInst = cast<IntrinsicInst>(FalseVal);
+ // select(mask, mload(ptr,mask,0), 0) -> mload(ptr,mask,0)
+ // Load inst is intentionally not checked for hasOneUse()
+ if (match(FalseVal, m_Zero()) &&
+ (match(TrueVal, m_MaskedLoad(m_Value(), m_Specific(CondVal),
+ m_CombineOr(m_Undef(), m_Zero()))) ||
+ match(TrueVal, m_MaskedGather(m_Value(), m_Specific(CondVal),
+ m_CombineOr(m_Undef(), m_Zero()))))) {
+ auto *MaskedInst = cast<IntrinsicInst>(TrueVal);
if (isa<UndefValue>(MaskedInst->getArgOperand(2)))
- MaskedInst->setArgOperand(2, TrueVal /* Zero */);
+ MaskedInst->setArgOperand(2, FalseVal /* Zero */);
return replaceInstUsesWith(SI, MaskedInst);
}
- }
- if (Instruction *I = foldSelectOfSymmetricSelect(SI, Builder))
- return I;
+ Value *Mask;
+ if (match(TrueVal, m_Zero()) &&
+ (match(FalseVal, m_MaskedLoad(m_Value(), m_Value(Mask),
+ m_CombineOr(m_Undef(), m_Zero()))) ||
+ match(FalseVal, m_MaskedGather(m_Value(), m_Value(Mask),
+ m_CombineOr(m_Undef(), m_Zero())))) &&
+ (CondVal->getType() == Mask->getType())) {
+ // We can remove the select by ensuring the load zeros all lanes the
+ // select would have. We determine this by proving there is no overlap
+ // between the load and select masks.
+ // (i.e (load_mask & select_mask) == 0 == no overlap)
+ bool CanMergeSelectIntoLoad = false;
+ if (Value *V = simplifyAndInst(CondVal, Mask, SQ.getWithInstruction(&SI)))
+ CanMergeSelectIntoLoad = match(V, m_Zero());
+
+ if (CanMergeSelectIntoLoad) {
+ auto *MaskedInst = cast<IntrinsicInst>(FalseVal);
+ if (isa<UndefValue>(MaskedInst->getArgOperand(2)))
+ MaskedInst->setArgOperand(2, TrueVal /* Zero */);
+ return replaceInstUsesWith(SI, MaskedInst);
+ }
+ }
- if (Instruction *I = foldNestedSelects(SI, Builder))
- return I;
+ if (Instruction *I = foldSelectOfSymmetricSelect(SI, Builder))
+ return I;
- // Match logical variants of the pattern,
- // and transform them iff that gets rid of inversions.
- // (~x) | y --> ~(x & (~y))
- // (~x) & y --> ~(x | (~y))
- if (sinkNotIntoOtherHandOfLogicalOp(SI))
- return &SI;
+ if (Instruction *I = foldNestedSelects(SI, Builder))
+ return I;
- if (Instruction *I = foldBitCeil(SI, Builder, *this))
- return I;
+ // Match logical variants of the pattern,
+ // and transform them iff that gets rid of inversions.
+ // (~x) | y --> ~(x & (~y))
+ // (~x) & y --> ~(x | (~y))
+ if (sinkNotIntoOtherHandOfLogicalOp(SI))
+ return &SI;
- if (Instruction *I = foldSelectToCmp(SI))
- return I;
+ if (Instruction *I = foldBitCeil(SI, Builder, *this))
+ return I;
- if (Instruction *I = foldSelectEqualityTest(SI))
- return I;
+ if (Instruction *I = foldSelectToCmp(SI))
+ return I;
- // Fold:
- // (select A && B, T, F) -> (select A, (select B, T, F), F)
- // (select A || B, T, F) -> (select A, T, (select B, T, F))
- // if (select B, T, F) is foldable.
- // TODO: preserve FMF flags
- auto FoldSelectWithAndOrCond = [&](bool IsAnd, Value *A,
- Value *B) -> Instruction * {
- if (Value *V = simplifySelectInst(B, TrueVal, FalseVal, FMF,
- SQ.getWithInstruction(&SI))) {
- Value *NewTrueVal = IsAnd ? V : TrueVal;
- Value *NewFalseVal = IsAnd ? FalseVal : V;
-
- // If the True and False values don't change, then preserve the branch
- // metadata of the original select as the net effect of this change is to
- // simplify the conditional.
- Instruction *MDFrom = nullptr;
- if (NewTrueVal == TrueVal && NewFalseVal == FalseVal &&
- !ProfcheckDisableMetadataFixes) {
- MDFrom = &SI;
- }
- return SelectInst::Create(A, NewTrueVal, NewFalseVal, "", nullptr,
- MDFrom);
- }
+ if (Instruction *I = foldSelectEqualityTest(SI))
+ return I;
- // Is (select B, T, F) a SPF?
- if (CondVal->hasOneUse() && SelType->isIntOrIntVectorTy()) {
- if (ICmpInst *Cmp = dyn_cast<ICmpInst>(B))
- if (Value *V = canonicalizeSPF(*Cmp, TrueVal, FalseVal, *this)) {
- return SelectInst::Create(
- A, IsAnd ? V : TrueVal, IsAnd ? FalseVal : V, "", nullptr,
- ProfcheckDisableMetadataFixes ? nullptr : &SI);
+ // Fold:
+ // (select A && B, T, F) -> (select A, (select B, T, F), F)
+ // (select A || B, T, F) -> (select A, T, (select B, T, F))
+ // if (select B, T, F) is foldable.
+ // TODO: preserve FMF flags
+ auto FoldSelectWithAndOrCond = [&](bool IsAnd, Value *A,
+ Value *B) -> Instruction * {
+ if (Value *V = simplifySelectInst(B, TrueVal, FalseVal, FMF,
+ SQ.getWithInstruction(&SI))) {
+ Value *NewTrueVal = IsAnd ? V : TrueVal;
+ Value *NewFalseVal = IsAnd ? FalseVal : V;
+
+ // If the True and False values don't change, then preserve the branch
+ // metadata of the original select as the net effect of this change is
+ // to simplify the conditional.
+ Instruction *MDFrom = nullptr;
+ if (NewTrueVal == TrueVal && NewFalseVal == FalseVal &&
+ !ProfcheckDisableMetadataFixes) {
+ MDFrom = &SI;
}
- }
+ return SelectInst::Create(A, NewTrueVal, NewFalseVal, "", nullptr,
+ MDFrom);
+ }
- return nullptr;
- };
+ // Is (select B, T, F) a SPF?
+ if (CondVal->hasOneUse() && SelType->isIntOrIntVectorTy()) {
+ if (ICmpInst *Cmp = dyn_cast<ICmpInst>(B))
+ if (Value *V = canonicalizeSPF(*Cmp, TrueVal, FalseVal, *this)) {
+ return SelectInst::Create(
+ A, IsAnd ? V : TrueVal, IsAnd ? FalseVal : V, "", nullptr,
+ ProfcheckDisableMetadataFixes ? nullptr : &SI);
+ }
+ }
- Value *LHS, *RHS;
- if (match(CondVal, m_And(m_Value(LHS), m_Value(RHS)))) {
- if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, LHS, RHS))
- return I;
- if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, RHS, LHS))
- return I;
- } else if (match(CondVal, m_Or(m_Value(LHS), m_Value(RHS)))) {
- if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, LHS, RHS))
- return I;
- if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, RHS, LHS))
- return I;
- } else {
- // We cannot swap the operands of logical and/or.
- // TODO: Can we swap the operands by inserting a freeze?
- if (match(CondVal, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
+ return nullptr;
+ };
+
+ Value *LHS, *RHS;
+ if (match(CondVal, m_And(m_Value(LHS), m_Value(RHS)))) {
if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, LHS, RHS))
return I;
- } else if (match(CondVal, m_LogicalOr(m_Value(LHS), m_Value(RHS)))) {
+ if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, RHS, LHS))
+ return I;
+ } else if (match(CondVal, m_Or(m_Value(LHS), m_Value(RHS)))) {
if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, LHS, RHS))
return I;
+ if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, RHS, LHS))
+ return I;
+ } else {
+ // We cannot swap the operands of logical and/or.
+ // TODO: Can we swap the operands by inserting a freeze?
+ if (match(CondVal, m_LogicalAnd(m_Value(LHS), m_Value(RHS)))) {
+ if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, LHS, RHS))
+ return I;
+ } else if (match(CondVal, m_LogicalOr(m_Value(LHS), m_Value(RHS)))) {
+ if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, LHS, RHS))
+ return I;
+ }
}
- }
- // select Cond, !X, X -> xor Cond, X
- if (CondVal->getType() == SI.getType() && isKnownInversion(FalseVal, TrueVal))
- return BinaryOperator::CreateXor(CondVal, FalseVal);
+ // select Cond, !X, X -> xor Cond, X
+ if (CondVal->getType() == SI.getType() &&
+ isKnownInversion(FalseVal, TrueVal))
+ return BinaryOperator::CreateXor(CondVal, FalseVal);
+
+ // For vectors, this transform is only safe if the simplification does not
+ // look through any lane-crossing operations. For now, limit to scalars
+ // only.
+ if (SelType->isIntegerTy() &&
+ (!isa<Constant>(TrueVal) || !isa<Constant>(FalseVal))) {
+ // Try to simplify select arms based on KnownBits implied by the
+ // condition.
+ CondContext CC(CondVal);
+ findValuesAffectedByCondition(CondVal, /*IsAssume=*/false, [&](Value *V) {
+ CC.AffectedValues.insert(V);
+ });
+ SimplifyQuery Q = SQ.getWithInstruction(&SI).getWithCondContext(CC);
+ if (!CC.AffectedValues.empty()) {
+ if (!isa<Constant>(TrueVal) &&
+ hasAffectedValue(TrueVal, CC.AffectedValues, /*Depth=*/0)) {
+ KnownBits Known = llvm::computeKnownBits(TrueVal, Q);
+ if (Known.isConstant())
+ return replaceOperand(
+ SI, 1, ConstantInt::get(SelType, Known.getConstant()));
+ }
- // For vectors, this transform is only safe if the simplification does not
- // look through any lane-crossing operations. For now, limit to scalars only.
- if (SelType->isIntegerTy() &&
- (!isa<Constant>(TrueVal) || !isa<Constant>(FalseVal))) {
- // Try to simplify select arms based on KnownBits implied by the condition.
- CondContext CC(CondVal);
- findValuesAffectedByCondition(CondVal, /*IsAssume=*/false, [&](Value *V) {
- CC.AffectedValues.insert(V);
- });
- SimplifyQuery Q = SQ.getWithInstruction(&SI).getWithCondContext(CC);
- if (!CC.AffectedValues.empty()) {
- if (!isa<Constant>(TrueVal) &&
- hasAffectedValue(TrueVal, CC.AffectedValues, /*Depth=*/0)) {
- KnownBits Known = llvm::computeKnownBits(TrueVal, Q);
- if (Known.isConstant())
- return replaceOperand(SI, 1,
- ConstantInt::get(SelType, Known.getConstant()));
+ CC.Invert = true;
+ if (!isa<Constant>(FalseVal) &&
+ hasAffectedValue(FalseVal, CC.AffectedValues, /*Depth=*/0)) {
+ KnownBits Known = llvm::computeKnownBits(FalseVal, Q);
+ if (Known.isConstant())
+ return replaceOperand(
+ SI, 2, ConstantInt::get(SelType, Known.getConstant()));
+ }
}
+ }
- CC.Invert = true;
- if (!isa<Constant>(FalseVal) &&
- hasAffectedValue(FalseVal, CC.AffectedValues, /*Depth=*/0)) {
- KnownBits Known = llvm::computeKnownBits(FalseVal, Q);
- if (Known.isConstant())
- return replaceOperand(SI, 2,
- ConstantInt::get(SelType, Known.getConstant()));
- }
+ // select (trunc nuw X to i1), X, Y --> select (trunc nuw X to i1), 1, Y
+ // select (trunc nuw X to i1), Y, X --> select (trunc nuw X to i1), Y, 0
+ // select (trunc nsw X to i1), X, Y --> select (trunc nsw X to i1), -1, Y
+ // select (trunc nsw X to i1), Y, X --> select (trunc nsw X to i1), Y, 0
+ Value *Trunc;
+ if (match(CondVal, m_NUWTrunc(m_Value(Trunc))) && !isa<Constant>(Trunc)) {
+ if (TrueVal == Trunc)
+ return replaceOperand(SI, 1, ConstantInt::get(TrueVal->getType(), 1));
+ if (FalseVal == Trunc)
+ return replaceOperand(SI, 2, ConstantInt::get(FalseVal->getType(), 0));
+ }
+ if (match(CondVal, m_NSWTrunc(m_Value(Trunc))) && !isa<Constant>(Trunc)) {
+ if (TrueVal == Trunc)
+ return replaceOperand(SI, 1,
+ Constant::getAllOnesValue(TrueVal->getType()));
+ if (FalseVal == Trunc)
+ return replaceOperand(SI, 2, ConstantInt::get(FalseVal->getType(), 0));
}
- }
- // select (trunc nuw X to i1), X, Y --> select (trunc nuw X to i1), 1, Y
- // select (trunc nuw X to i1), Y, X --> select (trunc nuw X to i1), Y, 0
- // select (trunc nsw X to i1), X, Y --> select (trunc nsw X to i1), -1, Y
- // select (trunc nsw X to i1), Y, X --> select (trunc nsw X to i1), Y, 0
- Value *Trunc;
- if (match(CondVal, m_NUWTrunc(m_Value(Trunc))) && !isa<Constant>(Trunc)) {
- if (TrueVal == Trunc)
- return replaceOperand(SI, 1, ConstantInt::get(TrueVal->getType(), 1));
- if (FalseVal == Trunc)
- return replaceOperand(SI, 2, ConstantInt::get(FalseVal->getType(), 0));
- }
- if (match(CondVal, m_NSWTrunc(m_Value(Trunc))) && !isa<Constant>(Trunc)) {
- if (TrueVal == Trunc)
- return replaceOperand(SI, 1,
- Constant::getAllOnesValue(TrueVal->getType()));
- if (FalseVal == Trunc)
- return replaceOperand(SI, 2, ConstantInt::get(FalseVal->getType(), 0));
- }
-
- Value *MaskedLoadPtr;
- if (match(TrueVal, m_OneUse(m_MaskedLoad(m_Value(MaskedLoadPtr),
- m_Specific(CondVal), m_Value()))))
- return replaceInstUsesWith(
- SI, Builder.CreateMaskedLoad(
- TrueVal->getType(), MaskedLoadPtr,
- cast<IntrinsicInst>(TrueVal)->getParamAlign(0).valueOrOne(),
- CondVal, FalseVal));
-
- // Canonicalize sign function ashr pattern: select (icmp slt X, 1), ashr X,
- // bitwidth-1, 1 -> scmp(X, 0)
- // Also handles: select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
- unsigned BitWidth = SI.getType()->getScalarSizeInBits();
- CmpPredicate Pred;
- Value *CmpLHS, *CmpRHS;
+ Value *MaskedLoadPtr;
+ if (match(TrueVal, m_OneUse(m_MaskedLoad(m_Value(MaskedLoadPtr),
+ m_Specific(CondVal), m_Value()))))
+ return replaceInstUsesWith(
+ SI, Builder.CreateMaskedLoad(
+ TrueVal->getType(), MaskedLoadPtr,
+ cast<IntrinsicInst>(TrueVal)->getParamAlign(0).valueOrOne(),
+ CondVal, FalseVal));
+
+ // Canonicalize sign function ashr pattern: select (icmp slt X, 1), ashr X,
+ // bitwidth-1, 1 -> scmp(X, 0)
+ // Also handles: select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
+ unsigned BitWidth = SI.getType()->getScalarSizeInBits();
+ CmpPredicate Pred;
+ Value *CmpLHS, *CmpRHS;
+
+ // Canonicalize sign function ashr patterns:
+ // select (icmp slt X, 1), ashr X, bitwidth-1, 1 -> scmp(X, 0)
+ // select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
+ if (match(&SI, m_Select(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
+ m_Value(TrueVal), m_Value(FalseVal))) &&
+ ((Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_One()) &&
+ match(TrueVal,
+ m_AShr(m_Specific(CmpLHS), m_SpecificInt(BitWidth - 1))) &&
+ match(FalseVal, m_One())) ||
+ (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_Zero()) &&
+ match(TrueVal, m_One()) &&
+ match(FalseVal,
+ m_AShr(m_Specific(CmpLHS), m_SpecificInt(BitWidth - 1)))))) {
+
+ Function *Scmp = Intrinsic::getOrInsertDeclaration(
+ SI.getModule(), Intrinsic::scmp, {SI.getType(), SI.getType()});
+ return CallInst::Create(Scmp,
+ {CmpLHS, ConstantInt::get(SI.getType(), 0)});
+ }
- // Canonicalize sign function ashr patterns:
- // select (icmp slt X, 1), ashr X, bitwidth-1, 1 -> scmp(X, 0)
- // select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
- if (match(&SI, m_Select(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
- m_Value(TrueVal), m_Value(FalseVal))) &&
- ((Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_One()) &&
- match(TrueVal,
- m_AShr(m_Specific(CmpLHS), m_SpecificInt(BitWidth - 1))) &&
- match(FalseVal, m_One())) ||
- (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_Zero()) &&
- match(TrueVal, m_One()) &&
- match(FalseVal,
- m_AShr(m_Specific(CmpLHS), m_SpecificInt(BitWidth - 1)))))) {
-
- Function *Scmp = Intrinsic::getOrInsertDeclaration(
- SI.getModule(), Intrinsic::scmp, {SI.getType(), SI.getType()});
- return CallInst::Create(Scmp, {CmpLHS, ConstantInt::get(SI.getType(), 0)});
+ return nullptr;
}
-
- return nullptr;
-}
``````````
</details>
https://github.com/llvm/llvm-project/pull/201453
More information about the llvm-commits
mailing list