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/Support/PatternMatch.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
19 using namespace PatternMatch;
21 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
22 /// returning the kind and providing the out parameter results if we
23 /// successfully match.
24 static SelectPatternFlavor
25 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
26 SelectInst *SI = dyn_cast<SelectInst>(V);
27 if (SI == 0) return SPF_UNKNOWN;
29 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
30 if (ICI == 0) return SPF_UNKNOWN;
32 LHS = ICI->getOperand(0);
33 RHS = ICI->getOperand(1);
35 // (icmp X, Y) ? X : Y
36 if (SI->getTrueValue() == ICI->getOperand(0) &&
37 SI->getFalseValue() == ICI->getOperand(1)) {
38 switch (ICI->getPredicate()) {
39 default: return SPF_UNKNOWN; // Equality.
40 case ICmpInst::ICMP_UGT:
41 case ICmpInst::ICMP_UGE: return SPF_UMAX;
42 case ICmpInst::ICMP_SGT:
43 case ICmpInst::ICMP_SGE: return SPF_SMAX;
44 case ICmpInst::ICMP_ULT:
45 case ICmpInst::ICMP_ULE: return SPF_UMIN;
46 case ICmpInst::ICMP_SLT:
47 case ICmpInst::ICMP_SLE: return SPF_SMIN;
51 // (icmp X, Y) ? Y : X
52 if (SI->getTrueValue() == ICI->getOperand(1) &&
53 SI->getFalseValue() == ICI->getOperand(0)) {
54 switch (ICI->getPredicate()) {
55 default: return SPF_UNKNOWN; // Equality.
56 case ICmpInst::ICMP_UGT:
57 case ICmpInst::ICMP_UGE: return SPF_UMIN;
58 case ICmpInst::ICMP_SGT:
59 case ICmpInst::ICMP_SGE: return SPF_SMIN;
60 case ICmpInst::ICMP_ULT:
61 case ICmpInst::ICMP_ULE: return SPF_UMAX;
62 case ICmpInst::ICMP_SLT:
63 case ICmpInst::ICMP_SLE: return SPF_SMAX;
67 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
73 /// GetSelectFoldableOperands - We want to turn code that looks like this:
75 /// %D = select %cond, %C, %A
77 /// %C = select %cond, %B, 0
80 /// Assuming that the specified instruction is an operand to the select, return
81 /// a bitmask indicating which operands of this instruction are foldable if they
82 /// equal the other incoming value of the select.
84 static unsigned GetSelectFoldableOperands(Instruction *I) {
85 switch (I->getOpcode()) {
86 case Instruction::Add:
87 case Instruction::Mul:
88 case Instruction::And:
90 case Instruction::Xor:
91 return 3; // Can fold through either operand.
92 case Instruction::Sub: // Can only fold on the amount subtracted.
93 case Instruction::Shl: // Can only fold on the shift amount.
94 case Instruction::LShr:
95 case Instruction::AShr:
98 return 0; // Cannot fold
102 /// GetSelectFoldableConstant - For the same transformation as the previous
103 /// function, return the identity constant that goes into the select.
104 static Constant *GetSelectFoldableConstant(Instruction *I) {
105 switch (I->getOpcode()) {
106 default: llvm_unreachable("This cannot happen!");
107 case Instruction::Add:
108 case Instruction::Sub:
109 case Instruction::Or:
110 case Instruction::Xor:
111 case Instruction::Shl:
112 case Instruction::LShr:
113 case Instruction::AShr:
114 return Constant::getNullValue(I->getType());
115 case Instruction::And:
116 return Constant::getAllOnesValue(I->getType());
117 case Instruction::Mul:
118 return ConstantInt::get(I->getType(), 1);
122 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
123 /// have the same opcode and only one use each. Try to simplify this.
124 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
126 if (TI->getNumOperands() == 1) {
127 // If this is a non-volatile load or a cast from the same type,
130 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
133 return 0; // unknown unary op.
136 // Fold this by inserting a select from the input values.
137 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
138 FI->getOperand(0), SI.getName()+".v");
139 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
143 // Only handle binary operators here.
144 if (!isa<BinaryOperator>(TI))
147 // Figure out if the operations have any operands in common.
148 Value *MatchOp, *OtherOpT, *OtherOpF;
150 if (TI->getOperand(0) == FI->getOperand(0)) {
151 MatchOp = TI->getOperand(0);
152 OtherOpT = TI->getOperand(1);
153 OtherOpF = FI->getOperand(1);
154 MatchIsOpZero = true;
155 } else if (TI->getOperand(1) == FI->getOperand(1)) {
156 MatchOp = TI->getOperand(1);
157 OtherOpT = TI->getOperand(0);
158 OtherOpF = FI->getOperand(0);
159 MatchIsOpZero = false;
160 } else if (!TI->isCommutative()) {
162 } else if (TI->getOperand(0) == FI->getOperand(1)) {
163 MatchOp = TI->getOperand(0);
164 OtherOpT = TI->getOperand(1);
165 OtherOpF = FI->getOperand(0);
166 MatchIsOpZero = true;
167 } else if (TI->getOperand(1) == FI->getOperand(0)) {
168 MatchOp = TI->getOperand(1);
169 OtherOpT = TI->getOperand(0);
170 OtherOpF = FI->getOperand(1);
171 MatchIsOpZero = true;
176 // If we reach here, they do have operations in common.
177 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
178 OtherOpF, SI.getName()+".v");
180 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
182 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
184 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
186 llvm_unreachable("Shouldn't get here");
190 static bool isSelect01(Constant *C1, Constant *C2) {
191 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
194 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
197 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
199 return C1I->isOne() || C1I->isAllOnesValue() ||
200 C2I->isOne() || C2I->isAllOnesValue();
203 /// FoldSelectIntoOp - Try fold the select into one of the operands to
204 /// facilitate further optimization.
205 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
207 // See the comment above GetSelectFoldableOperands for a description of the
208 // transformation we are doing here.
209 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
210 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
211 !isa<Constant>(FalseVal)) {
212 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
213 unsigned OpToFold = 0;
214 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
216 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
221 Constant *C = GetSelectFoldableConstant(TVI);
222 Value *OOp = TVI->getOperand(2-OpToFold);
223 // Avoid creating select between 2 constants unless it's selecting
224 // between 0, 1 and -1.
225 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
226 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
227 NewSel->takeName(TVI);
228 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
229 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
231 if (isa<PossiblyExactOperator>(BO))
232 BO->setIsExact(TVI_BO->isExact());
233 if (isa<OverflowingBinaryOperator>(BO)) {
234 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
235 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
244 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
245 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
246 !isa<Constant>(TrueVal)) {
247 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
248 unsigned OpToFold = 0;
249 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
251 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
256 Constant *C = GetSelectFoldableConstant(FVI);
257 Value *OOp = FVI->getOperand(2-OpToFold);
258 // Avoid creating select between 2 constants unless it's selecting
259 // between 0, 1 and -1.
260 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
261 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
262 NewSel->takeName(FVI);
263 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
264 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
266 if (isa<PossiblyExactOperator>(BO))
267 BO->setIsExact(FVI_BO->isExact());
268 if (isa<OverflowingBinaryOperator>(BO)) {
269 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
270 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
282 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
283 /// replaced with RepOp.
284 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
285 const TargetData *TD,
286 const TargetLibraryInfo *TLI) {
287 // Trivial replacement.
291 Instruction *I = dyn_cast<Instruction>(V);
295 // If this is a binary operator, try to simplify it with the replaced op.
296 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
297 if (B->getOperand(0) == Op)
298 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
299 if (B->getOperand(1) == Op)
300 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
303 // Same for CmpInsts.
304 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
305 if (C->getOperand(0) == Op)
306 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
308 if (C->getOperand(1) == Op)
309 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
313 // TODO: We could hand off more cases to instsimplify here.
315 // If all operands are constant after substituting Op for RepOp then we can
316 // constant fold the instruction.
317 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
318 // Build a list of all constant operands.
319 SmallVector<Constant*, 8> ConstOps;
320 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
321 if (I->getOperand(i) == Op)
322 ConstOps.push_back(CRepOp);
323 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
324 ConstOps.push_back(COp);
329 // All operands were constants, fold it.
330 if (ConstOps.size() == I->getNumOperands()) {
331 if (LoadInst *LI = dyn_cast<LoadInst>(I))
332 if (!LI->isVolatile())
333 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
335 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
343 /// visitSelectInstWithICmp - Visit a SelectInst that has an
344 /// ICmpInst as its first operand.
346 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
348 bool Changed = false;
349 ICmpInst::Predicate Pred = ICI->getPredicate();
350 Value *CmpLHS = ICI->getOperand(0);
351 Value *CmpRHS = ICI->getOperand(1);
352 Value *TrueVal = SI.getTrueValue();
353 Value *FalseVal = SI.getFalseValue();
355 // Check cases where the comparison is with a constant that
356 // can be adjusted to fit the min/max idiom. We may move or edit ICI
357 // here, so make sure the select is the only user.
358 if (ICI->hasOneUse())
359 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
360 // X < MIN ? T : F --> F
361 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
362 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
363 return ReplaceInstUsesWith(SI, FalseVal);
364 // X > MAX ? T : F --> F
365 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
366 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
367 return ReplaceInstUsesWith(SI, FalseVal);
370 case ICmpInst::ICMP_ULT:
371 case ICmpInst::ICMP_SLT:
372 case ICmpInst::ICMP_UGT:
373 case ICmpInst::ICMP_SGT: {
374 // These transformations only work for selects over integers.
375 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
379 Constant *AdjustedRHS;
380 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
381 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
382 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
383 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
385 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
386 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
387 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
388 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
389 ; // Nothing to do here. Values match without any sign/zero extension.
391 // Types do not match. Instead of calculating this with mixed types
392 // promote all to the larger type. This enables scalar evolution to
393 // analyze this expression.
394 else if (CmpRHS->getType()->getScalarSizeInBits()
395 < SelectTy->getBitWidth()) {
396 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
398 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
399 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
400 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
401 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
402 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
403 sextRHS == FalseVal) {
405 AdjustedRHS = sextRHS;
406 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
407 sextRHS == TrueVal) {
409 AdjustedRHS = sextRHS;
410 } else if (ICI->isUnsigned()) {
411 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
412 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
413 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
414 // zext + signed compare cannot be changed:
415 // 0xff <s 0x00, but 0x00ff >s 0x0000
416 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
417 zextRHS == FalseVal) {
419 AdjustedRHS = zextRHS;
420 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
421 zextRHS == TrueVal) {
423 AdjustedRHS = zextRHS;
431 Pred = ICmpInst::getSwappedPredicate(Pred);
432 CmpRHS = AdjustedRHS;
433 std::swap(FalseVal, TrueVal);
434 ICI->setPredicate(Pred);
435 ICI->setOperand(0, CmpLHS);
436 ICI->setOperand(1, CmpRHS);
437 SI.setOperand(1, TrueVal);
438 SI.setOperand(2, FalseVal);
440 // Move ICI instruction right before the select instruction. Otherwise
441 // the sext/zext value may be defined after the ICI instruction uses it.
442 ICI->moveBefore(&SI);
450 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
451 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
452 // FIXME: Type and constness constraints could be lifted, but we have to
453 // watch code size carefully. We should consider xor instead of
454 // sub/add when we decide to do that.
455 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
456 if (TrueVal->getType() == Ty) {
457 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
458 ConstantInt *C1 = NULL, *C2 = NULL;
459 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
460 C1 = dyn_cast<ConstantInt>(TrueVal);
461 C2 = dyn_cast<ConstantInt>(FalseVal);
462 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
463 C1 = dyn_cast<ConstantInt>(FalseVal);
464 C2 = dyn_cast<ConstantInt>(TrueVal);
467 // This shift results in either -1 or 0.
468 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
470 // Check if we can express the operation with a single or.
471 if (C2->isAllOnesValue())
472 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
474 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
475 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
481 // If we have an equality comparison then we know the value in one of the
482 // arms of the select. See if substituting this value into the arm and
483 // simplifying the result yields the same value as the other arm.
484 if (Pred == ICmpInst::ICMP_EQ) {
485 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
486 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
487 return ReplaceInstUsesWith(SI, FalseVal);
488 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
489 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
490 return ReplaceInstUsesWith(SI, FalseVal);
491 } else if (Pred == ICmpInst::ICMP_NE) {
492 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
493 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
494 return ReplaceInstUsesWith(SI, TrueVal);
495 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
496 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
497 return ReplaceInstUsesWith(SI, TrueVal);
500 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
502 if (isa<Constant>(CmpRHS)) {
503 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
504 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
505 SI.setOperand(1, CmpRHS);
507 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
508 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
509 SI.setOperand(2, CmpRHS);
514 return Changed ? &SI : 0;
518 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
519 /// PHI node (but the two may be in different blocks). See if the true/false
520 /// values (V) are live in all of the predecessor blocks of the PHI. For
521 /// example, cases like this cannot be mapped:
523 /// X = phi [ C1, BB1], [C2, BB2]
525 /// Z = select X, Y, 0
527 /// because Y is not live in BB1/BB2.
529 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
530 const SelectInst &SI) {
531 // If the value is a non-instruction value like a constant or argument, it
532 // can always be mapped.
533 const Instruction *I = dyn_cast<Instruction>(V);
534 if (I == 0) return true;
536 // If V is a PHI node defined in the same block as the condition PHI, we can
537 // map the arguments.
538 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
540 if (const PHINode *VP = dyn_cast<PHINode>(I))
541 if (VP->getParent() == CondPHI->getParent())
544 // Otherwise, if the PHI and select are defined in the same block and if V is
545 // defined in a different block, then we can transform it.
546 if (SI.getParent() == CondPHI->getParent() &&
547 I->getParent() != CondPHI->getParent())
550 // Otherwise we have a 'hard' case and we can't tell without doing more
551 // detailed dominator based analysis, punt.
555 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
556 /// SPF2(SPF1(A, B), C)
557 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
558 SelectPatternFlavor SPF1,
561 SelectPatternFlavor SPF2, Value *C) {
562 if (C == A || C == B) {
563 // MAX(MAX(A, B), B) -> MAX(A, B)
564 // MIN(MIN(a, b), a) -> MIN(a, b)
566 return ReplaceInstUsesWith(Outer, Inner);
568 // MAX(MIN(a, b), a) -> a
569 // MIN(MAX(a, b), a) -> a
570 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
571 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
572 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
573 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
574 return ReplaceInstUsesWith(Outer, C);
577 // TODO: MIN(MIN(A, 23), 97)
582 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
583 /// both be) and we have an icmp instruction with zero, and we have an 'and'
584 /// with the non-constant value and a power of two we can turn the select
585 /// into a shift on the result of the 'and'.
586 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
587 ConstantInt *FalseVal,
588 InstCombiner::BuilderTy *Builder) {
589 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
590 if (!IC || !IC->isEquality())
593 if (!match(IC->getOperand(1), m_Zero()))
597 Value *LHS = IC->getOperand(0);
598 if (LHS->getType() != SI.getType() ||
599 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
602 // If both select arms are non-zero see if we have a select of the form
603 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
604 // for 'x ? 2^n : 0' and fix the thing up at the end.
605 ConstantInt *Offset = 0;
606 if (!TrueVal->isZero() && !FalseVal->isZero()) {
607 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
609 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
614 // Adjust TrueVal and FalseVal to the offset.
615 TrueVal = ConstantInt::get(Builder->getContext(),
616 TrueVal->getValue() - Offset->getValue());
617 FalseVal = ConstantInt::get(Builder->getContext(),
618 FalseVal->getValue() - Offset->getValue());
621 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
622 if (!AndRHS->getValue().isPowerOf2() ||
623 (!TrueVal->getValue().isPowerOf2() &&
624 !FalseVal->getValue().isPowerOf2()))
627 // Determine which shift is needed to transform result of the 'and' into the
629 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
630 unsigned ValZeros = ValC->getValue().logBase2();
631 unsigned AndZeros = AndRHS->getValue().logBase2();
634 if (ValZeros > AndZeros)
635 V = Builder->CreateShl(V, ValZeros - AndZeros);
636 else if (ValZeros < AndZeros)
637 V = Builder->CreateLShr(V, AndZeros - ValZeros);
639 // Okay, now we know that everything is set up, we just don't know whether we
640 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
641 bool ShouldNotVal = !TrueVal->isZero();
642 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
644 V = Builder->CreateXor(V, ValC);
646 // Apply an offset if needed.
648 V = Builder->CreateAdd(V, Offset);
652 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
653 Value *CondVal = SI.getCondition();
654 Value *TrueVal = SI.getTrueValue();
655 Value *FalseVal = SI.getFalseValue();
657 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
658 return ReplaceInstUsesWith(SI, V);
660 if (SI.getType()->isIntegerTy(1)) {
661 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
662 if (C->getZExtValue()) {
663 // Change: A = select B, true, C --> A = or B, C
664 return BinaryOperator::CreateOr(CondVal, FalseVal);
666 // Change: A = select B, false, C --> A = and !B, C
667 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
668 return BinaryOperator::CreateAnd(NotCond, FalseVal);
669 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
670 if (C->getZExtValue() == false) {
671 // Change: A = select B, C, false --> A = and B, C
672 return BinaryOperator::CreateAnd(CondVal, TrueVal);
674 // Change: A = select B, C, true --> A = or !B, C
675 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
676 return BinaryOperator::CreateOr(NotCond, TrueVal);
679 // select a, b, a -> a&b
680 // select a, a, b -> a|b
681 if (CondVal == TrueVal)
682 return BinaryOperator::CreateOr(CondVal, FalseVal);
683 else if (CondVal == FalseVal)
684 return BinaryOperator::CreateAnd(CondVal, TrueVal);
686 // select a, ~a, b -> (~a)&b
687 // select a, b, ~a -> (~a)|b
688 if (match(TrueVal, m_Not(m_Specific(CondVal))))
689 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
690 else if (match(FalseVal, m_Not(m_Specific(CondVal))))
691 return BinaryOperator::CreateOr(TrueVal, FalseVal);
694 // Selecting between two integer constants?
695 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
696 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
697 // select C, 1, 0 -> zext C to int
698 if (FalseValC->isZero() && TrueValC->getValue() == 1)
699 return new ZExtInst(CondVal, SI.getType());
701 // select C, -1, 0 -> sext C to int
702 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
703 return new SExtInst(CondVal, SI.getType());
705 // select C, 0, 1 -> zext !C to int
706 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
707 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
708 return new ZExtInst(NotCond, SI.getType());
711 // select C, 0, -1 -> sext !C to int
712 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
713 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
714 return new SExtInst(NotCond, SI.getType());
717 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
718 return ReplaceInstUsesWith(SI, V);
721 // See if we are selecting two values based on a comparison of the two values.
722 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
723 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
724 // Transform (X == Y) ? X : Y -> Y
725 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
726 // This is not safe in general for floating point:
727 // consider X== -0, Y== +0.
728 // It becomes safe if either operand is a nonzero constant.
729 ConstantFP *CFPt, *CFPf;
730 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
731 !CFPt->getValueAPF().isZero()) ||
732 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
733 !CFPf->getValueAPF().isZero()))
734 return ReplaceInstUsesWith(SI, FalseVal);
736 // Transform (X une Y) ? X : Y -> X
737 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
738 // This is not safe in general for floating point:
739 // consider X== -0, Y== +0.
740 // It becomes safe if either operand is a nonzero constant.
741 ConstantFP *CFPt, *CFPf;
742 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
743 !CFPt->getValueAPF().isZero()) ||
744 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
745 !CFPf->getValueAPF().isZero()))
746 return ReplaceInstUsesWith(SI, TrueVal);
748 // NOTE: if we wanted to, this is where to detect MIN/MAX
750 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
751 // Transform (X == Y) ? Y : X -> X
752 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
753 // This is not safe in general for floating point:
754 // consider X== -0, Y== +0.
755 // It becomes safe if either operand is a nonzero constant.
756 ConstantFP *CFPt, *CFPf;
757 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
758 !CFPt->getValueAPF().isZero()) ||
759 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
760 !CFPf->getValueAPF().isZero()))
761 return ReplaceInstUsesWith(SI, FalseVal);
763 // Transform (X une Y) ? Y : X -> Y
764 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
765 // This is not safe in general for floating point:
766 // consider X== -0, Y== +0.
767 // It becomes safe if either operand is a nonzero constant.
768 ConstantFP *CFPt, *CFPf;
769 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
770 !CFPt->getValueAPF().isZero()) ||
771 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
772 !CFPf->getValueAPF().isZero()))
773 return ReplaceInstUsesWith(SI, TrueVal);
775 // NOTE: if we wanted to, this is where to detect MIN/MAX
777 // NOTE: if we wanted to, this is where to detect ABS
780 // See if we are selecting two values based on a comparison of the two values.
781 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
782 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
785 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
786 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
787 if (TI->hasOneUse() && FI->hasOneUse()) {
788 Instruction *AddOp = 0, *SubOp = 0;
790 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
791 if (TI->getOpcode() == FI->getOpcode())
792 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
795 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
796 // even legal for FP.
797 if ((TI->getOpcode() == Instruction::Sub &&
798 FI->getOpcode() == Instruction::Add) ||
799 (TI->getOpcode() == Instruction::FSub &&
800 FI->getOpcode() == Instruction::FAdd)) {
801 AddOp = FI; SubOp = TI;
802 } else if ((FI->getOpcode() == Instruction::Sub &&
803 TI->getOpcode() == Instruction::Add) ||
804 (FI->getOpcode() == Instruction::FSub &&
805 TI->getOpcode() == Instruction::FAdd)) {
806 AddOp = TI; SubOp = FI;
810 Value *OtherAddOp = 0;
811 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
812 OtherAddOp = AddOp->getOperand(1);
813 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
814 OtherAddOp = AddOp->getOperand(0);
818 // So at this point we know we have (Y -> OtherAddOp):
819 // select C, (add X, Y), (sub X, Z)
820 Value *NegVal; // Compute -Z
821 if (SI.getType()->isFPOrFPVectorTy()) {
822 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
824 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
827 Value *NewTrueOp = OtherAddOp;
828 Value *NewFalseOp = NegVal;
830 std::swap(NewTrueOp, NewFalseOp);
832 Builder->CreateSelect(CondVal, NewTrueOp,
833 NewFalseOp, SI.getName() + ".p");
835 if (SI.getType()->isFPOrFPVectorTy())
836 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
838 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
843 // See if we can fold the select into one of our operands.
844 if (SI.getType()->isIntegerTy()) {
845 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
848 // MAX(MAX(a, b), a) -> MAX(a, b)
849 // MIN(MIN(a, b), a) -> MIN(a, b)
850 // MAX(MIN(a, b), a) -> a
851 // MIN(MAX(a, b), a) -> a
852 Value *LHS, *RHS, *LHS2, *RHS2;
853 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
854 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
855 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
858 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
859 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
866 // ABS(ABS(X)) -> ABS(X)
869 // See if we can fold the select into a phi node if the condition is a select.
870 if (isa<PHINode>(SI.getCondition()))
871 // The true/false values have to be live in the PHI predecessor's blocks.
872 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
873 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
874 if (Instruction *NV = FoldOpIntoPhi(SI))
877 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
878 if (TrueSI->getCondition() == CondVal) {
879 SI.setOperand(1, TrueSI->getTrueValue());
883 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
884 if (FalseSI->getCondition() == CondVal) {
885 SI.setOperand(2, FalseSI->getFalseValue());
890 if (BinaryOperator::isNot(CondVal)) {
891 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
892 SI.setOperand(1, FalseVal);
893 SI.setOperand(2, TrueVal);