1 //===- InstCombineSelect.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitSelect function.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombineInternal.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/PatternMatch.h"
20 using namespace PatternMatch;
22 #define DEBUG_TYPE "instcombine"
24 static SelectPatternFlavor
25 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
28 llvm_unreachable("unhandled!");
41 static CmpInst::Predicate getICmpPredicateForMinMax(SelectPatternFlavor SPF) {
44 llvm_unreachable("unhandled!");
47 return ICmpInst::ICMP_SLT;
49 return ICmpInst::ICMP_ULT;
51 return ICmpInst::ICMP_SGT;
53 return ICmpInst::ICMP_UGT;
57 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
58 SelectPatternFlavor SPF, Value *A,
60 CmpInst::Predicate Pred = getICmpPredicateForMinMax(SPF);
61 return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
64 /// GetSelectFoldableOperands - We want to turn code that looks like this:
66 /// %D = select %cond, %C, %A
68 /// %C = select %cond, %B, 0
71 /// Assuming that the specified instruction is an operand to the select, return
72 /// a bitmask indicating which operands of this instruction are foldable if they
73 /// equal the other incoming value of the select.
75 static unsigned GetSelectFoldableOperands(Instruction *I) {
76 switch (I->getOpcode()) {
77 case Instruction::Add:
78 case Instruction::Mul:
79 case Instruction::And:
81 case Instruction::Xor:
82 return 3; // Can fold through either operand.
83 case Instruction::Sub: // Can only fold on the amount subtracted.
84 case Instruction::Shl: // Can only fold on the shift amount.
85 case Instruction::LShr:
86 case Instruction::AShr:
89 return 0; // Cannot fold
93 /// GetSelectFoldableConstant - For the same transformation as the previous
94 /// function, return the identity constant that goes into the select.
95 static Constant *GetSelectFoldableConstant(Instruction *I) {
96 switch (I->getOpcode()) {
97 default: llvm_unreachable("This cannot happen!");
98 case Instruction::Add:
99 case Instruction::Sub:
100 case Instruction::Or:
101 case Instruction::Xor:
102 case Instruction::Shl:
103 case Instruction::LShr:
104 case Instruction::AShr:
105 return Constant::getNullValue(I->getType());
106 case Instruction::And:
107 return Constant::getAllOnesValue(I->getType());
108 case Instruction::Mul:
109 return ConstantInt::get(I->getType(), 1);
113 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
114 /// have the same opcode and only one use each. Try to simplify this.
115 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
117 if (TI->getNumOperands() == 1) {
118 // If this is a non-volatile load or a cast from the same type,
121 Type *FIOpndTy = FI->getOperand(0)->getType();
122 if (TI->getOperand(0)->getType() != FIOpndTy)
124 // The select condition may be a vector. We may only change the operand
125 // type if the vector width remains the same (and matches the condition).
126 Type *CondTy = SI.getCondition()->getType();
127 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
128 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
131 return nullptr; // unknown unary op.
134 // Fold this by inserting a select from the input values.
135 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
136 FI->getOperand(0), SI.getName()+".v");
137 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
141 // Only handle binary operators here.
142 if (!isa<BinaryOperator>(TI))
145 // Figure out if the operations have any operands in common.
146 Value *MatchOp, *OtherOpT, *OtherOpF;
148 if (TI->getOperand(0) == FI->getOperand(0)) {
149 MatchOp = TI->getOperand(0);
150 OtherOpT = TI->getOperand(1);
151 OtherOpF = FI->getOperand(1);
152 MatchIsOpZero = true;
153 } else if (TI->getOperand(1) == FI->getOperand(1)) {
154 MatchOp = TI->getOperand(1);
155 OtherOpT = TI->getOperand(0);
156 OtherOpF = FI->getOperand(0);
157 MatchIsOpZero = false;
158 } else if (!TI->isCommutative()) {
160 } else if (TI->getOperand(0) == FI->getOperand(1)) {
161 MatchOp = TI->getOperand(0);
162 OtherOpT = TI->getOperand(1);
163 OtherOpF = FI->getOperand(0);
164 MatchIsOpZero = true;
165 } else if (TI->getOperand(1) == FI->getOperand(0)) {
166 MatchOp = TI->getOperand(1);
167 OtherOpT = TI->getOperand(0);
168 OtherOpF = FI->getOperand(1);
169 MatchIsOpZero = true;
174 // If we reach here, they do have operations in common.
175 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
176 OtherOpF, SI.getName()+".v");
178 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
180 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
182 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
184 llvm_unreachable("Shouldn't get here");
187 static bool isSelect01(Constant *C1, Constant *C2) {
188 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
191 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
194 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
196 return C1I->isOne() || C1I->isAllOnesValue() ||
197 C2I->isOne() || C2I->isAllOnesValue();
200 /// FoldSelectIntoOp - Try fold the select into one of the operands to
201 /// facilitate further optimization.
202 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
204 // See the comment above GetSelectFoldableOperands for a description of the
205 // transformation we are doing here.
206 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
207 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
208 !isa<Constant>(FalseVal)) {
209 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
210 unsigned OpToFold = 0;
211 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
213 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
218 Constant *C = GetSelectFoldableConstant(TVI);
219 Value *OOp = TVI->getOperand(2-OpToFold);
220 // Avoid creating select between 2 constants unless it's selecting
221 // between 0, 1 and -1.
222 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
223 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
224 NewSel->takeName(TVI);
225 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
226 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
228 if (isa<PossiblyExactOperator>(BO))
229 BO->setIsExact(TVI_BO->isExact());
230 if (isa<OverflowingBinaryOperator>(BO)) {
231 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
232 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
241 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
242 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
243 !isa<Constant>(TrueVal)) {
244 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
245 unsigned OpToFold = 0;
246 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
248 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
253 Constant *C = GetSelectFoldableConstant(FVI);
254 Value *OOp = FVI->getOperand(2-OpToFold);
255 // Avoid creating select between 2 constants unless it's selecting
256 // between 0, 1 and -1.
257 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
258 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
259 NewSel->takeName(FVI);
260 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
261 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
263 if (isa<PossiblyExactOperator>(BO))
264 BO->setIsExact(FVI_BO->isExact());
265 if (isa<OverflowingBinaryOperator>(BO)) {
266 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
267 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
279 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
280 /// replaced with RepOp.
281 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
282 const TargetLibraryInfo *TLI,
283 const DataLayout &DL, DominatorTree *DT,
284 AssumptionCache *AC) {
285 // Trivial replacement.
289 Instruction *I = dyn_cast<Instruction>(V);
293 // If this is a binary operator, try to simplify it with the replaced op.
294 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
295 if (B->getOperand(0) == Op)
296 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), DL, TLI);
297 if (B->getOperand(1) == Op)
298 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, DL, TLI);
301 // Same for CmpInsts.
302 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
303 if (C->getOperand(0) == Op)
304 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), DL,
306 if (C->getOperand(1) == Op)
307 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, DL,
311 // TODO: We could hand off more cases to instsimplify here.
313 // If all operands are constant after substituting Op for RepOp then we can
314 // constant fold the instruction.
315 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
316 // Build a list of all constant operands.
317 SmallVector<Constant*, 8> ConstOps;
318 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
319 if (I->getOperand(i) == Op)
320 ConstOps.push_back(CRepOp);
321 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
322 ConstOps.push_back(COp);
327 // All operands were constants, fold it.
328 if (ConstOps.size() == I->getNumOperands()) {
329 if (CmpInst *C = dyn_cast<CmpInst>(I))
330 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
331 ConstOps[1], DL, TLI);
333 if (LoadInst *LI = dyn_cast<LoadInst>(I))
334 if (!LI->isVolatile())
335 return ConstantFoldLoadFromConstPtr(ConstOps[0], DL);
337 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), ConstOps,
345 /// foldSelectICmpAndOr - We want to turn:
346 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
348 /// (or (shl (and X, C1), C3), y)
350 /// C1 and C2 are both powers of 2
352 /// C3 = Log(C2) - Log(C1)
354 /// This transform handles cases where:
355 /// 1. The icmp predicate is inverted
356 /// 2. The select operands are reversed
357 /// 3. The magnitude of C2 and C1 are flipped
358 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
360 InstCombiner::BuilderTy *Builder) {
361 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
362 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
365 Value *CmpLHS = IC->getOperand(0);
366 Value *CmpRHS = IC->getOperand(1);
368 if (!match(CmpRHS, m_Zero()))
373 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
377 bool OrOnTrueVal = false;
378 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
380 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
382 if (!OrOnFalseVal && !OrOnTrueVal)
386 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
388 unsigned C1Log = C1->logBase2();
389 unsigned C2Log = C2->logBase2();
391 V = Builder->CreateZExtOrTrunc(V, Y->getType());
392 V = Builder->CreateShl(V, C2Log - C1Log);
393 } else if (C1Log > C2Log) {
394 V = Builder->CreateLShr(V, C1Log - C2Log);
395 V = Builder->CreateZExtOrTrunc(V, Y->getType());
397 V = Builder->CreateZExtOrTrunc(V, Y->getType());
399 ICmpInst::Predicate Pred = IC->getPredicate();
400 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
401 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
402 V = Builder->CreateXor(V, *C2);
404 return Builder->CreateOr(V, Y);
407 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
408 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
410 /// For example, we can fold the following code sequence:
412 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
413 /// %1 = icmp ne i32 %x, 0
414 /// %2 = select i1 %1, i32 %0, i32 32
418 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
419 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
420 InstCombiner::BuilderTy *Builder) {
421 ICmpInst::Predicate Pred = ICI->getPredicate();
422 Value *CmpLHS = ICI->getOperand(0);
423 Value *CmpRHS = ICI->getOperand(1);
425 // Check if the condition value compares a value for equality against zero.
426 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
429 Value *Count = FalseVal;
430 Value *ValueOnZero = TrueVal;
431 if (Pred == ICmpInst::ICMP_NE)
432 std::swap(Count, ValueOnZero);
434 // Skip zero extend/truncate.
436 if (match(Count, m_ZExt(m_Value(V))) ||
437 match(Count, m_Trunc(m_Value(V))))
440 // Check if the value propagated on zero is a constant number equal to the
441 // sizeof in bits of 'Count'.
442 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
443 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
446 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
447 // input to the cttz/ctlz is used as LHS for the compare instruction.
448 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
449 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
450 IntrinsicInst *II = cast<IntrinsicInst>(Count);
451 IRBuilder<> Builder(II);
452 // Explicitly clear the 'undef_on_zero' flag.
453 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
454 Type *Ty = NewI->getArgOperand(1)->getType();
455 NewI->setArgOperand(1, Constant::getNullValue(Ty));
456 Builder.Insert(NewI);
457 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
463 /// visitSelectInstWithICmp - Visit a SelectInst that has an
464 /// ICmpInst as its first operand.
466 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
468 bool Changed = false;
469 ICmpInst::Predicate Pred = ICI->getPredicate();
470 Value *CmpLHS = ICI->getOperand(0);
471 Value *CmpRHS = ICI->getOperand(1);
472 Value *TrueVal = SI.getTrueValue();
473 Value *FalseVal = SI.getFalseValue();
475 // Check cases where the comparison is with a constant that
476 // can be adjusted to fit the min/max idiom. We may move or edit ICI
477 // here, so make sure the select is the only user.
478 if (ICI->hasOneUse())
479 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
480 // X < MIN ? T : F --> F
481 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
482 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
483 return ReplaceInstUsesWith(SI, FalseVal);
484 // X > MAX ? T : F --> F
485 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
486 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
487 return ReplaceInstUsesWith(SI, FalseVal);
490 case ICmpInst::ICMP_ULT:
491 case ICmpInst::ICMP_SLT:
492 case ICmpInst::ICMP_UGT:
493 case ICmpInst::ICMP_SGT: {
494 // These transformations only work for selects over integers.
495 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
499 Constant *AdjustedRHS;
500 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
501 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
502 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
503 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
505 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
506 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
507 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
508 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
509 ; // Nothing to do here. Values match without any sign/zero extension.
511 // Types do not match. Instead of calculating this with mixed types
512 // promote all to the larger type. This enables scalar evolution to
513 // analyze this expression.
514 else if (CmpRHS->getType()->getScalarSizeInBits()
515 < SelectTy->getBitWidth()) {
516 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
518 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
519 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
520 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
521 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
522 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
523 sextRHS == FalseVal) {
525 AdjustedRHS = sextRHS;
526 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
527 sextRHS == TrueVal) {
529 AdjustedRHS = sextRHS;
530 } else if (ICI->isUnsigned()) {
531 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
532 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
533 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
534 // zext + signed compare cannot be changed:
535 // 0xff <s 0x00, but 0x00ff >s 0x0000
536 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
537 zextRHS == FalseVal) {
539 AdjustedRHS = zextRHS;
540 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
541 zextRHS == TrueVal) {
543 AdjustedRHS = zextRHS;
551 Pred = ICmpInst::getSwappedPredicate(Pred);
552 CmpRHS = AdjustedRHS;
553 std::swap(FalseVal, TrueVal);
554 ICI->setPredicate(Pred);
555 ICI->setOperand(0, CmpLHS);
556 ICI->setOperand(1, CmpRHS);
557 SI.setOperand(1, TrueVal);
558 SI.setOperand(2, FalseVal);
560 // Move ICI instruction right before the select instruction. Otherwise
561 // the sext/zext value may be defined after the ICI instruction uses it.
562 ICI->moveBefore(&SI);
570 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
571 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
572 // FIXME: Type and constness constraints could be lifted, but we have to
573 // watch code size carefully. We should consider xor instead of
574 // sub/add when we decide to do that.
575 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
576 if (TrueVal->getType() == Ty) {
577 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
578 ConstantInt *C1 = nullptr, *C2 = nullptr;
579 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
580 C1 = dyn_cast<ConstantInt>(TrueVal);
581 C2 = dyn_cast<ConstantInt>(FalseVal);
582 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
583 C1 = dyn_cast<ConstantInt>(FalseVal);
584 C2 = dyn_cast<ConstantInt>(TrueVal);
587 // This shift results in either -1 or 0.
588 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
590 // Check if we can express the operation with a single or.
591 if (C2->isAllOnesValue())
592 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
594 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
595 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
602 // %cmp = icmp eq i32 %x, 2147483647
603 // %add = add nsw i32 %x, 1
604 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
606 // We can't replace %sel with %add unless we strip away the flags.
607 auto StripBinOpFlags = [](Value *V) {
608 if (auto *B = dyn_cast<BinaryOperator>(V)) {
609 if (isa<OverflowingBinaryOperator>(B)) {
610 B->setHasNoSignedWrap(false);
611 B->setHasNoUnsignedWrap(false);
613 if (isa<PossiblyExactOperator>(B))
614 B->setIsExact(false);
619 // If we have an equality comparison then we know the value in one of the
620 // arms of the select. See if substituting this value into the arm and
621 // simplifying the result yields the same value as the other arm.
622 if (Pred == ICmpInst::ICMP_EQ) {
623 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
625 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
627 return ReplaceInstUsesWith(SI, StripBinOpFlags(FalseVal));
628 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
630 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
632 return ReplaceInstUsesWith(SI, StripBinOpFlags(FalseVal));
633 } else if (Pred == ICmpInst::ICMP_NE) {
634 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
636 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
638 return ReplaceInstUsesWith(SI, StripBinOpFlags(TrueVal));
639 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
641 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
643 return ReplaceInstUsesWith(SI, StripBinOpFlags(TrueVal));
646 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
648 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
649 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
650 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
651 SI.setOperand(1, CmpRHS);
653 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
654 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
655 SI.setOperand(2, CmpRHS);
660 if (unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits()) {
661 APInt MinSignedValue = APInt::getSignBit(BitWidth);
665 bool IsBitTest = false;
666 if (ICmpInst::isEquality(Pred) &&
667 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
668 match(CmpRHS, m_Zero())) {
670 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
671 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
675 TrueWhenUnset = false;
676 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
680 TrueWhenUnset = true;
684 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
685 if (TrueWhenUnset && TrueVal == X &&
686 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
687 V = Builder->CreateAnd(X, ~(*Y));
688 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
689 else if (!TrueWhenUnset && FalseVal == X &&
690 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
691 V = Builder->CreateAnd(X, ~(*Y));
692 // (X & Y) == 0 ? X ^ Y : X --> X | Y
693 else if (TrueWhenUnset && FalseVal == X &&
694 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
695 V = Builder->CreateOr(X, *Y);
696 // (X & Y) != 0 ? X : X ^ Y --> X | Y
697 else if (!TrueWhenUnset && TrueVal == X &&
698 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
699 V = Builder->CreateOr(X, *Y);
702 return ReplaceInstUsesWith(SI, V);
706 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
707 return ReplaceInstUsesWith(SI, V);
709 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
710 return ReplaceInstUsesWith(SI, V);
712 return Changed ? &SI : nullptr;
716 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
717 /// PHI node (but the two may be in different blocks). See if the true/false
718 /// values (V) are live in all of the predecessor blocks of the PHI. For
719 /// example, cases like this cannot be mapped:
721 /// X = phi [ C1, BB1], [C2, BB2]
723 /// Z = select X, Y, 0
725 /// because Y is not live in BB1/BB2.
727 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
728 const SelectInst &SI) {
729 // If the value is a non-instruction value like a constant or argument, it
730 // can always be mapped.
731 const Instruction *I = dyn_cast<Instruction>(V);
734 // If V is a PHI node defined in the same block as the condition PHI, we can
735 // map the arguments.
736 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
738 if (const PHINode *VP = dyn_cast<PHINode>(I))
739 if (VP->getParent() == CondPHI->getParent())
742 // Otherwise, if the PHI and select are defined in the same block and if V is
743 // defined in a different block, then we can transform it.
744 if (SI.getParent() == CondPHI->getParent() &&
745 I->getParent() != CondPHI->getParent())
748 // Otherwise we have a 'hard' case and we can't tell without doing more
749 // detailed dominator based analysis, punt.
753 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
754 /// SPF2(SPF1(A, B), C)
755 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
756 SelectPatternFlavor SPF1,
759 SelectPatternFlavor SPF2, Value *C) {
760 if (C == A || C == B) {
761 // MAX(MAX(A, B), B) -> MAX(A, B)
762 // MIN(MIN(a, b), a) -> MIN(a, b)
764 return ReplaceInstUsesWith(Outer, Inner);
766 // MAX(MIN(a, b), a) -> a
767 // MIN(MAX(a, b), a) -> a
768 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
769 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
770 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
771 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
772 return ReplaceInstUsesWith(Outer, C);
776 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
777 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
778 APInt ACB = CB->getValue();
779 APInt ACC = CC->getValue();
781 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
782 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
783 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
784 (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
785 (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
786 (SPF1 == SPF_SMAX && ACB.sge(ACC)))
787 return ReplaceInstUsesWith(Outer, Inner);
789 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
790 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
791 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
792 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
793 (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
794 (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
795 Outer.replaceUsesOfWith(Inner, A);
802 // ABS(ABS(X)) -> ABS(X)
803 // NABS(NABS(X)) -> NABS(X)
804 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
805 return ReplaceInstUsesWith(Outer, Inner);
808 // ABS(NABS(X)) -> ABS(X)
809 // NABS(ABS(X)) -> NABS(X)
810 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
811 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
812 SelectInst *SI = cast<SelectInst>(Inner);
813 Value *NewSI = Builder->CreateSelect(
814 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
815 return ReplaceInstUsesWith(Outer, NewSI);
818 auto IsFreeOrProfitableToInvert =
819 [&](Value *V, Value *&NotV, bool &ElidesXor) {
820 if (match(V, m_Not(m_Value(NotV)))) {
821 // If V has at most 2 uses then we can get rid of the xor operation
823 ElidesXor |= !V->hasNUsesOrMore(3);
827 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
835 Value *NotA, *NotB, *NotC;
836 bool ElidesXor = false;
838 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
839 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
840 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
841 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
843 // This transform is performance neutral if we can elide at least one xor from
844 // the set of three operands, since we'll be tacking on an xor at the very
846 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
847 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
848 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
850 NotA = Builder->CreateNot(A);
852 NotB = Builder->CreateNot(B);
854 NotC = Builder->CreateNot(C);
856 Value *NewInner = generateMinMaxSelectPattern(
857 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
858 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
859 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
860 return ReplaceInstUsesWith(Outer, NewOuter);
866 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
867 /// both be) and we have an icmp instruction with zero, and we have an 'and'
868 /// with the non-constant value and a power of two we can turn the select
869 /// into a shift on the result of the 'and'.
870 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
871 ConstantInt *FalseVal,
872 InstCombiner::BuilderTy *Builder) {
873 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
874 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
877 if (!match(IC->getOperand(1), m_Zero()))
881 Value *LHS = IC->getOperand(0);
882 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
885 // If both select arms are non-zero see if we have a select of the form
886 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
887 // for 'x ? 2^n : 0' and fix the thing up at the end.
888 ConstantInt *Offset = nullptr;
889 if (!TrueVal->isZero() && !FalseVal->isZero()) {
890 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
892 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
897 // Adjust TrueVal and FalseVal to the offset.
898 TrueVal = ConstantInt::get(Builder->getContext(),
899 TrueVal->getValue() - Offset->getValue());
900 FalseVal = ConstantInt::get(Builder->getContext(),
901 FalseVal->getValue() - Offset->getValue());
904 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
905 if (!AndRHS->getValue().isPowerOf2() ||
906 (!TrueVal->getValue().isPowerOf2() &&
907 !FalseVal->getValue().isPowerOf2()))
910 // Determine which shift is needed to transform result of the 'and' into the
912 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
913 unsigned ValZeros = ValC->getValue().logBase2();
914 unsigned AndZeros = AndRHS->getValue().logBase2();
916 // If types don't match we can still convert the select by introducing a zext
917 // or a trunc of the 'and'. The trunc case requires that all of the truncated
918 // bits are zero, we can figure that out by looking at the 'and' mask.
919 if (AndZeros >= ValC->getBitWidth())
922 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
923 if (ValZeros > AndZeros)
924 V = Builder->CreateShl(V, ValZeros - AndZeros);
925 else if (ValZeros < AndZeros)
926 V = Builder->CreateLShr(V, AndZeros - ValZeros);
928 // Okay, now we know that everything is set up, we just don't know whether we
929 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
930 bool ShouldNotVal = !TrueVal->isZero();
931 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
933 V = Builder->CreateXor(V, ValC);
935 // Apply an offset if needed.
937 V = Builder->CreateAdd(V, Offset);
941 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
942 Value *CondVal = SI.getCondition();
943 Value *TrueVal = SI.getTrueValue();
944 Value *FalseVal = SI.getFalseValue();
947 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
948 return ReplaceInstUsesWith(SI, V);
950 if (SI.getType()->isIntegerTy(1)) {
951 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
952 if (C->getZExtValue()) {
953 // Change: A = select B, true, C --> A = or B, C
954 return BinaryOperator::CreateOr(CondVal, FalseVal);
956 // Change: A = select B, false, C --> A = and !B, C
957 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
958 return BinaryOperator::CreateAnd(NotCond, FalseVal);
960 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
961 if (!C->getZExtValue()) {
962 // Change: A = select B, C, false --> A = and B, C
963 return BinaryOperator::CreateAnd(CondVal, TrueVal);
965 // Change: A = select B, C, true --> A = or !B, C
966 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
967 return BinaryOperator::CreateOr(NotCond, TrueVal);
970 // select a, b, a -> a&b
971 // select a, a, b -> a|b
972 if (CondVal == TrueVal)
973 return BinaryOperator::CreateOr(CondVal, FalseVal);
974 if (CondVal == FalseVal)
975 return BinaryOperator::CreateAnd(CondVal, TrueVal);
977 // select a, ~a, b -> (~a)&b
978 // select a, b, ~a -> (~a)|b
979 if (match(TrueVal, m_Not(m_Specific(CondVal))))
980 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
981 if (match(FalseVal, m_Not(m_Specific(CondVal))))
982 return BinaryOperator::CreateOr(TrueVal, FalseVal);
985 // Selecting between two integer constants?
986 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
987 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
988 // select C, 1, 0 -> zext C to int
989 if (FalseValC->isZero() && TrueValC->getValue() == 1)
990 return new ZExtInst(CondVal, SI.getType());
992 // select C, -1, 0 -> sext C to int
993 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
994 return new SExtInst(CondVal, SI.getType());
996 // select C, 0, 1 -> zext !C to int
997 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
998 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
999 return new ZExtInst(NotCond, SI.getType());
1002 // select C, 0, -1 -> sext !C to int
1003 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
1004 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
1005 return new SExtInst(NotCond, SI.getType());
1008 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
1009 return ReplaceInstUsesWith(SI, V);
1012 // See if we are selecting two values based on a comparison of the two values.
1013 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1014 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1015 // Transform (X == Y) ? X : Y -> Y
1016 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1017 // This is not safe in general for floating point:
1018 // consider X== -0, Y== +0.
1019 // It becomes safe if either operand is a nonzero constant.
1020 ConstantFP *CFPt, *CFPf;
1021 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1022 !CFPt->getValueAPF().isZero()) ||
1023 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1024 !CFPf->getValueAPF().isZero()))
1025 return ReplaceInstUsesWith(SI, FalseVal);
1027 // Transform (X une Y) ? X : Y -> X
1028 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1029 // This is not safe in general for floating point:
1030 // consider X== -0, Y== +0.
1031 // It becomes safe if either operand is a nonzero constant.
1032 ConstantFP *CFPt, *CFPf;
1033 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1034 !CFPt->getValueAPF().isZero()) ||
1035 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1036 !CFPf->getValueAPF().isZero()))
1037 return ReplaceInstUsesWith(SI, TrueVal);
1040 // Canonicalize to use ordered comparisons by swapping the select
1044 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1045 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1046 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1047 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1048 FCI->getName() + ".inv");
1050 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1051 SI.getName() + ".p");
1054 // NOTE: if we wanted to, this is where to detect MIN/MAX
1055 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1056 // Transform (X == Y) ? Y : X -> X
1057 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1058 // This is not safe in general for floating point:
1059 // consider X== -0, Y== +0.
1060 // It becomes safe if either operand is a nonzero constant.
1061 ConstantFP *CFPt, *CFPf;
1062 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1063 !CFPt->getValueAPF().isZero()) ||
1064 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1065 !CFPf->getValueAPF().isZero()))
1066 return ReplaceInstUsesWith(SI, FalseVal);
1068 // Transform (X une Y) ? Y : X -> Y
1069 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1070 // This is not safe in general for floating point:
1071 // consider X== -0, Y== +0.
1072 // It becomes safe if either operand is a nonzero constant.
1073 ConstantFP *CFPt, *CFPf;
1074 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1075 !CFPt->getValueAPF().isZero()) ||
1076 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1077 !CFPf->getValueAPF().isZero()))
1078 return ReplaceInstUsesWith(SI, TrueVal);
1081 // Canonicalize to use ordered comparisons by swapping the select
1085 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1086 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1087 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1088 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1089 FCI->getName() + ".inv");
1091 return SelectInst::Create(NewCond, FalseVal, TrueVal,
1092 SI.getName() + ".p");
1095 // NOTE: if we wanted to, this is where to detect MIN/MAX
1097 // NOTE: if we wanted to, this is where to detect ABS
1100 // See if we are selecting two values based on a comparison of the two values.
1101 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1102 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
1105 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
1106 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
1107 if (TI->hasOneUse() && FI->hasOneUse()) {
1108 Instruction *AddOp = nullptr, *SubOp = nullptr;
1110 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1111 if (TI->getOpcode() == FI->getOpcode())
1112 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
1115 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
1116 // even legal for FP.
1117 if ((TI->getOpcode() == Instruction::Sub &&
1118 FI->getOpcode() == Instruction::Add) ||
1119 (TI->getOpcode() == Instruction::FSub &&
1120 FI->getOpcode() == Instruction::FAdd)) {
1121 AddOp = FI; SubOp = TI;
1122 } else if ((FI->getOpcode() == Instruction::Sub &&
1123 TI->getOpcode() == Instruction::Add) ||
1124 (FI->getOpcode() == Instruction::FSub &&
1125 TI->getOpcode() == Instruction::FAdd)) {
1126 AddOp = TI; SubOp = FI;
1130 Value *OtherAddOp = nullptr;
1131 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1132 OtherAddOp = AddOp->getOperand(1);
1133 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1134 OtherAddOp = AddOp->getOperand(0);
1138 // So at this point we know we have (Y -> OtherAddOp):
1139 // select C, (add X, Y), (sub X, Z)
1140 Value *NegVal; // Compute -Z
1141 if (SI.getType()->isFPOrFPVectorTy()) {
1142 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
1143 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1144 FastMathFlags Flags = AddOp->getFastMathFlags();
1145 Flags &= SubOp->getFastMathFlags();
1146 NegInst->setFastMathFlags(Flags);
1149 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
1152 Value *NewTrueOp = OtherAddOp;
1153 Value *NewFalseOp = NegVal;
1155 std::swap(NewTrueOp, NewFalseOp);
1157 Builder->CreateSelect(CondVal, NewTrueOp,
1158 NewFalseOp, SI.getName() + ".p");
1160 if (SI.getType()->isFPOrFPVectorTy()) {
1162 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1164 FastMathFlags Flags = AddOp->getFastMathFlags();
1165 Flags &= SubOp->getFastMathFlags();
1166 RI->setFastMathFlags(Flags);
1169 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1174 // See if we can fold the select into one of our operands.
1175 if (SI.getType()->isIntOrIntVectorTy()) {
1176 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1179 Value *LHS, *RHS, *LHS2, *RHS2;
1180 Instruction::CastOps CastOp;
1181 SelectPatternFlavor SPF = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1184 // Canonicalize so that type casts are outside select patterns.
1185 if (LHS->getType()->getPrimitiveSizeInBits() !=
1186 SI.getType()->getPrimitiveSizeInBits()) {
1187 CmpInst::Predicate Pred = getICmpPredicateForMinMax(SPF);
1188 Value *Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1189 Value *NewSI = Builder->CreateCast(CastOp,
1190 Builder->CreateSelect(Cmp, LHS, RHS),
1192 return ReplaceInstUsesWith(SI, NewSI);
1195 // MAX(MAX(a, b), a) -> MAX(a, b)
1196 // MIN(MIN(a, b), a) -> MIN(a, b)
1197 // MAX(MIN(a, b), a) -> a
1198 // MIN(MAX(a, b), a) -> a
1199 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2))
1200 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1203 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2))
1204 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1209 // MAX(~a, ~b) -> ~MIN(a, b)
1210 if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1211 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1212 IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1214 // This transform adds a xor operation and that extra cost needs to be
1215 // justified. We look for simplifications that will result from
1216 // applying this rule:
1219 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1220 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1221 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1224 Value *NewLHS = Builder->CreateNot(LHS);
1225 Value *NewRHS = Builder->CreateNot(RHS);
1226 Value *NewCmp = SPF == SPF_SMAX
1227 ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1228 : Builder->CreateICmpULT(NewLHS, NewRHS);
1230 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1231 return ReplaceInstUsesWith(SI, NewSI);
1237 // ABS(-X) -> ABS(X)
1240 // See if we can fold the select into a phi node if the condition is a select.
1241 if (isa<PHINode>(SI.getCondition()))
1242 // The true/false values have to be live in the PHI predecessor's blocks.
1243 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1244 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1245 if (Instruction *NV = FoldOpIntoPhi(SI))
1248 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1249 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1250 // select(C, select(C, a, b), c) -> select(C, a, c)
1251 if (TrueSI->getCondition() == CondVal) {
1252 if (SI.getTrueValue() == TrueSI->getTrueValue())
1254 SI.setOperand(1, TrueSI->getTrueValue());
1257 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1258 // We choose this as normal form to enable folding on the And and shortening
1259 // paths for the values (this helps GetUnderlyingObjects() for example).
1260 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1261 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1262 SI.setOperand(0, And);
1263 SI.setOperand(1, TrueSI->getTrueValue());
1268 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1269 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1270 // select(C, a, select(C, b, c)) -> select(C, a, c)
1271 if (FalseSI->getCondition() == CondVal) {
1272 if (SI.getFalseValue() == FalseSI->getFalseValue())
1274 SI.setOperand(2, FalseSI->getFalseValue());
1277 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1278 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1279 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1280 SI.setOperand(0, Or);
1281 SI.setOperand(2, FalseSI->getFalseValue());
1287 if (BinaryOperator::isNot(CondVal)) {
1288 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1289 SI.setOperand(1, FalseVal);
1290 SI.setOperand(2, TrueVal);
1294 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
1295 unsigned VWidth = VecTy->getNumElements();
1296 APInt UndefElts(VWidth, 0);
1297 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1298 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1300 return ReplaceInstUsesWith(SI, V);
1304 if (isa<ConstantAggregateZero>(CondVal)) {
1305 return ReplaceInstUsesWith(SI, FalseVal);