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/Support/PatternMatch.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 Type *FIOpndTy = FI->getOperand(0)->getType();
131 if (TI->getOperand(0)->getType() != FIOpndTy)
133 // The select condition may be a vector. We may only change the operand
134 // type if the vector width remains the same (and matches the condition).
135 Type *CondTy = SI.getCondition()->getType();
136 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
137 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
140 return 0; // unknown unary op.
143 // Fold this by inserting a select from the input values.
144 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
145 FI->getOperand(0), SI.getName()+".v");
146 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
150 // Only handle binary operators here.
151 if (!isa<BinaryOperator>(TI))
154 // Figure out if the operations have any operands in common.
155 Value *MatchOp, *OtherOpT, *OtherOpF;
157 if (TI->getOperand(0) == FI->getOperand(0)) {
158 MatchOp = TI->getOperand(0);
159 OtherOpT = TI->getOperand(1);
160 OtherOpF = FI->getOperand(1);
161 MatchIsOpZero = true;
162 } else if (TI->getOperand(1) == FI->getOperand(1)) {
163 MatchOp = TI->getOperand(1);
164 OtherOpT = TI->getOperand(0);
165 OtherOpF = FI->getOperand(0);
166 MatchIsOpZero = false;
167 } else if (!TI->isCommutative()) {
169 } else if (TI->getOperand(0) == FI->getOperand(1)) {
170 MatchOp = TI->getOperand(0);
171 OtherOpT = TI->getOperand(1);
172 OtherOpF = FI->getOperand(0);
173 MatchIsOpZero = true;
174 } else if (TI->getOperand(1) == FI->getOperand(0)) {
175 MatchOp = TI->getOperand(1);
176 OtherOpT = TI->getOperand(0);
177 OtherOpF = FI->getOperand(1);
178 MatchIsOpZero = true;
183 // If we reach here, they do have operations in common.
184 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
185 OtherOpF, SI.getName()+".v");
187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
189 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
191 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
193 llvm_unreachable("Shouldn't get here");
196 static bool isSelect01(Constant *C1, Constant *C2) {
197 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
200 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
203 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
205 return C1I->isOne() || C1I->isAllOnesValue() ||
206 C2I->isOne() || C2I->isAllOnesValue();
209 /// FoldSelectIntoOp - Try fold the select into one of the operands to
210 /// facilitate further optimization.
211 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
213 // See the comment above GetSelectFoldableOperands for a description of the
214 // transformation we are doing here.
215 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
216 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
217 !isa<Constant>(FalseVal)) {
218 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
219 unsigned OpToFold = 0;
220 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
222 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
227 Constant *C = GetSelectFoldableConstant(TVI);
228 Value *OOp = TVI->getOperand(2-OpToFold);
229 // Avoid creating select between 2 constants unless it's selecting
230 // between 0, 1 and -1.
231 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
232 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
233 NewSel->takeName(TVI);
234 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
235 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
237 if (isa<PossiblyExactOperator>(BO))
238 BO->setIsExact(TVI_BO->isExact());
239 if (isa<OverflowingBinaryOperator>(BO)) {
240 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
241 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
250 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
251 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
252 !isa<Constant>(TrueVal)) {
253 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
254 unsigned OpToFold = 0;
255 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
257 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
262 Constant *C = GetSelectFoldableConstant(FVI);
263 Value *OOp = FVI->getOperand(2-OpToFold);
264 // Avoid creating select between 2 constants unless it's selecting
265 // between 0, 1 and -1.
266 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
267 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
268 NewSel->takeName(FVI);
269 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
270 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
272 if (isa<PossiblyExactOperator>(BO))
273 BO->setIsExact(FVI_BO->isExact());
274 if (isa<OverflowingBinaryOperator>(BO)) {
275 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
276 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
288 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
289 /// replaced with RepOp.
290 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
291 const DataLayout *TD,
292 const TargetLibraryInfo *TLI) {
293 // Trivial replacement.
297 Instruction *I = dyn_cast<Instruction>(V);
301 // If this is a binary operator, try to simplify it with the replaced op.
302 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
303 if (B->getOperand(0) == Op)
304 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
305 if (B->getOperand(1) == Op)
306 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
309 // Same for CmpInsts.
310 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
311 if (C->getOperand(0) == Op)
312 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
314 if (C->getOperand(1) == Op)
315 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
319 // TODO: We could hand off more cases to instsimplify here.
321 // If all operands are constant after substituting Op for RepOp then we can
322 // constant fold the instruction.
323 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
324 // Build a list of all constant operands.
325 SmallVector<Constant*, 8> ConstOps;
326 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
327 if (I->getOperand(i) == Op)
328 ConstOps.push_back(CRepOp);
329 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
330 ConstOps.push_back(COp);
335 // All operands were constants, fold it.
336 if (ConstOps.size() == I->getNumOperands()) {
337 if (CmpInst *C = dyn_cast<CmpInst>(I))
338 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
339 ConstOps[1], TD, TLI);
341 if (LoadInst *LI = dyn_cast<LoadInst>(I))
342 if (!LI->isVolatile())
343 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
345 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
353 /// foldSelectICmpAndOr - We want to turn:
354 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
356 /// (or (shl (and X, C1), C3), y)
358 /// C1 and C2 are both powers of 2
360 /// C3 = Log(C2) - Log(C1)
362 /// This transform handles cases where:
363 /// 1. The icmp predicate is inverted
364 /// 2. The select operands are reversed
365 /// 3. The magnitude of C2 and C1 are flipped
366 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
368 InstCombiner::BuilderTy *Builder) {
369 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
370 if (!IC || !IC->isEquality())
373 Value *CmpLHS = IC->getOperand(0);
374 Value *CmpRHS = IC->getOperand(1);
376 if (!match(CmpRHS, m_Zero()))
381 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
385 bool OrOnTrueVal = false;
386 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
388 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
390 if (!OrOnFalseVal && !OrOnTrueVal)
395 unsigned C1Log = C1->logBase2();
396 unsigned C2Log = C2->logBase2();
398 V = Builder->CreateShl(V, C2Log - C1Log);
399 else if (C1Log > C2Log)
400 V = Builder->CreateLShr(V, C1Log - C2Log);
402 ICmpInst::Predicate Pred = IC->getPredicate();
403 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
404 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
405 V = Builder->CreateXor(V, *C2);
407 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
408 return Builder->CreateOr(V, Y);
411 /// visitSelectInstWithICmp - Visit a SelectInst that has an
412 /// ICmpInst as its first operand.
414 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
416 bool Changed = false;
417 ICmpInst::Predicate Pred = ICI->getPredicate();
418 Value *CmpLHS = ICI->getOperand(0);
419 Value *CmpRHS = ICI->getOperand(1);
420 Value *TrueVal = SI.getTrueValue();
421 Value *FalseVal = SI.getFalseValue();
423 // Check cases where the comparison is with a constant that
424 // can be adjusted to fit the min/max idiom. We may move or edit ICI
425 // here, so make sure the select is the only user.
426 if (ICI->hasOneUse())
427 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
428 // X < MIN ? T : F --> F
429 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
430 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
431 return ReplaceInstUsesWith(SI, FalseVal);
432 // X > MAX ? T : F --> F
433 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
434 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
435 return ReplaceInstUsesWith(SI, FalseVal);
438 case ICmpInst::ICMP_ULT:
439 case ICmpInst::ICMP_SLT:
440 case ICmpInst::ICMP_UGT:
441 case ICmpInst::ICMP_SGT: {
442 // These transformations only work for selects over integers.
443 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
447 Constant *AdjustedRHS;
448 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
449 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
450 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
451 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
453 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
454 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
455 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
456 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
457 ; // Nothing to do here. Values match without any sign/zero extension.
459 // Types do not match. Instead of calculating this with mixed types
460 // promote all to the larger type. This enables scalar evolution to
461 // analyze this expression.
462 else if (CmpRHS->getType()->getScalarSizeInBits()
463 < SelectTy->getBitWidth()) {
464 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
466 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
467 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
468 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
469 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
470 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
471 sextRHS == FalseVal) {
473 AdjustedRHS = sextRHS;
474 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
475 sextRHS == TrueVal) {
477 AdjustedRHS = sextRHS;
478 } else if (ICI->isUnsigned()) {
479 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
480 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
481 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
482 // zext + signed compare cannot be changed:
483 // 0xff <s 0x00, but 0x00ff >s 0x0000
484 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
485 zextRHS == FalseVal) {
487 AdjustedRHS = zextRHS;
488 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
489 zextRHS == TrueVal) {
491 AdjustedRHS = zextRHS;
499 Pred = ICmpInst::getSwappedPredicate(Pred);
500 CmpRHS = AdjustedRHS;
501 std::swap(FalseVal, TrueVal);
502 ICI->setPredicate(Pred);
503 ICI->setOperand(0, CmpLHS);
504 ICI->setOperand(1, CmpRHS);
505 SI.setOperand(1, TrueVal);
506 SI.setOperand(2, FalseVal);
508 // Move ICI instruction right before the select instruction. Otherwise
509 // the sext/zext value may be defined after the ICI instruction uses it.
510 ICI->moveBefore(&SI);
518 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
519 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
520 // FIXME: Type and constness constraints could be lifted, but we have to
521 // watch code size carefully. We should consider xor instead of
522 // sub/add when we decide to do that.
523 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
524 if (TrueVal->getType() == Ty) {
525 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
526 ConstantInt *C1 = NULL, *C2 = NULL;
527 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
528 C1 = dyn_cast<ConstantInt>(TrueVal);
529 C2 = dyn_cast<ConstantInt>(FalseVal);
530 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
531 C1 = dyn_cast<ConstantInt>(FalseVal);
532 C2 = dyn_cast<ConstantInt>(TrueVal);
535 // This shift results in either -1 or 0.
536 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
538 // Check if we can express the operation with a single or.
539 if (C2->isAllOnesValue())
540 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
542 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
543 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
549 // If we have an equality comparison then we know the value in one of the
550 // arms of the select. See if substituting this value into the arm and
551 // simplifying the result yields the same value as the other arm.
552 if (Pred == ICmpInst::ICMP_EQ) {
553 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
554 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
555 return ReplaceInstUsesWith(SI, FalseVal);
556 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
557 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
558 return ReplaceInstUsesWith(SI, FalseVal);
559 } else if (Pred == ICmpInst::ICMP_NE) {
560 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) == FalseVal ||
561 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) == FalseVal)
562 return ReplaceInstUsesWith(SI, TrueVal);
563 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) == TrueVal ||
564 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) == TrueVal)
565 return ReplaceInstUsesWith(SI, TrueVal);
568 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
570 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
571 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
572 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
573 SI.setOperand(1, CmpRHS);
575 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
576 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
577 SI.setOperand(2, CmpRHS);
582 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
583 return ReplaceInstUsesWith(SI, V);
585 return Changed ? &SI : 0;
589 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
590 /// PHI node (but the two may be in different blocks). See if the true/false
591 /// values (V) are live in all of the predecessor blocks of the PHI. For
592 /// example, cases like this cannot be mapped:
594 /// X = phi [ C1, BB1], [C2, BB2]
596 /// Z = select X, Y, 0
598 /// because Y is not live in BB1/BB2.
600 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
601 const SelectInst &SI) {
602 // If the value is a non-instruction value like a constant or argument, it
603 // can always be mapped.
604 const Instruction *I = dyn_cast<Instruction>(V);
605 if (I == 0) return true;
607 // If V is a PHI node defined in the same block as the condition PHI, we can
608 // map the arguments.
609 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
611 if (const PHINode *VP = dyn_cast<PHINode>(I))
612 if (VP->getParent() == CondPHI->getParent())
615 // Otherwise, if the PHI and select are defined in the same block and if V is
616 // defined in a different block, then we can transform it.
617 if (SI.getParent() == CondPHI->getParent() &&
618 I->getParent() != CondPHI->getParent())
621 // Otherwise we have a 'hard' case and we can't tell without doing more
622 // detailed dominator based analysis, punt.
626 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
627 /// SPF2(SPF1(A, B), C)
628 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
629 SelectPatternFlavor SPF1,
632 SelectPatternFlavor SPF2, Value *C) {
633 if (C == A || C == B) {
634 // MAX(MAX(A, B), B) -> MAX(A, B)
635 // MIN(MIN(a, b), a) -> MIN(a, b)
637 return ReplaceInstUsesWith(Outer, Inner);
639 // MAX(MIN(a, b), a) -> a
640 // MIN(MAX(a, b), a) -> a
641 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
642 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
643 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
644 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
645 return ReplaceInstUsesWith(Outer, C);
648 // TODO: MIN(MIN(A, 23), 97)
653 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
654 /// both be) and we have an icmp instruction with zero, and we have an 'and'
655 /// with the non-constant value and a power of two we can turn the select
656 /// into a shift on the result of the 'and'.
657 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
658 ConstantInt *FalseVal,
659 InstCombiner::BuilderTy *Builder) {
660 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
661 if (!IC || !IC->isEquality())
664 if (!match(IC->getOperand(1), m_Zero()))
668 Value *LHS = IC->getOperand(0);
669 if (LHS->getType() != SI.getType() ||
670 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
673 // If both select arms are non-zero see if we have a select of the form
674 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
675 // for 'x ? 2^n : 0' and fix the thing up at the end.
676 ConstantInt *Offset = 0;
677 if (!TrueVal->isZero() && !FalseVal->isZero()) {
678 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
680 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
685 // Adjust TrueVal and FalseVal to the offset.
686 TrueVal = ConstantInt::get(Builder->getContext(),
687 TrueVal->getValue() - Offset->getValue());
688 FalseVal = ConstantInt::get(Builder->getContext(),
689 FalseVal->getValue() - Offset->getValue());
692 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
693 if (!AndRHS->getValue().isPowerOf2() ||
694 (!TrueVal->getValue().isPowerOf2() &&
695 !FalseVal->getValue().isPowerOf2()))
698 // Determine which shift is needed to transform result of the 'and' into the
700 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
701 unsigned ValZeros = ValC->getValue().logBase2();
702 unsigned AndZeros = AndRHS->getValue().logBase2();
705 if (ValZeros > AndZeros)
706 V = Builder->CreateShl(V, ValZeros - AndZeros);
707 else if (ValZeros < AndZeros)
708 V = Builder->CreateLShr(V, AndZeros - ValZeros);
710 // Okay, now we know that everything is set up, we just don't know whether we
711 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
712 bool ShouldNotVal = !TrueVal->isZero();
713 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
715 V = Builder->CreateXor(V, ValC);
717 // Apply an offset if needed.
719 V = Builder->CreateAdd(V, Offset);
723 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
724 Value *CondVal = SI.getCondition();
725 Value *TrueVal = SI.getTrueValue();
726 Value *FalseVal = SI.getFalseValue();
728 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
729 return ReplaceInstUsesWith(SI, V);
731 if (SI.getType()->isIntegerTy(1)) {
732 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
733 if (C->getZExtValue()) {
734 // Change: A = select B, true, C --> A = or B, C
735 return BinaryOperator::CreateOr(CondVal, FalseVal);
737 // Change: A = select B, false, C --> A = and !B, C
738 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
739 return BinaryOperator::CreateAnd(NotCond, FalseVal);
740 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
741 if (C->getZExtValue() == false) {
742 // Change: A = select B, C, false --> A = and B, C
743 return BinaryOperator::CreateAnd(CondVal, TrueVal);
745 // Change: A = select B, C, true --> A = or !B, C
746 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
747 return BinaryOperator::CreateOr(NotCond, TrueVal);
750 // select a, b, a -> a&b
751 // select a, a, b -> a|b
752 if (CondVal == TrueVal)
753 return BinaryOperator::CreateOr(CondVal, FalseVal);
754 else if (CondVal == FalseVal)
755 return BinaryOperator::CreateAnd(CondVal, TrueVal);
757 // select a, ~a, b -> (~a)&b
758 // select a, b, ~a -> (~a)|b
759 if (match(TrueVal, m_Not(m_Specific(CondVal))))
760 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
761 else if (match(FalseVal, m_Not(m_Specific(CondVal))))
762 return BinaryOperator::CreateOr(TrueVal, FalseVal);
765 // Selecting between two integer constants?
766 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
767 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
768 // select C, 1, 0 -> zext C to int
769 if (FalseValC->isZero() && TrueValC->getValue() == 1)
770 return new ZExtInst(CondVal, SI.getType());
772 // select C, -1, 0 -> sext C to int
773 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
774 return new SExtInst(CondVal, SI.getType());
776 // select C, 0, 1 -> zext !C to int
777 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
778 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
779 return new ZExtInst(NotCond, SI.getType());
782 // select C, 0, -1 -> sext !C to int
783 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
784 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
785 return new SExtInst(NotCond, SI.getType());
788 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
789 return ReplaceInstUsesWith(SI, V);
792 // See if we are selecting two values based on a comparison of the two values.
793 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
794 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
795 // Transform (X == Y) ? X : Y -> Y
796 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
797 // This is not safe in general for floating point:
798 // consider X== -0, Y== +0.
799 // It becomes safe if either operand is a nonzero constant.
800 ConstantFP *CFPt, *CFPf;
801 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
802 !CFPt->getValueAPF().isZero()) ||
803 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
804 !CFPf->getValueAPF().isZero()))
805 return ReplaceInstUsesWith(SI, FalseVal);
807 // Transform (X une Y) ? X : Y -> X
808 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
809 // This is not safe in general for floating point:
810 // consider X== -0, Y== +0.
811 // It becomes safe if either operand is a nonzero constant.
812 ConstantFP *CFPt, *CFPf;
813 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
814 !CFPt->getValueAPF().isZero()) ||
815 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
816 !CFPf->getValueAPF().isZero()))
817 return ReplaceInstUsesWith(SI, TrueVal);
819 // NOTE: if we wanted to, this is where to detect MIN/MAX
821 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
822 // Transform (X == Y) ? Y : X -> X
823 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
824 // This is not safe in general for floating point:
825 // consider X== -0, Y== +0.
826 // It becomes safe if either operand is a nonzero constant.
827 ConstantFP *CFPt, *CFPf;
828 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
829 !CFPt->getValueAPF().isZero()) ||
830 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
831 !CFPf->getValueAPF().isZero()))
832 return ReplaceInstUsesWith(SI, FalseVal);
834 // Transform (X une Y) ? Y : X -> Y
835 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
836 // This is not safe in general for floating point:
837 // consider X== -0, Y== +0.
838 // It becomes safe if either operand is a nonzero constant.
839 ConstantFP *CFPt, *CFPf;
840 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
841 !CFPt->getValueAPF().isZero()) ||
842 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
843 !CFPf->getValueAPF().isZero()))
844 return ReplaceInstUsesWith(SI, TrueVal);
846 // NOTE: if we wanted to, this is where to detect MIN/MAX
848 // NOTE: if we wanted to, this is where to detect ABS
851 // See if we are selecting two values based on a comparison of the two values.
852 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
853 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
856 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
857 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
858 if (TI->hasOneUse() && FI->hasOneUse()) {
859 Instruction *AddOp = 0, *SubOp = 0;
861 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
862 if (TI->getOpcode() == FI->getOpcode())
863 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
866 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
867 // even legal for FP.
868 if ((TI->getOpcode() == Instruction::Sub &&
869 FI->getOpcode() == Instruction::Add) ||
870 (TI->getOpcode() == Instruction::FSub &&
871 FI->getOpcode() == Instruction::FAdd)) {
872 AddOp = FI; SubOp = TI;
873 } else if ((FI->getOpcode() == Instruction::Sub &&
874 TI->getOpcode() == Instruction::Add) ||
875 (FI->getOpcode() == Instruction::FSub &&
876 TI->getOpcode() == Instruction::FAdd)) {
877 AddOp = TI; SubOp = FI;
881 Value *OtherAddOp = 0;
882 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
883 OtherAddOp = AddOp->getOperand(1);
884 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
885 OtherAddOp = AddOp->getOperand(0);
889 // So at this point we know we have (Y -> OtherAddOp):
890 // select C, (add X, Y), (sub X, Z)
891 Value *NegVal; // Compute -Z
892 if (SI.getType()->isFPOrFPVectorTy()) {
893 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
895 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
898 Value *NewTrueOp = OtherAddOp;
899 Value *NewFalseOp = NegVal;
901 std::swap(NewTrueOp, NewFalseOp);
903 Builder->CreateSelect(CondVal, NewTrueOp,
904 NewFalseOp, SI.getName() + ".p");
906 if (SI.getType()->isFPOrFPVectorTy())
907 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
909 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
914 // See if we can fold the select into one of our operands.
915 if (SI.getType()->isIntegerTy()) {
916 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
919 // MAX(MAX(a, b), a) -> MAX(a, b)
920 // MIN(MIN(a, b), a) -> MIN(a, b)
921 // MAX(MIN(a, b), a) -> a
922 // MIN(MAX(a, b), a) -> a
923 Value *LHS, *RHS, *LHS2, *RHS2;
924 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
925 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
926 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
929 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
930 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
937 // ABS(ABS(X)) -> ABS(X)
940 // See if we can fold the select into a phi node if the condition is a select.
941 if (isa<PHINode>(SI.getCondition()))
942 // The true/false values have to be live in the PHI predecessor's blocks.
943 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
944 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
945 if (Instruction *NV = FoldOpIntoPhi(SI))
948 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
949 if (TrueSI->getCondition() == CondVal) {
950 if (SI.getTrueValue() == TrueSI->getTrueValue())
952 SI.setOperand(1, TrueSI->getTrueValue());
956 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
957 if (FalseSI->getCondition() == CondVal) {
958 if (SI.getFalseValue() == FalseSI->getFalseValue())
960 SI.setOperand(2, FalseSI->getFalseValue());
965 if (BinaryOperator::isNot(CondVal)) {
966 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
967 SI.setOperand(1, FalseVal);
968 SI.setOperand(2, TrueVal);
972 if (VectorType *VecTy = dyn_cast<VectorType>(SI.getType())) {
973 unsigned VWidth = VecTy->getNumElements();
974 APInt UndefElts(VWidth, 0);
975 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
976 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
978 return ReplaceInstUsesWith(SI, V);
982 if (ConstantVector *CV = dyn_cast<ConstantVector>(CondVal)) {
983 // Form a shufflevector instruction.
984 SmallVector<Constant *, 8> Mask(VWidth);
985 Type *Int32Ty = Type::getInt32Ty(CV->getContext());
986 for (unsigned i = 0; i != VWidth; ++i) {
987 Constant *Elem = cast<Constant>(CV->getOperand(i));
988 if (ConstantInt *E = dyn_cast<ConstantInt>(Elem))
989 Mask[i] = ConstantInt::get(Int32Ty, i + (E->isZero() ? VWidth : 0));
990 else if (isa<UndefValue>(Elem))
991 Mask[i] = UndefValue::get(Int32Ty);
995 Constant *MaskVal = ConstantVector::get(Mask);
996 Value *V = Builder->CreateShuffleVector(TrueVal, FalseVal, MaskVal);
997 return ReplaceInstUsesWith(SI, V);
1000 if (isa<ConstantAggregateZero>(CondVal)) {
1001 return ReplaceInstUsesWith(SI, FalseVal);