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 "InstCombine.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/PatternMatch.h"
19 using namespace PatternMatch;
21 #define DEBUG_TYPE "instcombine"
23 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
24 /// returning the kind and providing the out parameter results if we
25 /// successfully match.
26 static SelectPatternFlavor
27 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
28 SelectInst *SI = dyn_cast<SelectInst>(V);
29 if (!SI) return SPF_UNKNOWN;
31 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
32 if (!ICI) return SPF_UNKNOWN;
34 LHS = ICI->getOperand(0);
35 RHS = ICI->getOperand(1);
37 // (icmp X, Y) ? X : Y
38 if (SI->getTrueValue() == ICI->getOperand(0) &&
39 SI->getFalseValue() == ICI->getOperand(1)) {
40 switch (ICI->getPredicate()) {
41 default: return SPF_UNKNOWN; // Equality.
42 case ICmpInst::ICMP_UGT:
43 case ICmpInst::ICMP_UGE: return SPF_UMAX;
44 case ICmpInst::ICMP_SGT:
45 case ICmpInst::ICMP_SGE: return SPF_SMAX;
46 case ICmpInst::ICMP_ULT:
47 case ICmpInst::ICMP_ULE: return SPF_UMIN;
48 case ICmpInst::ICMP_SLT:
49 case ICmpInst::ICMP_SLE: return SPF_SMIN;
53 // (icmp X, Y) ? Y : X
54 if (SI->getTrueValue() == ICI->getOperand(1) &&
55 SI->getFalseValue() == ICI->getOperand(0)) {
56 switch (ICI->getPredicate()) {
57 default: return SPF_UNKNOWN; // Equality.
58 case ICmpInst::ICMP_UGT:
59 case ICmpInst::ICMP_UGE: return SPF_UMIN;
60 case ICmpInst::ICMP_SGT:
61 case ICmpInst::ICMP_SGE: return SPF_SMIN;
62 case ICmpInst::ICMP_ULT:
63 case ICmpInst::ICMP_ULE: return SPF_UMAX;
64 case ICmpInst::ICMP_SLT:
65 case ICmpInst::ICMP_SLE: return SPF_SMAX;
69 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
75 /// GetSelectFoldableOperands - We want to turn code that looks like this:
77 /// %D = select %cond, %C, %A
79 /// %C = select %cond, %B, 0
82 /// Assuming that the specified instruction is an operand to the select, return
83 /// a bitmask indicating which operands of this instruction are foldable if they
84 /// equal the other incoming value of the select.
86 static unsigned GetSelectFoldableOperands(Instruction *I) {
87 switch (I->getOpcode()) {
88 case Instruction::Add:
89 case Instruction::Mul:
90 case Instruction::And:
92 case Instruction::Xor:
93 return 3; // Can fold through either operand.
94 case Instruction::Sub: // Can only fold on the amount subtracted.
95 case Instruction::Shl: // Can only fold on the shift amount.
96 case Instruction::LShr:
97 case Instruction::AShr:
100 return 0; // Cannot fold
104 /// GetSelectFoldableConstant - For the same transformation as the previous
105 /// function, return the identity constant that goes into the select.
106 static Constant *GetSelectFoldableConstant(Instruction *I) {
107 switch (I->getOpcode()) {
108 default: llvm_unreachable("This cannot happen!");
109 case Instruction::Add:
110 case Instruction::Sub:
111 case Instruction::Or:
112 case Instruction::Xor:
113 case Instruction::Shl:
114 case Instruction::LShr:
115 case Instruction::AShr:
116 return Constant::getNullValue(I->getType());
117 case Instruction::And:
118 return Constant::getAllOnesValue(I->getType());
119 case Instruction::Mul:
120 return ConstantInt::get(I->getType(), 1);
124 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
125 /// have the same opcode and only one use each. Try to simplify this.
126 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 if (TI->getNumOperands() == 1) {
129 // If this is a non-volatile load or a cast from the same type,
132 Type *FIOpndTy = FI->getOperand(0)->getType();
133 if (TI->getOperand(0)->getType() != FIOpndTy)
135 // The select condition may be a vector. We may only change the operand
136 // type if the vector width remains the same (and matches the condition).
137 Type *CondTy = SI.getCondition()->getType();
138 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
139 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
142 return nullptr; // unknown unary op.
145 // Fold this by inserting a select from the input values.
146 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
147 FI->getOperand(0), SI.getName()+".v");
148 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
152 // Only handle binary operators here.
153 if (!isa<BinaryOperator>(TI))
156 // Figure out if the operations have any operands in common.
157 Value *MatchOp, *OtherOpT, *OtherOpF;
159 if (TI->getOperand(0) == FI->getOperand(0)) {
160 MatchOp = TI->getOperand(0);
161 OtherOpT = TI->getOperand(1);
162 OtherOpF = FI->getOperand(1);
163 MatchIsOpZero = true;
164 } else if (TI->getOperand(1) == FI->getOperand(1)) {
165 MatchOp = TI->getOperand(1);
166 OtherOpT = TI->getOperand(0);
167 OtherOpF = FI->getOperand(0);
168 MatchIsOpZero = false;
169 } else if (!TI->isCommutative()) {
171 } else if (TI->getOperand(0) == FI->getOperand(1)) {
172 MatchOp = TI->getOperand(0);
173 OtherOpT = TI->getOperand(1);
174 OtherOpF = FI->getOperand(0);
175 MatchIsOpZero = true;
176 } else if (TI->getOperand(1) == FI->getOperand(0)) {
177 MatchOp = TI->getOperand(1);
178 OtherOpT = TI->getOperand(0);
179 OtherOpF = FI->getOperand(1);
180 MatchIsOpZero = true;
185 // If we reach here, they do have operations in common.
186 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
187 OtherOpF, SI.getName()+".v");
189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
191 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
193 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
195 llvm_unreachable("Shouldn't get here");
198 static bool isSelect01(Constant *C1, Constant *C2) {
199 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
202 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
205 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
207 return C1I->isOne() || C1I->isAllOnesValue() ||
208 C2I->isOne() || C2I->isAllOnesValue();
211 /// FoldSelectIntoOp - Try fold the select into one of the operands to
212 /// facilitate further optimization.
213 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
215 // See the comment above GetSelectFoldableOperands for a description of the
216 // transformation we are doing here.
217 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
218 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
219 !isa<Constant>(FalseVal)) {
220 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
221 unsigned OpToFold = 0;
222 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
224 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
229 Constant *C = GetSelectFoldableConstant(TVI);
230 Value *OOp = TVI->getOperand(2-OpToFold);
231 // Avoid creating select between 2 constants unless it's selecting
232 // between 0, 1 and -1.
233 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
234 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
235 NewSel->takeName(TVI);
236 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
237 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
239 if (isa<PossiblyExactOperator>(BO))
240 BO->setIsExact(TVI_BO->isExact());
241 if (isa<OverflowingBinaryOperator>(BO)) {
242 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
243 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
252 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
253 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
254 !isa<Constant>(TrueVal)) {
255 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
256 unsigned OpToFold = 0;
257 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
259 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
264 Constant *C = GetSelectFoldableConstant(FVI);
265 Value *OOp = FVI->getOperand(2-OpToFold);
266 // Avoid creating select between 2 constants unless it's selecting
267 // between 0, 1 and -1.
268 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
269 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
270 NewSel->takeName(FVI);
271 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
272 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
274 if (isa<PossiblyExactOperator>(BO))
275 BO->setIsExact(FVI_BO->isExact());
276 if (isa<OverflowingBinaryOperator>(BO)) {
277 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
278 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
290 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
291 /// replaced with RepOp.
292 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
293 const DataLayout *TD,
294 const TargetLibraryInfo *TLI) {
295 // Trivial replacement.
299 Instruction *I = dyn_cast<Instruction>(V);
303 // If this is a binary operator, try to simplify it with the replaced op.
304 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
305 if (B->getOperand(0) == Op)
306 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
307 if (B->getOperand(1) == Op)
308 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
311 // Same for CmpInsts.
312 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
313 if (C->getOperand(0) == Op)
314 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
316 if (C->getOperand(1) == Op)
317 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
321 // TODO: We could hand off more cases to instsimplify here.
323 // If all operands are constant after substituting Op for RepOp then we can
324 // constant fold the instruction.
325 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
326 // Build a list of all constant operands.
327 SmallVector<Constant*, 8> ConstOps;
328 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
329 if (I->getOperand(i) == Op)
330 ConstOps.push_back(CRepOp);
331 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
332 ConstOps.push_back(COp);
337 // All operands were constants, fold it.
338 if (ConstOps.size() == I->getNumOperands()) {
339 if (CmpInst *C = dyn_cast<CmpInst>(I))
340 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
341 ConstOps[1], TD, TLI);
343 if (LoadInst *LI = dyn_cast<LoadInst>(I))
344 if (!LI->isVolatile())
345 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
347 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
355 /// foldSelectICmpAndOr - We want to turn:
356 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
358 /// (or (shl (and X, C1), C3), y)
360 /// C1 and C2 are both powers of 2
362 /// C3 = Log(C2) - Log(C1)
364 /// This transform handles cases where:
365 /// 1. The icmp predicate is inverted
366 /// 2. The select operands are reversed
367 /// 3. The magnitude of C2 and C1 are flipped
369 /// This also tries to turn
370 /// --- Single bit tests:
371 /// if ((x & C) == 0) x |= C to x |= C
372 /// if ((x & C) != 0) x ^= C to x &= ~C
373 /// if ((x & C) == 0) x ^= C to x |= C
374 /// if ((x & C) != 0) x &= ~C to x &= ~C
375 /// if ((x & C) == 0) x &= ~C to nothing
376 static Value *foldSelectICmpAndOr(SelectInst &SI, Value *TrueVal,
378 InstCombiner::BuilderTy *Builder) {
379 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
380 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
383 Value *CmpLHS = IC->getOperand(0);
384 Value *CmpRHS = IC->getOperand(1);
386 if (!match(CmpRHS, m_Zero()))
391 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
396 // if ((x & C) != 0) x ^= C becomes x &= ~C
397 if (match(FalseVal, m_Xor(m_Specific(TrueVal), m_APInt(C2))) && C1 == C2) {
398 return Builder->CreateAnd(TrueVal, ~(*C1));
401 // if ((x & C) == 0) x ^= C becomes x |= C
402 if (match(TrueVal, m_Xor(m_Specific(FalseVal), m_APInt(C2))) && C1 == C2) {
403 return Builder->CreateOr(FalseVal, *C1);
406 // if ((x & C) != 0) x &= ~C becomes x &= ~C
407 // if ((x & C) == 0) x &= ~C becomes nothing
408 if ((match(FalseVal, m_And(m_Specific(TrueVal), m_APInt(C2))) ||
409 match(TrueVal, m_And(m_Specific(FalseVal), m_APInt(C2)))) &&
414 bool OrOnFalseVal = false;
415 bool OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
417 // if ((x & C) == 0) x |= C becomes x |= C
418 if (OrOnTrueVal && C1 == C2)
422 OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
424 if (!OrOnFalseVal && !OrOnTrueVal)
428 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
430 unsigned C1Log = C1->logBase2();
431 unsigned C2Log = C2->logBase2();
433 V = Builder->CreateZExtOrTrunc(V, Y->getType());
434 V = Builder->CreateShl(V, C2Log - C1Log);
435 } else if (C1Log > C2Log) {
436 V = Builder->CreateLShr(V, C1Log - C2Log);
437 V = Builder->CreateZExtOrTrunc(V, Y->getType());
439 V = Builder->CreateZExtOrTrunc(V, Y->getType());
441 ICmpInst::Predicate Pred = IC->getPredicate();
442 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
443 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
444 V = Builder->CreateXor(V, *C2);
446 return Builder->CreateOr(V, Y);
449 /// visitSelectInstWithICmp - Visit a SelectInst that has an
450 /// ICmpInst as its first operand.
452 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
454 bool Changed = false;
455 ICmpInst::Predicate Pred = ICI->getPredicate();
456 Value *CmpLHS = ICI->getOperand(0);
457 Value *CmpRHS = ICI->getOperand(1);
458 Value *TrueVal = SI.getTrueValue();
459 Value *FalseVal = SI.getFalseValue();
461 // Check cases where the comparison is with a constant that
462 // can be adjusted to fit the min/max idiom. We may move or edit ICI
463 // here, so make sure the select is the only user.
464 if (ICI->hasOneUse())
465 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
466 // X < MIN ? T : F --> F
467 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
468 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
469 return ReplaceInstUsesWith(SI, FalseVal);
470 // X > MAX ? T : F --> F
471 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
472 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
473 return ReplaceInstUsesWith(SI, FalseVal);
476 case ICmpInst::ICMP_ULT:
477 case ICmpInst::ICMP_SLT:
478 case ICmpInst::ICMP_UGT:
479 case ICmpInst::ICMP_SGT: {
480 // These transformations only work for selects over integers.
481 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
485 Constant *AdjustedRHS;
486 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
487 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
488 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
489 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
491 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
492 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
493 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
494 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
495 ; // Nothing to do here. Values match without any sign/zero extension.
497 // Types do not match. Instead of calculating this with mixed types
498 // promote all to the larger type. This enables scalar evolution to
499 // analyze this expression.
500 else if (CmpRHS->getType()->getScalarSizeInBits()
501 < SelectTy->getBitWidth()) {
502 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
504 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
505 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
506 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
507 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
508 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
509 sextRHS == FalseVal) {
511 AdjustedRHS = sextRHS;
512 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
513 sextRHS == TrueVal) {
515 AdjustedRHS = sextRHS;
516 } else if (ICI->isUnsigned()) {
517 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
518 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
519 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
520 // zext + signed compare cannot be changed:
521 // 0xff <s 0x00, but 0x00ff >s 0x0000
522 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
523 zextRHS == FalseVal) {
525 AdjustedRHS = zextRHS;
526 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
527 zextRHS == TrueVal) {
529 AdjustedRHS = zextRHS;
537 Pred = ICmpInst::getSwappedPredicate(Pred);
538 CmpRHS = AdjustedRHS;
539 std::swap(FalseVal, TrueVal);
540 ICI->setPredicate(Pred);
541 ICI->setOperand(0, CmpLHS);
542 ICI->setOperand(1, CmpRHS);
543 SI.setOperand(1, TrueVal);
544 SI.setOperand(2, FalseVal);
546 // Move ICI instruction right before the select instruction. Otherwise
547 // the sext/zext value may be defined after the ICI instruction uses it.
548 ICI->moveBefore(&SI);
556 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
557 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
558 // FIXME: Type and constness constraints could be lifted, but we have to
559 // watch code size carefully. We should consider xor instead of
560 // sub/add when we decide to do that.
561 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
562 if (TrueVal->getType() == Ty) {
563 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
564 ConstantInt *C1 = nullptr, *C2 = nullptr;
565 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
566 C1 = dyn_cast<ConstantInt>(TrueVal);
567 C2 = dyn_cast<ConstantInt>(FalseVal);
568 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
569 C1 = dyn_cast<ConstantInt>(FalseVal);
570 C2 = dyn_cast<ConstantInt>(TrueVal);
573 // This shift results in either -1 or 0.
574 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
576 // Check if we can express the operation with a single or.
577 if (C2->isAllOnesValue())
578 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
580 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
581 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
587 // If we have an equality comparison then we know the value in one of the
588 // arms of the select. See if substituting this value into the arm and
589 // simplifying the result yields the same value as the other arm.
590 if (Pred == ICmpInst::ICMP_EQ) {
591 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
592 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
593 return ReplaceInstUsesWith(SI, FalseVal);
594 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
595 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
596 return ReplaceInstUsesWith(SI, FalseVal);
597 } else if (Pred == ICmpInst::ICMP_NE) {
598 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
599 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
600 return ReplaceInstUsesWith(SI, TrueVal);
601 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
602 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
603 return ReplaceInstUsesWith(SI, TrueVal);
606 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
608 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
609 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
610 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
611 SI.setOperand(1, CmpRHS);
613 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
614 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
615 SI.setOperand(2, CmpRHS);
620 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
621 return ReplaceInstUsesWith(SI, V);
623 return Changed ? &SI : nullptr;
627 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
628 /// PHI node (but the two may be in different blocks). See if the true/false
629 /// values (V) are live in all of the predecessor blocks of the PHI. For
630 /// example, cases like this cannot be mapped:
632 /// X = phi [ C1, BB1], [C2, BB2]
634 /// Z = select X, Y, 0
636 /// because Y is not live in BB1/BB2.
638 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
639 const SelectInst &SI) {
640 // If the value is a non-instruction value like a constant or argument, it
641 // can always be mapped.
642 const Instruction *I = dyn_cast<Instruction>(V);
645 // If V is a PHI node defined in the same block as the condition PHI, we can
646 // map the arguments.
647 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
649 if (const PHINode *VP = dyn_cast<PHINode>(I))
650 if (VP->getParent() == CondPHI->getParent())
653 // Otherwise, if the PHI and select are defined in the same block and if V is
654 // defined in a different block, then we can transform it.
655 if (SI.getParent() == CondPHI->getParent() &&
656 I->getParent() != CondPHI->getParent())
659 // Otherwise we have a 'hard' case and we can't tell without doing more
660 // detailed dominator based analysis, punt.
664 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
665 /// SPF2(SPF1(A, B), C)
666 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
667 SelectPatternFlavor SPF1,
670 SelectPatternFlavor SPF2, Value *C) {
671 if (C == A || C == B) {
672 // MAX(MAX(A, B), B) -> MAX(A, B)
673 // MIN(MIN(a, b), a) -> MIN(a, b)
675 return ReplaceInstUsesWith(Outer, Inner);
677 // MAX(MIN(a, b), a) -> a
678 // MIN(MAX(a, b), a) -> a
679 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
680 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
681 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
682 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
683 return ReplaceInstUsesWith(Outer, C);
686 // TODO: MIN(MIN(A, 23), 97)
691 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
692 /// both be) and we have an icmp instruction with zero, and we have an 'and'
693 /// with the non-constant value and a power of two we can turn the select
694 /// into a shift on the result of the 'and'.
695 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
696 ConstantInt *FalseVal,
697 InstCombiner::BuilderTy *Builder) {
698 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
699 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
702 if (!match(IC->getOperand(1), m_Zero()))
706 Value *LHS = IC->getOperand(0);
707 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
710 // If both select arms are non-zero see if we have a select of the form
711 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
712 // for 'x ? 2^n : 0' and fix the thing up at the end.
713 ConstantInt *Offset = nullptr;
714 if (!TrueVal->isZero() && !FalseVal->isZero()) {
715 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
717 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
722 // Adjust TrueVal and FalseVal to the offset.
723 TrueVal = ConstantInt::get(Builder->getContext(),
724 TrueVal->getValue() - Offset->getValue());
725 FalseVal = ConstantInt::get(Builder->getContext(),
726 FalseVal->getValue() - Offset->getValue());
729 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
730 if (!AndRHS->getValue().isPowerOf2() ||
731 (!TrueVal->getValue().isPowerOf2() &&
732 !FalseVal->getValue().isPowerOf2()))
735 // Determine which shift is needed to transform result of the 'and' into the
737 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
738 unsigned ValZeros = ValC->getValue().logBase2();
739 unsigned AndZeros = AndRHS->getValue().logBase2();
741 // If types don't match we can still convert the select by introducing a zext
742 // or a trunc of the 'and'. The trunc case requires that all of the truncated
743 // bits are zero, we can figure that out by looking at the 'and' mask.
744 if (AndZeros >= ValC->getBitWidth())
747 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
748 if (ValZeros > AndZeros)
749 V = Builder->CreateShl(V, ValZeros - AndZeros);
750 else if (ValZeros < AndZeros)
751 V = Builder->CreateLShr(V, AndZeros - ValZeros);
753 // Okay, now we know that everything is set up, we just don't know whether we
754 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
755 bool ShouldNotVal = !TrueVal->isZero();
756 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
758 V = Builder->CreateXor(V, ValC);
760 // Apply an offset if needed.
762 V = Builder->CreateAdd(V, Offset);
766 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
767 Value *CondVal = SI.getCondition();
768 Value *TrueVal = SI.getTrueValue();
769 Value *FalseVal = SI.getFalseValue();
771 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL))
772 return ReplaceInstUsesWith(SI, V);
774 if (SI.getType()->isIntegerTy(1)) {
775 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
776 if (C->getZExtValue()) {
777 // Change: A = select B, true, C --> A = or B, C
778 return BinaryOperator::CreateOr(CondVal, FalseVal);
780 // Change: A = select B, false, C --> A = and !B, C
781 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
782 return BinaryOperator::CreateAnd(NotCond, FalseVal);
784 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
785 if (C->getZExtValue() == false) {
786 // Change: A = select B, C, false --> A = and B, C
787 return BinaryOperator::CreateAnd(CondVal, TrueVal);
789 // Change: A = select B, C, true --> A = or !B, C
790 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
791 return BinaryOperator::CreateOr(NotCond, TrueVal);
794 // select a, b, a -> a&b
795 // select a, a, b -> a|b
796 if (CondVal == TrueVal)
797 return BinaryOperator::CreateOr(CondVal, FalseVal);
798 if (CondVal == FalseVal)
799 return BinaryOperator::CreateAnd(CondVal, TrueVal);
801 // select a, ~a, b -> (~a)&b
802 // select a, b, ~a -> (~a)|b
803 if (match(TrueVal, m_Not(m_Specific(CondVal))))
804 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
805 if (match(FalseVal, m_Not(m_Specific(CondVal))))
806 return BinaryOperator::CreateOr(TrueVal, FalseVal);
809 // Selecting between two integer constants?
810 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
811 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
812 // select C, 1, 0 -> zext C to int
813 if (FalseValC->isZero() && TrueValC->getValue() == 1)
814 return new ZExtInst(CondVal, SI.getType());
816 // select C, -1, 0 -> sext C to int
817 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
818 return new SExtInst(CondVal, SI.getType());
820 // select C, 0, 1 -> zext !C to int
821 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
822 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
823 return new ZExtInst(NotCond, SI.getType());
826 // select C, 0, -1 -> sext !C to int
827 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
828 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
829 return new SExtInst(NotCond, SI.getType());
832 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
833 return ReplaceInstUsesWith(SI, V);
836 // See if we are selecting two values based on a comparison of the two values.
837 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
838 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
839 // Transform (X == Y) ? X : Y -> Y
840 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
841 // This is not safe in general for floating point:
842 // consider X== -0, Y== +0.
843 // It becomes safe if either operand is a nonzero constant.
844 ConstantFP *CFPt, *CFPf;
845 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
846 !CFPt->getValueAPF().isZero()) ||
847 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
848 !CFPf->getValueAPF().isZero()))
849 return ReplaceInstUsesWith(SI, FalseVal);
851 // Transform (X une Y) ? X : Y -> X
852 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
853 // This is not safe in general for floating point:
854 // consider X== -0, Y== +0.
855 // It becomes safe if either operand is a nonzero constant.
856 ConstantFP *CFPt, *CFPf;
857 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
858 !CFPt->getValueAPF().isZero()) ||
859 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
860 !CFPf->getValueAPF().isZero()))
861 return ReplaceInstUsesWith(SI, TrueVal);
863 // NOTE: if we wanted to, this is where to detect MIN/MAX
865 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
866 // Transform (X == Y) ? Y : X -> X
867 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
868 // This is not safe in general for floating point:
869 // consider X== -0, Y== +0.
870 // It becomes safe if either operand is a nonzero constant.
871 ConstantFP *CFPt, *CFPf;
872 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
873 !CFPt->getValueAPF().isZero()) ||
874 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
875 !CFPf->getValueAPF().isZero()))
876 return ReplaceInstUsesWith(SI, FalseVal);
878 // Transform (X une Y) ? Y : X -> Y
879 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
880 // This is not safe in general for floating point:
881 // consider X== -0, Y== +0.
882 // It becomes safe if either operand is a nonzero constant.
883 ConstantFP *CFPt, *CFPf;
884 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
885 !CFPt->getValueAPF().isZero()) ||
886 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
887 !CFPf->getValueAPF().isZero()))
888 return ReplaceInstUsesWith(SI, TrueVal);
890 // NOTE: if we wanted to, this is where to detect MIN/MAX
892 // NOTE: if we wanted to, this is where to detect ABS
895 // See if we are selecting two values based on a comparison of the two values.
896 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
897 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
900 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
901 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
902 if (TI->hasOneUse() && FI->hasOneUse()) {
903 Instruction *AddOp = nullptr, *SubOp = nullptr;
905 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
906 if (TI->getOpcode() == FI->getOpcode())
907 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
910 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
911 // even legal for FP.
912 if ((TI->getOpcode() == Instruction::Sub &&
913 FI->getOpcode() == Instruction::Add) ||
914 (TI->getOpcode() == Instruction::FSub &&
915 FI->getOpcode() == Instruction::FAdd)) {
916 AddOp = FI; SubOp = TI;
917 } else if ((FI->getOpcode() == Instruction::Sub &&
918 TI->getOpcode() == Instruction::Add) ||
919 (FI->getOpcode() == Instruction::FSub &&
920 TI->getOpcode() == Instruction::FAdd)) {
921 AddOp = TI; SubOp = FI;
925 Value *OtherAddOp = nullptr;
926 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
927 OtherAddOp = AddOp->getOperand(1);
928 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
929 OtherAddOp = AddOp->getOperand(0);
933 // So at this point we know we have (Y -> OtherAddOp):
934 // select C, (add X, Y), (sub X, Z)
935 Value *NegVal; // Compute -Z
936 if (SI.getType()->isFPOrFPVectorTy()) {
937 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
938 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
939 FastMathFlags Flags = AddOp->getFastMathFlags();
940 Flags &= SubOp->getFastMathFlags();
941 NegInst->setFastMathFlags(Flags);
944 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
947 Value *NewTrueOp = OtherAddOp;
948 Value *NewFalseOp = NegVal;
950 std::swap(NewTrueOp, NewFalseOp);
952 Builder->CreateSelect(CondVal, NewTrueOp,
953 NewFalseOp, SI.getName() + ".p");
955 if (SI.getType()->isFPOrFPVectorTy()) {
957 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
959 FastMathFlags Flags = AddOp->getFastMathFlags();
960 Flags &= SubOp->getFastMathFlags();
961 RI->setFastMathFlags(Flags);
964 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
969 // See if we can fold the select into one of our operands.
970 if (SI.getType()->isIntegerTy()) {
971 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
974 // MAX(MAX(a, b), a) -> MAX(a, b)
975 // MIN(MIN(a, b), a) -> MIN(a, b)
976 // MAX(MIN(a, b), a) -> a
977 // MIN(MAX(a, b), a) -> a
978 Value *LHS, *RHS, *LHS2, *RHS2;
979 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
980 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
981 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
984 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
985 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
992 // ABS(ABS(X)) -> ABS(X)
995 // See if we can fold the select into a phi node if the condition is a select.
996 if (isa<PHINode>(SI.getCondition()))
997 // The true/false values have to be live in the PHI predecessor's blocks.
998 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
999 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1000 if (Instruction *NV = FoldOpIntoPhi(SI))
1003 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1004 if (TrueSI->getCondition() == CondVal) {
1005 if (SI.getTrueValue() == TrueSI->getTrueValue())
1007 SI.setOperand(1, TrueSI->getTrueValue());
1011 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1012 if (FalseSI->getCondition() == CondVal) {
1013 if (SI.getFalseValue() == FalseSI->getFalseValue())
1015 SI.setOperand(2, FalseSI->getFalseValue());
1020 if (BinaryOperator::isNot(CondVal)) {
1021 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1022 SI.setOperand(1, FalseVal);
1023 SI.setOperand(2, TrueVal);
1027 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
1028 unsigned VWidth = VecTy->getNumElements();
1029 APInt UndefElts(VWidth, 0);
1030 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1031 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1033 return ReplaceInstUsesWith(SI, V);
1037 if (isa<ConstantAggregateZero>(CondVal)) {
1038 return ReplaceInstUsesWith(SI, FalseVal);