1 //===- InstCombineSelect.cpp ----------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the visitSelect function.
11 //===----------------------------------------------------------------------===//
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CmpInstAnalysis.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
45 using namespace PatternMatch;
47 #define DEBUG_TYPE "instcombine"
49 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
50 SelectPatternFlavor SPF, Value *A, Value *B) {
51 CmpInst::Predicate Pred = getMinMaxPred(SPF);
52 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
53 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
56 /// Replace a select operand based on an equality comparison with the identity
57 /// constant of a binop.
58 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
59 const TargetLibraryInfo &TLI,
61 // The select condition must be an equality compare with a constant operand.
64 CmpInst::Predicate Pred;
65 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
69 if (ICmpInst::isEquality(Pred))
70 IsEq = Pred == ICmpInst::ICMP_EQ;
71 else if (Pred == FCmpInst::FCMP_OEQ)
73 else if (Pred == FCmpInst::FCMP_UNE)
78 // A select operand must be a binop.
80 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
83 // The compare constant must be the identity constant for that binop.
84 // If this a floating-point compare with 0.0, any zero constant will do.
85 Type *Ty = BO->getType();
86 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
88 if (!IdC || !CmpInst::isFPPredicate(Pred))
90 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
94 // Last, match the compare variable operand with a binop operand.
96 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
98 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
101 // +0.0 compares equal to -0.0, and so it does not behave as required for this
102 // transform. Bail out if we can not exclude that possibility.
103 if (isa<FPMathOperator>(BO))
104 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
108 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
110 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
111 return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
115 /// select (icmp eq (and X, C1)), TC, FC
116 /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
117 /// To something like:
118 /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
120 /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
121 /// With some variations depending if FC is larger than TC, or the shift
122 /// isn't needed, or the bit widths don't match.
123 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
124 InstCombiner::BuilderTy &Builder) {
125 const APInt *SelTC, *SelFC;
126 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
127 !match(Sel.getFalseValue(), m_APInt(SelFC)))
130 // If this is a vector select, we need a vector compare.
131 Type *SelType = Sel.getType();
132 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
137 bool CreateAnd = false;
138 ICmpInst::Predicate Pred = Cmp->getPredicate();
139 if (ICmpInst::isEquality(Pred)) {
140 if (!match(Cmp->getOperand(1), m_Zero()))
143 V = Cmp->getOperand(0);
145 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
149 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
151 assert(ICmpInst::isEquality(Pred) && "Not equality test?");
152 if (!AndMask.isPowerOf2())
160 // In general, when both constants are non-zero, we would need an offset to
161 // replace the select. This would require more instructions than we started
162 // with. But there's one special-case that we handle here because it can
163 // simplify/reduce the instructions.
166 if (!TC.isNullValue() && !FC.isNullValue()) {
167 // If the select constants differ by exactly one bit and that's the same
168 // bit that is masked and checked by the select condition, the select can
169 // be replaced by bitwise logic to set/clear one bit of the constant result.
170 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
173 // If we have to create an 'and', then we must kill the cmp to not
174 // increase the instruction count.
175 if (!Cmp->hasOneUse())
177 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
179 bool ExtraBitInTC = TC.ugt(FC);
180 if (Pred == ICmpInst::ICMP_EQ) {
181 // If the masked bit in V is clear, clear or set the bit in the result:
182 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
183 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
184 Constant *C = ConstantInt::get(SelType, TC);
185 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
187 if (Pred == ICmpInst::ICMP_NE) {
188 // If the masked bit in V is set, set or clear the bit in the result:
189 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
190 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
191 Constant *C = ConstantInt::get(SelType, FC);
192 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
194 llvm_unreachable("Only expecting equality predicates");
197 // Make sure one of the select arms is a power-of-2.
198 if (!TC.isPowerOf2() && !FC.isPowerOf2())
201 // Determine which shift is needed to transform result of the 'and' into the
203 const APInt &ValC = !TC.isNullValue() ? TC : FC;
204 unsigned ValZeros = ValC.logBase2();
205 unsigned AndZeros = AndMask.logBase2();
207 // Insert the 'and' instruction on the input to the truncate.
209 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
211 // If types don't match, we can still convert the select by introducing a zext
212 // or a trunc of the 'and'.
213 if (ValZeros > AndZeros) {
214 V = Builder.CreateZExtOrTrunc(V, SelType);
215 V = Builder.CreateShl(V, ValZeros - AndZeros);
216 } else if (ValZeros < AndZeros) {
217 V = Builder.CreateLShr(V, AndZeros - ValZeros);
218 V = Builder.CreateZExtOrTrunc(V, SelType);
220 V = Builder.CreateZExtOrTrunc(V, SelType);
223 // Okay, now we know that everything is set up, we just don't know whether we
224 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
225 bool ShouldNotVal = !TC.isNullValue();
226 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
228 V = Builder.CreateXor(V, ValC);
233 /// We want to turn code that looks like this:
235 /// %D = select %cond, %C, %A
237 /// %C = select %cond, %B, 0
240 /// Assuming that the specified instruction is an operand to the select, return
241 /// a bitmask indicating which operands of this instruction are foldable if they
242 /// equal the other incoming value of the select.
243 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
244 switch (I->getOpcode()) {
245 case Instruction::Add:
246 case Instruction::Mul:
247 case Instruction::And:
248 case Instruction::Or:
249 case Instruction::Xor:
250 return 3; // Can fold through either operand.
251 case Instruction::Sub: // Can only fold on the amount subtracted.
252 case Instruction::Shl: // Can only fold on the shift amount.
253 case Instruction::LShr:
254 case Instruction::AShr:
257 return 0; // Cannot fold
261 /// For the same transformation as the previous function, return the identity
262 /// constant that goes into the select.
263 static APInt getSelectFoldableConstant(BinaryOperator *I) {
264 switch (I->getOpcode()) {
265 default: llvm_unreachable("This cannot happen!");
266 case Instruction::Add:
267 case Instruction::Sub:
268 case Instruction::Or:
269 case Instruction::Xor:
270 case Instruction::Shl:
271 case Instruction::LShr:
272 case Instruction::AShr:
273 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
274 case Instruction::And:
275 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
276 case Instruction::Mul:
277 return APInt(I->getType()->getScalarSizeInBits(), 1);
281 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
282 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
284 // Don't break up min/max patterns. The hasOneUse checks below prevent that
285 // for most cases, but vector min/max with bitcasts can be transformed. If the
286 // one-use restrictions are eased for other patterns, we still don't want to
287 // obfuscate min/max.
288 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
289 match(&SI, m_SMax(m_Value(), m_Value())) ||
290 match(&SI, m_UMin(m_Value(), m_Value())) ||
291 match(&SI, m_UMax(m_Value(), m_Value()))))
294 // If this is a cast from the same type, merge.
295 Value *Cond = SI.getCondition();
296 Type *CondTy = Cond->getType();
297 if (TI->getNumOperands() == 1 && TI->isCast()) {
298 Type *FIOpndTy = FI->getOperand(0)->getType();
299 if (TI->getOperand(0)->getType() != FIOpndTy)
302 // The select condition may be a vector. We may only change the operand
303 // type if the vector width remains the same (and matches the condition).
304 if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
305 if (!FIOpndTy->isVectorTy())
307 if (CondVTy->getNumElements() !=
308 cast<VectorType>(FIOpndTy)->getNumElements())
311 // TODO: If the backend knew how to deal with casts better, we could
312 // remove this limitation. For now, there's too much potential to create
313 // worse codegen by promoting the select ahead of size-altering casts
316 // Note that ValueTracking's matchSelectPattern() looks through casts
317 // without checking 'hasOneUse' when it matches min/max patterns, so this
318 // transform may end up happening anyway.
319 if (TI->getOpcode() != Instruction::BitCast &&
320 (!TI->hasOneUse() || !FI->hasOneUse()))
322 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
323 // TODO: The one-use restrictions for a scalar select could be eased if
324 // the fold of a select in visitLoadInst() was enhanced to match a pattern
325 // that includes a cast.
329 // Fold this by inserting a select from the input values.
331 Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
332 SI.getName() + ".v", &SI);
333 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
337 // Cond ? -X : -Y --> -(Cond ? X : Y)
339 if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
340 (TI->hasOneUse() || FI->hasOneUse())) {
341 Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
342 return UnaryOperator::CreateFNegFMF(NewSel, TI);
345 // Only handle binary operators (including two-operand getelementptr) with
346 // one-use here. As with the cast case above, it may be possible to relax the
347 // one-use constraint, but that needs be examined carefully since it may not
348 // reduce the total number of instructions.
349 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
350 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
351 !TI->hasOneUse() || !FI->hasOneUse())
354 // Figure out if the operations have any operands in common.
355 Value *MatchOp, *OtherOpT, *OtherOpF;
357 if (TI->getOperand(0) == FI->getOperand(0)) {
358 MatchOp = TI->getOperand(0);
359 OtherOpT = TI->getOperand(1);
360 OtherOpF = FI->getOperand(1);
361 MatchIsOpZero = true;
362 } else if (TI->getOperand(1) == FI->getOperand(1)) {
363 MatchOp = TI->getOperand(1);
364 OtherOpT = TI->getOperand(0);
365 OtherOpF = FI->getOperand(0);
366 MatchIsOpZero = false;
367 } else if (!TI->isCommutative()) {
369 } else if (TI->getOperand(0) == FI->getOperand(1)) {
370 MatchOp = TI->getOperand(0);
371 OtherOpT = TI->getOperand(1);
372 OtherOpF = FI->getOperand(0);
373 MatchIsOpZero = true;
374 } else if (TI->getOperand(1) == FI->getOperand(0)) {
375 MatchOp = TI->getOperand(1);
376 OtherOpT = TI->getOperand(0);
377 OtherOpF = FI->getOperand(1);
378 MatchIsOpZero = true;
383 // If the select condition is a vector, the operands of the original select's
384 // operands also must be vectors. This may not be the case for getelementptr
386 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
387 !OtherOpF->getType()->isVectorTy()))
390 // If we reach here, they do have operations in common.
391 Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
392 SI.getName() + ".v", &SI);
393 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
394 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
395 if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
396 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
397 NewBO->copyIRFlags(TI);
398 NewBO->andIRFlags(FI);
401 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
402 auto *FGEP = cast<GetElementPtrInst>(FI);
403 Type *ElementType = TGEP->getResultElementType();
404 return TGEP->isInBounds() && FGEP->isInBounds()
405 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
406 : GetElementPtrInst::Create(ElementType, Op0, {Op1});
408 llvm_unreachable("Expected BinaryOperator or GEP");
412 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
413 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
415 return C1I.isOneValue() || C1I.isAllOnesValue() ||
416 C2I.isOneValue() || C2I.isAllOnesValue();
419 /// Try to fold the select into one of the operands to allow further
421 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
423 // See the comment above GetSelectFoldableOperands for a description of the
424 // transformation we are doing here.
425 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
426 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
427 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
428 unsigned OpToFold = 0;
429 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
431 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
436 APInt CI = getSelectFoldableConstant(TVI);
437 Value *OOp = TVI->getOperand(2-OpToFold);
438 // Avoid creating select between 2 constants unless it's selecting
439 // between 0, 1 and -1.
441 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
442 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
443 Value *C = ConstantInt::get(OOp->getType(), CI);
444 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
445 NewSel->takeName(TVI);
446 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
448 BO->copyIRFlags(TVI);
456 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
457 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
458 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
459 unsigned OpToFold = 0;
460 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
462 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
467 APInt CI = getSelectFoldableConstant(FVI);
468 Value *OOp = FVI->getOperand(2-OpToFold);
469 // Avoid creating select between 2 constants unless it's selecting
470 // between 0, 1 and -1.
472 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
473 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
474 Value *C = ConstantInt::get(OOp->getType(), CI);
475 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
476 NewSel->takeName(FVI);
477 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
479 BO->copyIRFlags(FVI);
491 /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
493 /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
495 /// Z may be 0 if lshr is missing.
496 /// Worst-case scenario is that we will replace 5 instructions with 5 different
497 /// instructions, but we got rid of select.
498 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
499 Value *TVal, Value *FVal,
500 InstCombiner::BuilderTy &Builder) {
501 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
502 Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
503 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
506 // The TrueVal has general form of: and %B, 1
508 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
511 // Where %B may be optionally shifted: lshr %X, %Z.
513 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
518 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
521 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
522 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
523 Constant *One = ConstantInt::get(SelType, 1);
524 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
525 Value *FullMask = Builder.CreateOr(Y, MaskB);
526 Value *MaskedX = Builder.CreateAnd(X, FullMask);
527 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
528 return new ZExtInst(ICmpNeZero, SelType);
532 /// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
533 /// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
536 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
538 InstCombiner::BuilderTy &Builder) {
539 ICmpInst::Predicate Pred = IC->getPredicate();
540 Value *CmpLHS = IC->getOperand(0);
541 Value *CmpRHS = IC->getOperand(1);
542 if (!CmpRHS->getType()->isIntOrIntVectorTy())
546 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
547 if ((Pred != ICmpInst::ICMP_SGT ||
549 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
550 (Pred != ICmpInst::ICMP_SLT ||
552 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
555 // Canonicalize so that ashr is in FalseVal.
556 if (Pred == ICmpInst::ICMP_SLT)
557 std::swap(TrueVal, FalseVal);
559 if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
560 match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
561 match(CmpLHS, m_Specific(X))) {
562 const auto *Ashr = cast<Instruction>(FalseVal);
563 // if lshr is not exact and ashr is, this new ashr must not be exact.
564 bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
565 return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
572 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
574 /// (or (shl (and X, C1), C3), Y)
576 /// C1 and C2 are both powers of 2
578 /// C3 = Log(C2) - Log(C1)
580 /// This transform handles cases where:
581 /// 1. The icmp predicate is inverted
582 /// 2. The select operands are reversed
583 /// 3. The magnitude of C2 and C1 are flipped
584 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
586 InstCombiner::BuilderTy &Builder) {
587 // Only handle integer compares. Also, if this is a vector select, we need a
589 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
590 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
593 Value *CmpLHS = IC->getOperand(0);
594 Value *CmpRHS = IC->getOperand(1);
599 bool NeedAnd = false;
600 if (IC->isEquality()) {
601 if (!match(CmpRHS, m_Zero()))
605 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
609 C1Log = C1->logBase2();
610 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
611 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
612 IC->getPredicate() == ICmpInst::ICMP_SGT) {
613 // We also need to recognize (icmp slt (trunc (X)), 0) and
614 // (icmp sgt (trunc (X)), -1).
615 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
616 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
617 (!IsEqualZero && !match(CmpRHS, m_Zero())))
620 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
623 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
630 bool OrOnTrueVal = false;
631 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
633 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
635 if (!OrOnFalseVal && !OrOnTrueVal)
638 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
640 unsigned C2Log = C2->logBase2();
642 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
643 bool NeedShift = C1Log != C2Log;
644 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
645 V->getType()->getScalarSizeInBits();
647 // Make sure we don't create more instructions than we save.
648 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
649 if ((NeedShift + NeedXor + NeedZExtTrunc) >
650 (IC->hasOneUse() + Or->hasOneUse()))
654 // Insert the AND instruction on the input to the truncate.
655 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
656 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
660 V = Builder.CreateZExtOrTrunc(V, Y->getType());
661 V = Builder.CreateShl(V, C2Log - C1Log);
662 } else if (C1Log > C2Log) {
663 V = Builder.CreateLShr(V, C1Log - C2Log);
664 V = Builder.CreateZExtOrTrunc(V, Y->getType());
666 V = Builder.CreateZExtOrTrunc(V, Y->getType());
669 V = Builder.CreateXor(V, *C2);
671 return Builder.CreateOr(V, Y);
674 /// Canonicalize a set or clear of a masked set of constant bits to
675 /// select-of-constants form.
676 static Instruction *foldSetClearBits(SelectInst &Sel,
677 InstCombiner::BuilderTy &Builder) {
678 Value *Cond = Sel.getCondition();
679 Value *T = Sel.getTrueValue();
680 Value *F = Sel.getFalseValue();
681 Type *Ty = Sel.getType();
683 const APInt *NotC, *C;
685 // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
686 if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
687 match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
688 Constant *Zero = ConstantInt::getNullValue(Ty);
689 Constant *OrC = ConstantInt::get(Ty, *C);
690 Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
691 return BinaryOperator::CreateOr(T, NewSel);
694 // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
695 if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
696 match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
697 Constant *Zero = ConstantInt::getNullValue(Ty);
698 Constant *OrC = ConstantInt::get(Ty, *C);
699 Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
700 return BinaryOperator::CreateOr(F, NewSel);
706 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
707 /// There are 8 commuted/swapped variants of this pattern.
708 /// TODO: Also support a - UMIN(a,b) patterns.
709 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
710 const Value *TrueVal,
711 const Value *FalseVal,
712 InstCombiner::BuilderTy &Builder) {
713 ICmpInst::Predicate Pred = ICI->getPredicate();
714 if (!ICmpInst::isUnsigned(Pred))
717 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
718 if (match(TrueVal, m_Zero())) {
719 Pred = ICmpInst::getInversePredicate(Pred);
720 std::swap(TrueVal, FalseVal);
722 if (!match(FalseVal, m_Zero()))
725 Value *A = ICI->getOperand(0);
726 Value *B = ICI->getOperand(1);
727 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
728 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
730 Pred = ICmpInst::getSwappedPredicate(Pred);
733 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
734 "Unexpected isUnsigned predicate!");
736 // Ensure the sub is of the form:
737 // (a > b) ? a - b : 0 -> usub.sat(a, b)
738 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
739 // Checking for both a-b and a+(-b) as a constant.
740 bool IsNegative = false;
742 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
743 (match(A, m_APInt(C)) &&
744 match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
746 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
747 !(match(B, m_APInt(C)) &&
748 match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
751 // If we are adding a negate and the sub and icmp are used anywhere else, we
752 // would end up with more instructions.
753 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
756 // (a > b) ? a - b : 0 -> usub.sat(a, b)
757 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
758 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
760 Result = Builder.CreateNeg(Result);
764 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
765 InstCombiner::BuilderTy &Builder) {
766 if (!Cmp->hasOneUse())
769 // Match unsigned saturated add with constant.
770 Value *Cmp0 = Cmp->getOperand(0);
771 Value *Cmp1 = Cmp->getOperand(1);
772 ICmpInst::Predicate Pred = Cmp->getPredicate();
774 const APInt *C, *CmpC;
775 if (Pred == ICmpInst::ICMP_ULT &&
776 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
777 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
778 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
779 return Builder.CreateBinaryIntrinsic(
780 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
783 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
784 // There are 8 commuted variants.
785 // Canonicalize -1 (saturated result) to true value of the select. Just
786 // swapping the compare operands is legal, because the selected value is the
787 // same in case of equality, so we can interchange u< and u<=.
788 if (match(FVal, m_AllOnes())) {
789 std::swap(TVal, FVal);
790 std::swap(Cmp0, Cmp1);
792 if (!match(TVal, m_AllOnes()))
795 // Canonicalize predicate to 'ULT'.
796 if (Pred == ICmpInst::ICMP_UGT) {
797 Pred = ICmpInst::ICMP_ULT;
798 std::swap(Cmp0, Cmp1);
800 if (Pred != ICmpInst::ICMP_ULT)
803 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
805 if (match(Cmp0, m_Not(m_Value(X))) &&
806 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
807 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
808 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
809 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
811 // The 'not' op may be included in the sum but not the compare.
814 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
815 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
816 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
817 BinaryOperator *BO = cast<BinaryOperator>(FVal);
818 return Builder.CreateBinaryIntrinsic(
819 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
821 // The overflow may be detected via the add wrapping round.
822 if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
823 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
824 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
825 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
826 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
832 /// Fold the following code sequence:
834 /// int a = ctlz(x & -x);
840 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
842 InstCombiner::BuilderTy &Builder) {
843 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
844 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
847 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
848 std::swap(TrueVal, FalseVal);
851 m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
854 if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
857 Value *X = ICI->getOperand(0);
858 auto *II = cast<IntrinsicInst>(TrueVal);
859 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
862 Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
864 return CallInst::Create(F, {X, II->getArgOperand(1)});
867 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
868 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
870 /// For example, we can fold the following code sequence:
872 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
873 /// %1 = icmp ne i32 %x, 0
874 /// %2 = select i1 %1, i32 %0, i32 32
878 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
879 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
880 InstCombiner::BuilderTy &Builder) {
881 ICmpInst::Predicate Pred = ICI->getPredicate();
882 Value *CmpLHS = ICI->getOperand(0);
883 Value *CmpRHS = ICI->getOperand(1);
885 // Check if the condition value compares a value for equality against zero.
886 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
889 Value *SelectArg = FalseVal;
890 Value *ValueOnZero = TrueVal;
891 if (Pred == ICmpInst::ICMP_NE)
892 std::swap(SelectArg, ValueOnZero);
894 // Skip zero extend/truncate.
895 Value *Count = nullptr;
896 if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
897 !match(SelectArg, m_Trunc(m_Value(Count))))
900 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
901 // input to the cttz/ctlz is used as LHS for the compare instruction.
902 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
903 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
906 IntrinsicInst *II = cast<IntrinsicInst>(Count);
908 // Check if the value propagated on zero is a constant number equal to the
909 // sizeof in bits of 'Count'.
910 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
911 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
912 // Explicitly clear the 'undef_on_zero' flag. It's always valid to go from
913 // true to false on this flag, so we can replace it for all users.
914 II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
918 // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
919 // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
920 // not be used if the input is zero. Relax to 'undef_on_zero' for that case.
921 if (II->hasOneUse() && SelectArg->hasOneUse() &&
922 !match(II->getArgOperand(1), m_One()))
923 II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
928 /// Return true if we find and adjust an icmp+select pattern where the compare
929 /// is with a constant that can be incremented or decremented to match the
930 /// minimum or maximum idiom.
931 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
932 ICmpInst::Predicate Pred = Cmp.getPredicate();
933 Value *CmpLHS = Cmp.getOperand(0);
934 Value *CmpRHS = Cmp.getOperand(1);
935 Value *TrueVal = Sel.getTrueValue();
936 Value *FalseVal = Sel.getFalseValue();
938 // We may move or edit the compare, so make sure the select is the only user.
940 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
943 // These transforms only work for selects of integers or vector selects of
945 Type *SelTy = Sel.getType();
946 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
947 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
950 Constant *AdjustedRHS;
951 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
952 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
953 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
954 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
958 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
959 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
960 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
961 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
962 ; // Nothing to do here. Values match without any sign/zero extension.
964 // Types do not match. Instead of calculating this with mixed types, promote
965 // all to the larger type. This enables scalar evolution to analyze this
967 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
968 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
970 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
971 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
972 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
973 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
974 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
976 AdjustedRHS = SextRHS;
977 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
978 SextRHS == TrueVal) {
980 AdjustedRHS = SextRHS;
981 } else if (Cmp.isUnsigned()) {
982 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
983 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
984 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
985 // zext + signed compare cannot be changed:
986 // 0xff <s 0x00, but 0x00ff >s 0x0000
987 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
989 AdjustedRHS = ZextRHS;
990 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
991 ZextRHS == TrueVal) {
993 AdjustedRHS = ZextRHS;
1004 Pred = ICmpInst::getSwappedPredicate(Pred);
1005 CmpRHS = AdjustedRHS;
1006 std::swap(FalseVal, TrueVal);
1007 Cmp.setPredicate(Pred);
1008 Cmp.setOperand(0, CmpLHS);
1009 Cmp.setOperand(1, CmpRHS);
1010 Sel.setOperand(1, TrueVal);
1011 Sel.setOperand(2, FalseVal);
1012 Sel.swapProfMetadata();
1014 // Move the compare instruction right before the select instruction. Otherwise
1015 // the sext/zext value may be defined after the compare instruction uses it.
1016 Cmp.moveBefore(&Sel);
1021 /// If this is an integer min/max (icmp + select) with a constant operand,
1022 /// create the canonical icmp for the min/max operation and canonicalize the
1023 /// constant to the 'false' operand of the select:
1024 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
1025 /// Note: if C1 != C2, this will change the icmp constant to the existing
1026 /// constant operand of the select.
1027 static Instruction *
1028 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
1030 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1033 // Canonicalize the compare predicate based on whether we have min or max.
1035 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
1036 if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1039 // Is this already canonical?
1040 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1041 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1042 Cmp.getPredicate() == CanonicalPred)
1045 // Bail out on unsimplified X-0 operand (due to some worklist management bug),
1046 // as this may cause an infinite combine loop. Let the sub be folded first.
1047 if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1048 match(RHS, m_Sub(m_Value(), m_Zero())))
1051 // Create the canonical compare and plug it into the select.
1052 IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS));
1054 // If the select operands did not change, we're done.
1055 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1058 // If we are swapping the select operands, swap the metadata too.
1059 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
1060 "Unexpected results from matchSelectPattern");
1062 Sel.swapProfMetadata();
1066 /// There are many select variants for each of ABS/NABS.
1067 /// In matchSelectPattern(), there are different compare constants, compare
1068 /// predicates/operands and select operands.
1069 /// In isKnownNegation(), there are different formats of negated operands.
1070 /// Canonicalize all these variants to 1 pattern.
1071 /// This makes CSE more likely.
1072 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1074 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1077 // Choose a sign-bit check for the compare (likely simpler for codegen).
1078 // ABS: (X <s 0) ? -X : X
1079 // NABS: (X <s 0) ? X : -X
1081 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1082 if (SPF != SelectPatternFlavor::SPF_ABS &&
1083 SPF != SelectPatternFlavor::SPF_NABS)
1086 Value *TVal = Sel.getTrueValue();
1087 Value *FVal = Sel.getFalseValue();
1088 assert(isKnownNegation(TVal, FVal) &&
1089 "Unexpected result from matchSelectPattern");
1091 // The compare may use the negated abs()/nabs() operand, or it may use
1092 // negation in non-canonical form such as: sub A, B.
1093 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
1094 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
1096 bool CmpCanonicalized = !CmpUsesNegatedOp &&
1097 match(Cmp.getOperand(1), m_ZeroInt()) &&
1098 Cmp.getPredicate() == ICmpInst::ICMP_SLT;
1099 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
1101 // Is this already canonical?
1102 if (CmpCanonicalized && RHSCanonicalized)
1105 // If RHS is not canonical but is used by other instructions, don't
1106 // canonicalize it and potentially increase the instruction count.
1107 if (!RHSCanonicalized)
1108 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
1111 // Create the canonical compare: icmp slt LHS 0.
1112 if (!CmpCanonicalized) {
1113 Cmp.setPredicate(ICmpInst::ICMP_SLT);
1114 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
1115 if (CmpUsesNegatedOp)
1116 Cmp.setOperand(0, LHS);
1119 // Create the canonical RHS: RHS = sub (0, LHS).
1120 if (!RHSCanonicalized) {
1121 assert(RHS->hasOneUse() && "RHS use number is not right");
1122 RHS = IC.Builder.CreateNeg(LHS);
1124 // Replace false value.
1125 IC.replaceOperand(Sel, 2, RHS);
1128 // Replace true value.
1129 IC.replaceOperand(Sel, 1, RHS);
1134 // If the select operands do not change, we're done.
1135 if (SPF == SelectPatternFlavor::SPF_NABS) {
1138 assert(FVal == LHS && "Unexpected results from matchSelectPattern");
1142 assert(TVal == LHS && "Unexpected results from matchSelectPattern");
1145 // We are swapping the select operands, so swap the metadata too.
1147 Sel.swapProfMetadata();
1151 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp,
1152 const SimplifyQuery &Q) {
1153 // If this is a binary operator, try to simplify it with the replaced op
1154 // because we know Op and ReplaceOp are equivalant.
1155 // For example: V = X + 1, Op = X, ReplaceOp = 42
1156 // Simplifies as: add(42, 1) --> 43
1157 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
1158 if (BO->getOperand(0) == Op)
1159 return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q);
1160 if (BO->getOperand(1) == Op)
1161 return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q);
1167 /// If we have a select with an equality comparison, then we know the value in
1168 /// one of the arms of the select. See if substituting this value into an arm
1169 /// and simplifying the result yields the same value as the other arm.
1171 /// To make this transform safe, we must drop poison-generating flags
1172 /// (nsw, etc) if we simplified to a binop because the select may be guarding
1173 /// that poison from propagating. If the existing binop already had no
1174 /// poison-generating flags, then this transform can be done by instsimplify.
1177 /// %cmp = icmp eq i32 %x, 2147483647
1178 /// %add = add nsw i32 %x, 1
1179 /// %sel = select i1 %cmp, i32 -2147483648, i32 %add
1181 /// We can't replace %sel with %add unless we strip away the flags.
1182 /// TODO: Wrapping flags could be preserved in some cases with better analysis.
1183 static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp,
1184 const SimplifyQuery &Q) {
1185 if (!Cmp.isEquality())
1188 // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1189 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1190 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1191 std::swap(TrueVal, FalseVal);
1193 // Try each equivalence substitution possibility.
1194 // We have an 'EQ' comparison, so the select's false value will propagate.
1196 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1197 // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43
1198 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1199 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal ||
1200 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal ||
1201 simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal ||
1202 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) {
1203 if (auto *FalseInst = dyn_cast<Instruction>(FalseVal))
1204 FalseInst->dropPoisonGeneratingFlags();
1210 // See if this is a pattern like:
1211 // %old_cmp1 = icmp slt i32 %x, C2
1212 // %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1213 // %old_x_offseted = add i32 %x, C1
1214 // %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1215 // %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1216 // This can be rewritten as more canonical pattern:
1217 // %new_cmp1 = icmp slt i32 %x, -C1
1218 // %new_cmp2 = icmp sge i32 %x, C0-C1
1219 // %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1220 // %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1221 // Iff -C1 s<= C2 s<= C0-C1
1222 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1223 // SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1224 static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1225 InstCombiner::BuilderTy &Builder) {
1226 Value *X = Sel0.getTrueValue();
1227 Value *Sel1 = Sel0.getFalseValue();
1229 // First match the condition of the outermost select.
1230 // Said condition must be one-use.
1231 if (!Cmp0.hasOneUse())
1233 Value *Cmp00 = Cmp0.getOperand(0);
1235 if (!match(Cmp0.getOperand(1),
1236 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1238 // Canonicalize Cmp0 into the form we expect.
1239 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1240 switch (Cmp0.getPredicate()) {
1241 case ICmpInst::Predicate::ICMP_ULT:
1243 case ICmpInst::Predicate::ICMP_ULE:
1244 // We'd have to increment C0 by one, and for that it must not have all-ones
1245 // element, but then it would have been canonicalized to 'ult' before
1246 // we get here. So we can't do anything useful with 'ule'.
1248 case ICmpInst::Predicate::ICMP_UGT:
1249 // We want to canonicalize it to 'ult', so we'll need to increment C0,
1250 // which again means it must not have any all-ones elements.
1252 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1253 APInt::getAllOnesValue(
1254 C0->getType()->getScalarSizeInBits()))))
1255 return nullptr; // Can't do, have all-ones element[s].
1259 case ICmpInst::Predicate::ICMP_UGE:
1260 // The only way we'd get this predicate if this `icmp` has extra uses,
1261 // but then we won't be able to do this fold.
1264 return nullptr; // Unknown predicate.
1267 // Now that we've canonicalized the ICmp, we know the X we expect;
1268 // the select in other hand should be one-use.
1269 if (!Sel1->hasOneUse())
1272 // We now can finish matching the condition of the outermost select:
1273 // it should either be the X itself, or an addition of some constant to X.
1276 C1 = ConstantInt::getNullValue(Sel0.getType());
1277 else if (!match(Cmp00,
1278 m_Add(m_Specific(X),
1279 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1283 ICmpInst::Predicate Pred1;
1285 Value *ReplacementLow, *ReplacementHigh;
1286 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1287 m_Value(ReplacementHigh))) ||
1289 m_ICmp(Pred1, m_Specific(X),
1290 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1293 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1294 return nullptr; // Not enough one-use instructions for the fold.
1295 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1296 // two comparisons we'll need to build.
1298 // Canonicalize Cmp1 into the form we expect.
1299 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1301 case ICmpInst::Predicate::ICMP_SLT:
1303 case ICmpInst::Predicate::ICMP_SLE:
1304 // We'd have to increment C2 by one, and for that it must not have signed
1305 // max element, but then it would have been canonicalized to 'slt' before
1306 // we get here. So we can't do anything useful with 'sle'.
1308 case ICmpInst::Predicate::ICMP_SGT:
1309 // We want to canonicalize it to 'slt', so we'll need to increment C2,
1310 // which again means it must not have any signed max elements.
1312 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1313 APInt::getSignedMaxValue(
1314 C2->getType()->getScalarSizeInBits()))))
1315 return nullptr; // Can't do, have signed max element[s].
1318 case ICmpInst::Predicate::ICMP_SGE:
1319 // Also non-canonical, but here we don't need to change C2,
1320 // so we don't have any restrictions on C2, so we can just handle it.
1321 std::swap(ReplacementLow, ReplacementHigh);
1324 return nullptr; // Unknown predicate.
1327 // The thresholds of this clamp-like pattern.
1328 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1329 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1331 // The fold has a precondition 1: C2 s>= ThresholdLow
1332 auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1334 if (!match(Precond1, m_One()))
1336 // The fold has a precondition 2: C2 s<= ThresholdHigh
1337 auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1339 if (!match(Precond2, m_One()))
1342 // All good, finally emit the new pattern.
1343 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1344 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1345 Value *MaybeReplacedLow =
1346 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1347 Instruction *MaybeReplacedHigh =
1348 SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1350 return MaybeReplacedHigh;
1354 // %cmp = icmp [canonical predicate] i32 %x, C0
1355 // %r = select i1 %cmp, i32 %y, i32 C1
1356 // Where C0 != C1 and %x may be different from %y, see if the constant that we
1357 // will have if we flip the strictness of the predicate (i.e. without changing
1358 // the result) is identical to the C1 in select. If it matches we can change
1359 // original comparison to one with swapped predicate, reuse the constant,
1360 // and swap the hands of select.
1361 static Instruction *
1362 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1364 ICmpInst::Predicate Pred;
1367 if (!match(&Cmp, m_OneUse(m_ICmp(
1369 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1372 // If comparison predicate is non-relational, we won't be able to do anything.
1373 if (ICmpInst::isEquality(Pred))
1376 // If comparison predicate is non-canonical, then we certainly won't be able
1377 // to make it canonical; canonicalizeCmpWithConstant() already tried.
1378 if (!isCanonicalPredicate(Pred))
1381 // If the [input] type of comparison and select type are different, lets abort
1382 // for now. We could try to compare constants with trunc/[zs]ext though.
1383 if (C0->getType() != Sel.getType())
1386 // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1388 Value *SelVal0, *SelVal1; // We do not care which one is from where.
1389 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1390 // At least one of these values we are selecting between must be a constant
1391 // else we'll never succeed.
1392 if (!match(SelVal0, m_AnyIntegralConstant()) &&
1393 !match(SelVal1, m_AnyIntegralConstant()))
1396 // Does this constant C match any of the `select` values?
1397 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1398 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1401 // If C0 *already* matches true/false value of select, we are done.
1402 if (MatchesSelectValue(C0))
1405 // Check the constant we'd have with flipped-strictness predicate.
1406 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0);
1407 if (!FlippedStrictness)
1410 // If said constant doesn't match either, then there is no hope,
1411 if (!MatchesSelectValue(FlippedStrictness->second))
1414 // It matched! Lets insert the new comparison just before select.
1415 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1416 IC.Builder.SetInsertPoint(&Sel);
1418 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1419 Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1420 Cmp.getName() + ".inv");
1421 IC.replaceOperand(Sel, 0, NewCmp);
1423 Sel.swapProfMetadata();
1428 /// Visit a SelectInst that has an ICmpInst as its first operand.
1429 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1431 if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ))
1432 return replaceInstUsesWith(SI, V);
1434 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this))
1437 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, *this))
1440 if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
1443 if (Instruction *NewSel =
1444 tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1447 bool Changed = adjustMinMax(SI, *ICI);
1449 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1450 return replaceInstUsesWith(SI, V);
1452 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1453 Value *TrueVal = SI.getTrueValue();
1454 Value *FalseVal = SI.getFalseValue();
1455 ICmpInst::Predicate Pred = ICI->getPredicate();
1456 Value *CmpLHS = ICI->getOperand(0);
1457 Value *CmpRHS = ICI->getOperand(1);
1458 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1459 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1460 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1461 SI.setOperand(1, CmpRHS);
1463 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1464 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1465 SI.setOperand(2, CmpRHS);
1470 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1471 // decomposeBitTestICmp() might help.
1474 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1475 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1479 bool IsBitTest = false;
1480 if (ICmpInst::isEquality(Pred) &&
1481 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1482 match(CmpRHS, m_Zero())) {
1484 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1485 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1487 Y = &MinSignedValue;
1489 TrueWhenUnset = false;
1490 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1492 Y = &MinSignedValue;
1494 TrueWhenUnset = true;
1498 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
1499 if (TrueWhenUnset && TrueVal == X &&
1500 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1501 V = Builder.CreateAnd(X, ~(*Y));
1502 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
1503 else if (!TrueWhenUnset && FalseVal == X &&
1504 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1505 V = Builder.CreateAnd(X, ~(*Y));
1506 // (X & Y) == 0 ? X ^ Y : X --> X | Y
1507 else if (TrueWhenUnset && FalseVal == X &&
1508 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1509 V = Builder.CreateOr(X, *Y);
1510 // (X & Y) != 0 ? X : X ^ Y --> X | Y
1511 else if (!TrueWhenUnset && TrueVal == X &&
1512 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1513 V = Builder.CreateOr(X, *Y);
1516 return replaceInstUsesWith(SI, V);
1520 if (Instruction *V =
1521 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1524 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1527 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1528 return replaceInstUsesWith(SI, V);
1530 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1531 return replaceInstUsesWith(SI, V);
1533 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1534 return replaceInstUsesWith(SI, V);
1536 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1537 return replaceInstUsesWith(SI, V);
1539 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1540 return replaceInstUsesWith(SI, V);
1542 return Changed ? &SI : nullptr;
1545 /// SI is a select whose condition is a PHI node (but the two may be in
1546 /// different blocks). See if the true/false values (V) are live in all of the
1547 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1549 /// X = phi [ C1, BB1], [C2, BB2]
1551 /// Z = select X, Y, 0
1553 /// because Y is not live in BB1/BB2.
1554 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1555 const SelectInst &SI) {
1556 // If the value is a non-instruction value like a constant or argument, it
1557 // can always be mapped.
1558 const Instruction *I = dyn_cast<Instruction>(V);
1559 if (!I) return true;
1561 // If V is a PHI node defined in the same block as the condition PHI, we can
1562 // map the arguments.
1563 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1565 if (const PHINode *VP = dyn_cast<PHINode>(I))
1566 if (VP->getParent() == CondPHI->getParent())
1569 // Otherwise, if the PHI and select are defined in the same block and if V is
1570 // defined in a different block, then we can transform it.
1571 if (SI.getParent() == CondPHI->getParent() &&
1572 I->getParent() != CondPHI->getParent())
1575 // Otherwise we have a 'hard' case and we can't tell without doing more
1576 // detailed dominator based analysis, punt.
1580 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1581 /// SPF2(SPF1(A, B), C)
1582 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1583 SelectPatternFlavor SPF1,
1586 SelectPatternFlavor SPF2, Value *C) {
1587 if (Outer.getType() != Inner->getType())
1590 if (C == A || C == B) {
1591 // MAX(MAX(A, B), B) -> MAX(A, B)
1592 // MIN(MIN(a, b), a) -> MIN(a, b)
1593 // TODO: This could be done in instsimplify.
1594 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1595 return replaceInstUsesWith(Outer, Inner);
1597 // MAX(MIN(a, b), a) -> a
1598 // MIN(MAX(a, b), a) -> a
1599 // TODO: This could be done in instsimplify.
1600 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1601 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1602 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1603 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1604 return replaceInstUsesWith(Outer, C);
1608 const APInt *CB, *CC;
1609 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1610 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1611 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1612 // TODO: This could be done in instsimplify.
1613 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1614 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1615 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1616 (SPF1 == SPF_SMAX && CB->sge(*CC)))
1617 return replaceInstUsesWith(Outer, Inner);
1619 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1620 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1621 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1622 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1623 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1624 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1625 Outer.replaceUsesOfWith(Inner, A);
1631 // max(max(A, B), min(A, B)) --> max(A, B)
1632 // min(min(A, B), max(A, B)) --> min(A, B)
1633 // TODO: This could be done in instsimplify.
1635 ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1636 (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1637 (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1638 (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1639 return replaceInstUsesWith(Outer, Inner);
1641 // ABS(ABS(X)) -> ABS(X)
1642 // NABS(NABS(X)) -> NABS(X)
1643 // TODO: This could be done in instsimplify.
1644 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1645 return replaceInstUsesWith(Outer, Inner);
1648 // ABS(NABS(X)) -> ABS(X)
1649 // NABS(ABS(X)) -> NABS(X)
1650 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1651 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1652 SelectInst *SI = cast<SelectInst>(Inner);
1654 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1655 SI->getTrueValue(), SI->getName(), SI);
1656 return replaceInstUsesWith(Outer, NewSI);
1659 auto IsFreeOrProfitableToInvert =
1660 [&](Value *V, Value *&NotV, bool &ElidesXor) {
1661 if (match(V, m_Not(m_Value(NotV)))) {
1662 // If V has at most 2 uses then we can get rid of the xor operation
1664 ElidesXor |= !V->hasNUsesOrMore(3);
1668 if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1676 Value *NotA, *NotB, *NotC;
1677 bool ElidesXor = false;
1679 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1680 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1681 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1682 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1684 // This transform is performance neutral if we can elide at least one xor from
1685 // the set of three operands, since we'll be tacking on an xor at the very
1687 if (SelectPatternResult::isMinOrMax(SPF1) &&
1688 SelectPatternResult::isMinOrMax(SPF2) &&
1689 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1690 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1691 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1693 NotA = Builder.CreateNot(A);
1695 NotB = Builder.CreateNot(B);
1697 NotC = Builder.CreateNot(C);
1699 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1701 Value *NewOuter = Builder.CreateNot(
1702 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1703 return replaceInstUsesWith(Outer, NewOuter);
1709 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1710 /// This is even legal for FP.
1711 static Instruction *foldAddSubSelect(SelectInst &SI,
1712 InstCombiner::BuilderTy &Builder) {
1713 Value *CondVal = SI.getCondition();
1714 Value *TrueVal = SI.getTrueValue();
1715 Value *FalseVal = SI.getFalseValue();
1716 auto *TI = dyn_cast<Instruction>(TrueVal);
1717 auto *FI = dyn_cast<Instruction>(FalseVal);
1718 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1721 Instruction *AddOp = nullptr, *SubOp = nullptr;
1722 if ((TI->getOpcode() == Instruction::Sub &&
1723 FI->getOpcode() == Instruction::Add) ||
1724 (TI->getOpcode() == Instruction::FSub &&
1725 FI->getOpcode() == Instruction::FAdd)) {
1728 } else if ((FI->getOpcode() == Instruction::Sub &&
1729 TI->getOpcode() == Instruction::Add) ||
1730 (FI->getOpcode() == Instruction::FSub &&
1731 TI->getOpcode() == Instruction::FAdd)) {
1737 Value *OtherAddOp = nullptr;
1738 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1739 OtherAddOp = AddOp->getOperand(1);
1740 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1741 OtherAddOp = AddOp->getOperand(0);
1745 // So at this point we know we have (Y -> OtherAddOp):
1746 // select C, (add X, Y), (sub X, Z)
1747 Value *NegVal; // Compute -Z
1748 if (SI.getType()->isFPOrFPVectorTy()) {
1749 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1750 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1751 FastMathFlags Flags = AddOp->getFastMathFlags();
1752 Flags &= SubOp->getFastMathFlags();
1753 NegInst->setFastMathFlags(Flags);
1756 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1759 Value *NewTrueOp = OtherAddOp;
1760 Value *NewFalseOp = NegVal;
1762 std::swap(NewTrueOp, NewFalseOp);
1763 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1764 SI.getName() + ".p", &SI);
1766 if (SI.getType()->isFPOrFPVectorTy()) {
1768 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1770 FastMathFlags Flags = AddOp->getFastMathFlags();
1771 Flags &= SubOp->getFastMathFlags();
1772 RI->setFastMathFlags(Flags);
1775 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1781 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1782 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1783 /// Along with a number of patterns similar to:
1784 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1785 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1786 static Instruction *
1787 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1788 Value *CondVal = SI.getCondition();
1789 Value *TrueVal = SI.getTrueValue();
1790 Value *FalseVal = SI.getFalseValue();
1792 WithOverflowInst *II;
1793 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1794 !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1797 Value *X = II->getLHS();
1798 Value *Y = II->getRHS();
1800 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1801 Type *Ty = Limit->getType();
1803 ICmpInst::Predicate Pred;
1804 Value *TrueVal, *FalseVal, *Op;
1806 if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1807 m_Value(TrueVal), m_Value(FalseVal))))
1810 auto IsZeroOrOne = [](const APInt &C) {
1811 return C.isNullValue() || C.isOneValue();
1813 auto IsMinMax = [&](Value *Min, Value *Max) {
1814 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1815 APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1816 return match(Min, m_SpecificInt(MinVal)) &&
1817 match(Max, m_SpecificInt(MaxVal));
1820 if (Op != X && Op != Y)
1824 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1825 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1826 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1827 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1828 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1829 IsMinMax(TrueVal, FalseVal))
1831 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1832 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1833 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1834 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1835 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1836 IsMinMax(FalseVal, TrueVal))
1839 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1840 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1841 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
1842 IsMinMax(TrueVal, FalseVal))
1844 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1845 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1846 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
1847 IsMinMax(FalseVal, TrueVal))
1849 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1850 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1851 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1852 IsMinMax(FalseVal, TrueVal))
1854 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1855 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1856 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1857 IsMinMax(TrueVal, FalseVal))
1864 Intrinsic::ID NewIntrinsicID;
1865 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1866 match(TrueVal, m_AllOnes()))
1867 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1868 NewIntrinsicID = Intrinsic::uadd_sat;
1869 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1870 match(TrueVal, m_Zero()))
1871 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1872 NewIntrinsicID = Intrinsic::usub_sat;
1873 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
1874 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
1875 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1876 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1877 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1878 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1879 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1880 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1881 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1882 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1883 NewIntrinsicID = Intrinsic::sadd_sat;
1884 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
1885 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
1886 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1887 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1888 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1889 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1890 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1891 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1892 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1893 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1894 NewIntrinsicID = Intrinsic::ssub_sat;
1899 Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1900 return CallInst::Create(F, {X, Y});
1903 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1905 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1906 !match(Sel.getFalseValue(), m_Constant(C)))
1909 Instruction *ExtInst;
1910 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1911 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1914 auto ExtOpcode = ExtInst->getOpcode();
1915 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1918 // If we are extending from a boolean type or if we can create a select that
1919 // has the same size operands as its condition, try to narrow the select.
1920 Value *X = ExtInst->getOperand(0);
1921 Type *SmallType = X->getType();
1922 Value *Cond = Sel.getCondition();
1923 auto *Cmp = dyn_cast<CmpInst>(Cond);
1924 if (!SmallType->isIntOrIntVectorTy(1) &&
1925 (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1928 // If the constant is the same after truncation to the smaller type and
1929 // extension to the original type, we can narrow the select.
1930 Type *SelType = Sel.getType();
1931 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1932 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1933 if (ExtC == C && ExtInst->hasOneUse()) {
1934 Value *TruncCVal = cast<Value>(TruncC);
1935 if (ExtInst == Sel.getFalseValue())
1936 std::swap(X, TruncCVal);
1938 // select Cond, (ext X), C --> ext(select Cond, X, C')
1939 // select Cond, C, (ext X) --> ext(select Cond, C', X)
1940 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1941 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1944 // If one arm of the select is the extend of the condition, replace that arm
1945 // with the extension of the appropriate known bool value.
1947 if (ExtInst == Sel.getTrueValue()) {
1948 // select X, (sext X), C --> select X, -1, C
1949 // select X, (zext X), C --> select X, 1, C
1950 Constant *One = ConstantInt::getTrue(SmallType);
1951 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1952 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1954 // select X, C, (sext X) --> select X, C, 0
1955 // select X, C, (zext X) --> select X, C, 0
1956 Constant *Zero = ConstantInt::getNullValue(SelType);
1957 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1964 /// Try to transform a vector select with a constant condition vector into a
1965 /// shuffle for easier combining with other shuffles and insert/extract.
1966 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1967 Value *CondVal = SI.getCondition();
1969 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1972 unsigned NumElts = cast<VectorType>(CondVal->getType())->getNumElements();
1973 SmallVector<int, 16> Mask;
1974 Mask.reserve(NumElts);
1975 for (unsigned i = 0; i != NumElts; ++i) {
1976 Constant *Elt = CondC->getAggregateElement(i);
1980 if (Elt->isOneValue()) {
1981 // If the select condition element is true, choose from the 1st vector.
1983 } else if (Elt->isNullValue()) {
1984 // If the select condition element is false, choose from the 2nd vector.
1985 Mask.push_back(i + NumElts);
1986 } else if (isa<UndefValue>(Elt)) {
1987 // Undef in a select condition (choose one of the operands) does not mean
1988 // the same thing as undef in a shuffle mask (any value is acceptable), so
1992 // Bail out on a constant expression.
1997 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2000 /// If we have a select of vectors with a scalar condition, try to convert that
2001 /// to a vector select by splatting the condition. A splat may get folded with
2002 /// other operations in IR and having all operands of a select be vector types
2003 /// is likely better for vector codegen.
2004 static Instruction *canonicalizeScalarSelectOfVecs(
2005 SelectInst &Sel, InstCombiner &IC) {
2006 auto *Ty = dyn_cast<VectorType>(Sel.getType());
2010 // We can replace a single-use extract with constant index.
2011 Value *Cond = Sel.getCondition();
2012 if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
2015 // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2016 // Splatting the extracted condition reduces code (we could directly create a
2017 // splat shuffle of the source vector to eliminate the intermediate step).
2018 unsigned NumElts = Ty->getNumElements();
2019 return IC.replaceOperand(Sel, 0, IC.Builder.CreateVectorSplat(NumElts, Cond));
2022 /// Reuse bitcasted operands between a compare and select:
2023 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2024 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2025 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2026 InstCombiner::BuilderTy &Builder) {
2027 Value *Cond = Sel.getCondition();
2028 Value *TVal = Sel.getTrueValue();
2029 Value *FVal = Sel.getFalseValue();
2031 CmpInst::Predicate Pred;
2033 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2036 // The select condition is a compare instruction. If the select's true/false
2037 // values are already the same as the compare operands, there's nothing to do.
2038 if (TVal == A || TVal == B || FVal == A || FVal == B)
2042 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2045 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2047 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2048 !match(FVal, m_BitCast(m_Value(FSrc))))
2051 // If the select true/false values are *different bitcasts* of the same source
2052 // operands, make the select operands the same as the compare operands and
2053 // cast the result. This is the canonical select form for min/max.
2055 if (TSrc == C && FSrc == D) {
2056 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2057 // bitcast (select (cmp A, B), A, B)
2058 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2059 } else if (TSrc == D && FSrc == C) {
2060 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2061 // bitcast (select (cmp A, B), B, A)
2062 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2066 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2069 /// Try to eliminate select instructions that test the returned flag of cmpxchg
2072 /// If a select instruction tests the returned flag of a cmpxchg instruction and
2073 /// selects between the returned value of the cmpxchg instruction its compare
2074 /// operand, the result of the select will always be equal to its false value.
2077 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2078 /// %1 = extractvalue { i64, i1 } %0, 1
2079 /// %2 = extractvalue { i64, i1 } %0, 0
2080 /// %3 = select i1 %1, i64 %compare, i64 %2
2083 /// The returned value of the cmpxchg instruction (%2) is the original value
2084 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2085 /// must have been equal to %compare. Thus, the result of the select is always
2086 /// equal to %2, and the code can be simplified to:
2088 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2089 /// %1 = extractvalue { i64, i1 } %0, 0
2092 static Value *foldSelectCmpXchg(SelectInst &SI) {
2093 // A helper that determines if V is an extractvalue instruction whose
2094 // aggregate operand is a cmpxchg instruction and whose single index is equal
2095 // to I. If such conditions are true, the helper returns the cmpxchg
2096 // instruction; otherwise, a nullptr is returned.
2097 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2098 auto *Extract = dyn_cast<ExtractValueInst>(V);
2101 if (Extract->getIndices()[0] != I)
2103 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2106 // If the select has a single user, and this user is a select instruction that
2107 // we can simplify, skip the cmpxchg simplification for now.
2109 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2110 if (Select->getCondition() == SI.getCondition())
2111 if (Select->getFalseValue() == SI.getTrueValue() ||
2112 Select->getTrueValue() == SI.getFalseValue())
2115 // Ensure the select condition is the returned flag of a cmpxchg instruction.
2116 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2120 // Check the true value case: The true value of the select is the returned
2121 // value of the same cmpxchg used by the condition, and the false value is the
2122 // cmpxchg instruction's compare operand.
2123 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2124 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2125 return SI.getFalseValue();
2127 // Check the false value case: The false value of the select is the returned
2128 // value of the same cmpxchg used by the condition, and the true value is the
2129 // cmpxchg instruction's compare operand.
2130 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2131 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2132 return SI.getFalseValue();
2137 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2139 InstCombiner::BuilderTy &Builder) {
2140 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
2141 bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2142 SPF == SelectPatternFlavor::SPF_UMAX;
2143 // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2144 // the constant value check to an assert.
2146 const APInt *C1, *C2;
2147 if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2148 match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2149 // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2150 // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2151 Value *NewMinMax = createMinMax(Builder, SPF, A,
2152 ConstantInt::get(X->getType(), *C2 - *C1));
2153 return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2154 ConstantInt::get(X->getType(), *C1));
2157 if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2158 match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2160 APInt Diff = C2->ssub_ov(*C1, Overflow);
2162 // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2163 // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2164 Value *NewMinMax = createMinMax(Builder, SPF, A,
2165 ConstantInt::get(X->getType(), Diff));
2166 return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2167 ConstantInt::get(X->getType(), *C1));
2174 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
2175 Instruction *InstCombiner::matchSAddSubSat(SelectInst &MinMax1) {
2176 Type *Ty = MinMax1.getType();
2178 // We are looking for a tree of:
2179 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2180 // Where the min and max could be reversed
2181 Instruction *MinMax2;
2182 BinaryOperator *AddSub;
2183 const APInt *MinValue, *MaxValue;
2184 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2185 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2187 } else if (match(&MinMax1,
2188 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2189 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2194 // Check that the constants clamp a saturate, and that the new type would be
2195 // sensible to convert to.
2196 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2198 // In what bitwidth can this be treated as saturating arithmetics?
2199 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2200 // FIXME: This isn't quite right for vectors, but using the scalar type is a
2201 // good first approximation for what should be done there.
2202 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2205 // Also make sure that the number of uses is as expected. The "3"s are for the
2206 // the two items of min/max (the compare and the select).
2207 if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3))
2210 // Create the new type (which can be a vector type)
2211 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2212 // Match the two extends from the add/sub
2214 if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B)))))
2216 // And check the incoming values are of a type smaller than or equal to the
2217 // size of the saturation. Otherwise the higher bits can cause different
2219 if (A->getType()->getScalarSizeInBits() > NewBitWidth ||
2220 B->getType()->getScalarSizeInBits() > NewBitWidth)
2223 Intrinsic::ID IntrinsicID;
2224 if (AddSub->getOpcode() == Instruction::Add)
2225 IntrinsicID = Intrinsic::sadd_sat;
2226 else if (AddSub->getOpcode() == Instruction::Sub)
2227 IntrinsicID = Intrinsic::ssub_sat;
2231 // Finally create and return the sat intrinsic, truncated to the new type
2232 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2233 Value *AT = Builder.CreateSExt(A, NewTy);
2234 Value *BT = Builder.CreateSExt(B, NewTy);
2235 Value *Sat = Builder.CreateCall(F, {AT, BT});
2236 return CastInst::Create(Instruction::SExt, Sat, Ty);
2239 /// Reduce a sequence of min/max with a common operand.
2240 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2242 InstCombiner::BuilderTy &Builder) {
2243 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
2244 // TODO: Allow FP min/max with nnan/nsz.
2245 if (!LHS->getType()->isIntOrIntVectorTy())
2248 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2249 Value *A, *B, *C, *D;
2250 SelectPatternResult L = matchSelectPattern(LHS, A, B);
2251 SelectPatternResult R = matchSelectPattern(RHS, C, D);
2252 if (SPF != L.Flavor || L.Flavor != R.Flavor)
2255 // Look for a common operand. The use checks are different than usual because
2256 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2258 Value *MinMaxOp = nullptr;
2259 Value *ThirdOp = nullptr;
2260 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2261 // If the LHS is only used in this chain and the RHS is used outside of it,
2262 // reuse the RHS min/max because that will eliminate the LHS.
2263 if (D == A || C == A) {
2264 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2265 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2268 } else if (D == B || C == B) {
2269 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2270 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2274 } else if (!RHS->hasNUsesOrMore(3)) {
2275 // Reuse the LHS. This will eliminate the RHS.
2276 if (D == A || D == B) {
2277 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2278 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2281 } else if (C == A || C == B) {
2282 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2283 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2288 if (!MinMaxOp || !ThirdOp)
2291 CmpInst::Predicate P = getMinMaxPred(SPF);
2292 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2293 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2296 /// Try to reduce a rotate pattern that includes a compare and select into a
2297 /// funnel shift intrinsic. Example:
2298 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2299 /// --> call llvm.fshl.i32(a, a, b)
2300 static Instruction *foldSelectRotate(SelectInst &Sel) {
2301 // The false value of the select must be a rotate of the true value.
2303 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
2306 Value *TVal = Sel.getTrueValue();
2308 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
2309 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
2312 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
2313 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
2314 if (ShiftOpcode0 == ShiftOpcode1)
2317 // We have one of these patterns so far:
2318 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
2319 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
2320 // This must be a power-of-2 rotate for a bitmasking transform to be valid.
2321 unsigned Width = Sel.getType()->getScalarSizeInBits();
2322 if (!isPowerOf2_32(Width))
2325 // Check the shift amounts to see if they are an opposite pair.
2327 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2329 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2334 // Finally, see if the select is filtering out a shift-by-zero.
2335 Value *Cond = Sel.getCondition();
2336 ICmpInst::Predicate Pred;
2337 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2338 Pred != ICmpInst::ICMP_EQ)
2341 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2342 // Convert to funnel shift intrinsic.
2343 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
2344 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
2345 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2346 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2347 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
2350 static Instruction *foldSelectToCopysign(SelectInst &Sel,
2351 InstCombiner::BuilderTy &Builder) {
2352 Value *Cond = Sel.getCondition();
2353 Value *TVal = Sel.getTrueValue();
2354 Value *FVal = Sel.getFalseValue();
2355 Type *SelType = Sel.getType();
2357 // Match select ?, TC, FC where the constants are equal but negated.
2358 // TODO: Generalize to handle a negated variable operand?
2359 const APFloat *TC, *FC;
2360 if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) ||
2361 !abs(*TC).bitwiseIsEqual(abs(*FC)))
2364 assert(TC != FC && "Expected equal select arms to simplify");
2368 bool IsTrueIfSignSet;
2369 ICmpInst::Predicate Pred;
2370 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
2371 !isSignBitCheck(Pred, *C, IsTrueIfSignSet) || X->getType() != SelType)
2374 // If needed, negate the value that will be the sign argument of the copysign:
2375 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X)
2376 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X)
2377 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X)
2378 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X)
2379 if (IsTrueIfSignSet ^ TC->isNegative())
2380 X = Builder.CreateFNegFMF(X, &Sel);
2382 // Canonicalize the magnitude argument as the positive constant since we do
2383 // not care about its sign.
2384 Value *MagArg = TC->isNegative() ? FVal : TVal;
2385 Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
2387 Instruction *CopySign = IntrinsicInst::Create(F, { MagArg, X });
2388 CopySign->setFastMathFlags(Sel.getFastMathFlags());
2392 Instruction *InstCombiner::foldVectorSelect(SelectInst &Sel) {
2393 auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
2397 unsigned NumElts = VecTy->getNumElements();
2398 APInt UndefElts(NumElts, 0);
2399 APInt AllOnesEltMask(APInt::getAllOnesValue(NumElts));
2400 if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) {
2402 return replaceInstUsesWith(Sel, V);
2406 // A select of a "select shuffle" with a common operand can be rearranged
2407 // to select followed by "select shuffle". Because of poison, this only works
2408 // in the case of a shuffle with no undefined mask elements.
2409 Value *Cond = Sel.getCondition();
2410 Value *TVal = Sel.getTrueValue();
2411 Value *FVal = Sel.getFalseValue();
2414 if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2415 !is_contained(Mask, UndefMaskElem) &&
2416 cast<ShuffleVectorInst>(TVal)->isSelect()) {
2418 // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
2419 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2420 return new ShuffleVectorInst(X, NewSel, Mask);
2423 // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
2424 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2425 return new ShuffleVectorInst(NewSel, Y, Mask);
2428 if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2429 !is_contained(Mask, UndefMaskElem) &&
2430 cast<ShuffleVectorInst>(FVal)->isSelect()) {
2432 // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
2433 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2434 return new ShuffleVectorInst(X, NewSel, Mask);
2437 // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
2438 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2439 return new ShuffleVectorInst(NewSel, Y, Mask);
2446 static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
2447 const DominatorTree &DT,
2448 InstCombiner::BuilderTy &Builder) {
2449 // Find the block's immediate dominator that ends with a conditional branch
2450 // that matches select's condition (maybe inverted).
2451 auto *IDomNode = DT[BB]->getIDom();
2454 BasicBlock *IDom = IDomNode->getBlock();
2456 Value *Cond = Sel.getCondition();
2457 Value *IfTrue, *IfFalse;
2458 BasicBlock *TrueSucc, *FalseSucc;
2459 if (match(IDom->getTerminator(),
2460 m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
2461 m_BasicBlock(FalseSucc)))) {
2462 IfTrue = Sel.getTrueValue();
2463 IfFalse = Sel.getFalseValue();
2464 } else if (match(IDom->getTerminator(),
2465 m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
2466 m_BasicBlock(FalseSucc)))) {
2467 IfTrue = Sel.getFalseValue();
2468 IfFalse = Sel.getTrueValue();
2472 // Make sure the branches are actually different.
2473 if (TrueSucc == FalseSucc)
2476 // We want to replace select %cond, %a, %b with a phi that takes value %a
2477 // for all incoming edges that are dominated by condition `%cond == true`,
2478 // and value %b for edges dominated by condition `%cond == false`. If %a
2479 // or %b are also phis from the same basic block, we can go further and take
2480 // their incoming values from the corresponding blocks.
2481 BasicBlockEdge TrueEdge(IDom, TrueSucc);
2482 BasicBlockEdge FalseEdge(IDom, FalseSucc);
2483 DenseMap<BasicBlock *, Value *> Inputs;
2484 for (auto *Pred : predecessors(BB)) {
2485 // Check implication.
2486 BasicBlockEdge Incoming(Pred, BB);
2487 if (DT.dominates(TrueEdge, Incoming))
2488 Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
2489 else if (DT.dominates(FalseEdge, Incoming))
2490 Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
2493 // Check availability.
2494 if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
2495 if (!DT.dominates(Insn, Pred->getTerminator()))
2499 Builder.SetInsertPoint(&*BB->begin());
2500 auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
2501 for (auto *Pred : predecessors(BB))
2502 PN->addIncoming(Inputs[Pred], Pred);
2507 static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
2508 InstCombiner::BuilderTy &Builder) {
2509 // Try to replace this select with Phi in one of these blocks.
2510 SmallSetVector<BasicBlock *, 4> CandidateBlocks;
2511 CandidateBlocks.insert(Sel.getParent());
2512 for (Value *V : Sel.operands())
2513 if (auto *I = dyn_cast<Instruction>(V))
2514 CandidateBlocks.insert(I->getParent());
2516 for (BasicBlock *BB : CandidateBlocks)
2517 if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
2522 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2523 Value *CondVal = SI.getCondition();
2524 Value *TrueVal = SI.getTrueValue();
2525 Value *FalseVal = SI.getFalseValue();
2526 Type *SelType = SI.getType();
2528 // FIXME: Remove this workaround when freeze related patches are done.
2529 // For select with undef operand which feeds into an equality comparison,
2530 // don't simplify it so loop unswitch can know the equality comparison
2531 // may have an undef operand. This is a workaround for PR31652 caused by
2532 // descrepancy about branch on undef between LoopUnswitch and GVN.
2533 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
2534 if (llvm::any_of(SI.users(), [&](User *U) {
2535 ICmpInst *CI = dyn_cast<ICmpInst>(U);
2536 if (CI && CI->isEquality())
2544 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
2545 SQ.getWithInstruction(&SI)))
2546 return replaceInstUsesWith(SI, V);
2548 if (Instruction *I = canonicalizeSelectToShuffle(SI))
2551 if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
2554 CmpInst::Predicate Pred;
2556 if (SelType->isIntOrIntVectorTy(1) &&
2557 TrueVal->getType() == CondVal->getType()) {
2558 if (match(TrueVal, m_One())) {
2559 // Change: A = select B, true, C --> A = or B, C
2560 return BinaryOperator::CreateOr(CondVal, FalseVal);
2562 if (match(TrueVal, m_Zero())) {
2563 // Change: A = select B, false, C --> A = and !B, C
2564 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2565 return BinaryOperator::CreateAnd(NotCond, FalseVal);
2567 if (match(FalseVal, m_Zero())) {
2568 // Change: A = select B, C, false --> A = and B, C
2569 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2571 if (match(FalseVal, m_One())) {
2572 // Change: A = select B, C, true --> A = or !B, C
2573 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2574 return BinaryOperator::CreateOr(NotCond, TrueVal);
2577 // select a, a, b -> a | b
2578 // select a, b, a -> a & b
2579 if (CondVal == TrueVal)
2580 return BinaryOperator::CreateOr(CondVal, FalseVal);
2581 if (CondVal == FalseVal)
2582 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2584 // select a, ~a, b -> (~a) & b
2585 // select a, b, ~a -> (~a) | b
2586 if (match(TrueVal, m_Not(m_Specific(CondVal))))
2587 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
2588 if (match(FalseVal, m_Not(m_Specific(CondVal))))
2589 return BinaryOperator::CreateOr(TrueVal, FalseVal);
2592 // Selecting between two integer or vector splat integer constants?
2594 // Note that we don't handle a scalar select of vectors:
2595 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
2596 // because that may need 3 instructions to splat the condition value:
2597 // extend, insertelement, shufflevector.
2598 if (SelType->isIntOrIntVectorTy() &&
2599 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
2600 // select C, 1, 0 -> zext C to int
2601 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
2602 return new ZExtInst(CondVal, SelType);
2604 // select C, -1, 0 -> sext C to int
2605 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
2606 return new SExtInst(CondVal, SelType);
2608 // select C, 0, 1 -> zext !C to int
2609 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
2610 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2611 return new ZExtInst(NotCond, SelType);
2614 // select C, 0, -1 -> sext !C to int
2615 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
2616 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2617 return new SExtInst(NotCond, SelType);
2621 // See if we are selecting two values based on a comparison of the two values.
2622 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
2623 Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1);
2624 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
2625 (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
2626 // Canonicalize to use ordered comparisons by swapping the select
2630 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
2631 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
2632 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
2633 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2634 // FIXME: The FMF should propagate from the select, not the fcmp.
2635 Builder.setFastMathFlags(FCI->getFastMathFlags());
2636 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
2637 FCI->getName() + ".inv");
2638 Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
2639 return replaceInstUsesWith(SI, NewSel);
2642 // NOTE: if we wanted to, this is where to detect MIN/MAX
2646 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2647 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
2648 // also require nnan because we do not want to unintentionally change the
2649 // sign of a NaN value.
2650 // FIXME: These folds should test/propagate FMF from the select, not the
2652 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
2654 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2655 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
2656 match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2657 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2658 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub);
2659 return replaceInstUsesWith(SI, Fabs);
2661 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
2662 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2663 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
2664 match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2665 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2666 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub);
2667 return replaceInstUsesWith(SI, Fabs);
2669 // With nnan and nsz:
2670 // (X < +/-0.0) ? -X : X --> fabs(X)
2671 // (X <= +/-0.0) ? -X : X --> fabs(X)
2673 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2674 match(TrueVal, m_FNeg(m_Specific(FalseVal))) &&
2675 match(TrueVal, m_Instruction(FNeg)) &&
2676 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2677 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2678 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
2679 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg);
2680 return replaceInstUsesWith(SI, Fabs);
2682 // With nnan and nsz:
2683 // (X > +/-0.0) ? X : -X --> fabs(X)
2684 // (X >= +/-0.0) ? X : -X --> fabs(X)
2685 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2686 match(FalseVal, m_FNeg(m_Specific(TrueVal))) &&
2687 match(FalseVal, m_Instruction(FNeg)) &&
2688 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2689 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2690 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
2691 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg);
2692 return replaceInstUsesWith(SI, Fabs);
2695 // See if we are selecting two values based on a comparison of the two values.
2696 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
2697 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
2700 if (Instruction *Add = foldAddSubSelect(SI, Builder))
2702 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
2704 if (Instruction *Or = foldSetClearBits(SI, Builder))
2707 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
2708 auto *TI = dyn_cast<Instruction>(TrueVal);
2709 auto *FI = dyn_cast<Instruction>(FalseVal);
2710 if (TI && FI && TI->getOpcode() == FI->getOpcode())
2711 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
2714 if (Instruction *I = foldSelectExtConst(SI))
2717 // See if we can fold the select into one of our operands.
2718 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
2719 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
2723 Instruction::CastOps CastOp;
2724 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
2725 auto SPF = SPR.Flavor;
2728 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
2729 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
2730 RHS2, SI, SPF, RHS))
2732 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
2733 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
2734 RHS2, SI, SPF, LHS))
2737 // ABS(-X) -> ABS(X)
2740 if (SelectPatternResult::isMinOrMax(SPF)) {
2741 // Canonicalize so that
2742 // - type casts are outside select patterns.
2743 // - float clamp is transformed to min/max pattern
2745 bool IsCastNeeded = LHS->getType() != SelType;
2746 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
2747 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
2749 (LHS->getType()->isFPOrFPVectorTy() &&
2750 ((CmpLHS != LHS && CmpLHS != RHS) ||
2751 (CmpRHS != LHS && CmpRHS != RHS)))) {
2752 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
2755 if (CmpInst::isIntPredicate(MinMaxPred)) {
2756 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
2758 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2760 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
2761 Builder.setFastMathFlags(FMF);
2762 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
2765 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
2767 return replaceInstUsesWith(SI, NewSI);
2769 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
2770 return replaceInstUsesWith(SI, NewCast);
2773 // MAX(~a, ~b) -> ~MIN(a, b)
2774 // MAX(~a, C) -> ~MIN(a, ~C)
2775 // MIN(~a, ~b) -> ~MAX(a, b)
2776 // MIN(~a, C) -> ~MAX(a, ~C)
2777 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2779 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
2780 !isFreeToInvert(A, A->hasOneUse()) &&
2781 // Passing false to only consider m_Not and constants.
2782 isFreeToInvert(Y, false)) {
2783 Value *B = Builder.CreateNot(Y);
2784 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
2786 // Copy the profile metadata.
2787 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
2788 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
2789 // Swap the metadata if the operands are swapped.
2790 if (X == SI.getFalseValue() && Y == SI.getTrueValue())
2791 cast<SelectInst>(NewMinMax)->swapProfMetadata();
2794 return BinaryOperator::CreateNot(NewMinMax);
2800 if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
2802 if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
2805 if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
2808 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
2810 if (Instruction *I = matchSAddSubSat(SI))
2815 // Canonicalize select of FP values where NaN and -0.0 are not valid as
2816 // minnum/maxnum intrinsics.
2817 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
2819 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
2820 return replaceInstUsesWith(
2821 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
2823 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
2824 return replaceInstUsesWith(
2825 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
2828 // See if we can fold the select into a phi node if the condition is a select.
2829 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
2830 // The true/false values have to be live in the PHI predecessor's blocks.
2831 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
2832 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
2833 if (Instruction *NV = foldOpIntoPhi(SI, PN))
2836 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
2837 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
2838 // select(C, select(C, a, b), c) -> select(C, a, c)
2839 if (TrueSI->getCondition() == CondVal) {
2840 if (SI.getTrueValue() == TrueSI->getTrueValue())
2842 return replaceOperand(SI, 1, TrueSI->getTrueValue());
2844 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
2845 // We choose this as normal form to enable folding on the And and shortening
2846 // paths for the values (this helps GetUnderlyingObjects() for example).
2847 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
2848 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
2849 replaceOperand(SI, 0, And);
2850 replaceOperand(SI, 1, TrueSI->getTrueValue());
2855 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
2856 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
2857 // select(C, a, select(C, b, c)) -> select(C, a, c)
2858 if (FalseSI->getCondition() == CondVal) {
2859 if (SI.getFalseValue() == FalseSI->getFalseValue())
2861 return replaceOperand(SI, 2, FalseSI->getFalseValue());
2863 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
2864 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
2865 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
2866 replaceOperand(SI, 0, Or);
2867 replaceOperand(SI, 2, FalseSI->getFalseValue());
2873 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2874 // The select might be preventing a division by 0.
2875 switch (BO->getOpcode()) {
2878 case Instruction::SRem:
2879 case Instruction::URem:
2880 case Instruction::SDiv:
2881 case Instruction::UDiv:
2886 // Try to simplify a binop sandwiched between 2 selects with the same
2888 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2889 BinaryOperator *TrueBO;
2890 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2891 canMergeSelectThroughBinop(TrueBO)) {
2892 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2893 if (TrueBOSI->getCondition() == CondVal) {
2894 replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
2895 Worklist.push(TrueBO);
2899 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2900 if (TrueBOSI->getCondition() == CondVal) {
2901 replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
2902 Worklist.push(TrueBO);
2908 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2909 BinaryOperator *FalseBO;
2910 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2911 canMergeSelectThroughBinop(FalseBO)) {
2912 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2913 if (FalseBOSI->getCondition() == CondVal) {
2914 replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
2915 Worklist.push(FalseBO);
2919 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2920 if (FalseBOSI->getCondition() == CondVal) {
2921 replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
2922 Worklist.push(FalseBO);
2929 if (match(CondVal, m_Not(m_Value(NotCond)))) {
2930 replaceOperand(SI, 0, NotCond);
2932 SI.swapProfMetadata();
2936 if (Instruction *I = foldVectorSelect(SI))
2939 // If we can compute the condition, there's no need for a select.
2940 // Like the above fold, we are attempting to reduce compile-time cost by
2941 // putting this fold here with limitations rather than in InstSimplify.
2942 // The motivation for this call into value tracking is to take advantage of
2943 // the assumption cache, so make sure that is populated.
2944 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2946 computeKnownBits(CondVal, Known, 0, &SI);
2947 if (Known.One.isOneValue())
2948 return replaceInstUsesWith(SI, TrueVal);
2949 if (Known.Zero.isOneValue())
2950 return replaceInstUsesWith(SI, FalseVal);
2953 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2956 // Simplify selects that test the returned flag of cmpxchg instructions.
2957 if (Value *V = foldSelectCmpXchg(SI))
2958 return replaceInstUsesWith(SI, V);
2960 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
2963 if (Instruction *Rot = foldSelectRotate(SI))
2966 if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
2969 if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
2970 return replaceInstUsesWith(SI, PN);