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 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/IR/PatternMatch.h"
20 using namespace PatternMatch;
22 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
23 /// returning the kind and providing the out parameter results if we
24 /// successfully match.
25 static SelectPatternFlavor
26 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
27 SelectInst *SI = dyn_cast<SelectInst>(V);
28 if (SI == 0) return SPF_UNKNOWN;
30 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
31 if (ICI == 0) return SPF_UNKNOWN;
33 LHS = ICI->getOperand(0);
34 RHS = ICI->getOperand(1);
36 // (icmp X, Y) ? X : Y
37 if (SI->getTrueValue() == ICI->getOperand(0) &&
38 SI->getFalseValue() == ICI->getOperand(1)) {
39 switch (ICI->getPredicate()) {
40 default: return SPF_UNKNOWN; // Equality.
41 case ICmpInst::ICMP_UGT:
42 case ICmpInst::ICMP_UGE: return SPF_UMAX;
43 case ICmpInst::ICMP_SGT:
44 case ICmpInst::ICMP_SGE: return SPF_SMAX;
45 case ICmpInst::ICMP_ULT:
46 case ICmpInst::ICMP_ULE: return SPF_UMIN;
47 case ICmpInst::ICMP_SLT:
48 case ICmpInst::ICMP_SLE: return SPF_SMIN;
52 // (icmp X, Y) ? Y : X
53 if (SI->getTrueValue() == ICI->getOperand(1) &&
54 SI->getFalseValue() == ICI->getOperand(0)) {
55 switch (ICI->getPredicate()) {
56 default: return SPF_UNKNOWN; // Equality.
57 case ICmpInst::ICMP_UGT:
58 case ICmpInst::ICMP_UGE: return SPF_UMIN;
59 case ICmpInst::ICMP_SGT:
60 case ICmpInst::ICMP_SGE: return SPF_SMIN;
61 case ICmpInst::ICMP_ULT:
62 case ICmpInst::ICMP_ULE: return SPF_UMAX;
63 case ICmpInst::ICMP_SLT:
64 case ICmpInst::ICMP_SLE: return SPF_SMAX;
68 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
74 /// GetSelectFoldableOperands - We want to turn code that looks like this:
76 /// %D = select %cond, %C, %A
78 /// %C = select %cond, %B, 0
81 /// Assuming that the specified instruction is an operand to the select, return
82 /// a bitmask indicating which operands of this instruction are foldable if they
83 /// equal the other incoming value of the select.
85 static unsigned GetSelectFoldableOperands(Instruction *I) {
86 switch (I->getOpcode()) {
87 case Instruction::Add:
88 case Instruction::Mul:
89 case Instruction::And:
91 case Instruction::Xor:
92 return 3; // Can fold through either operand.
93 case Instruction::Sub: // Can only fold on the amount subtracted.
94 case Instruction::Shl: // Can only fold on the shift amount.
95 case Instruction::LShr:
96 case Instruction::AShr:
99 return 0; // Cannot fold
103 /// GetSelectFoldableConstant - For the same transformation as the previous
104 /// function, return the identity constant that goes into the select.
105 static Constant *GetSelectFoldableConstant(Instruction *I) {
106 switch (I->getOpcode()) {
107 default: llvm_unreachable("This cannot happen!");
108 case Instruction::Add:
109 case Instruction::Sub:
110 case Instruction::Or:
111 case Instruction::Xor:
112 case Instruction::Shl:
113 case Instruction::LShr:
114 case Instruction::AShr:
115 return Constant::getNullValue(I->getType());
116 case Instruction::And:
117 return Constant::getAllOnesValue(I->getType());
118 case Instruction::Mul:
119 return ConstantInt::get(I->getType(), 1);
123 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
124 /// have the same opcode and only one use each. Try to simplify this.
125 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 if (TI->getNumOperands() == 1) {
128 // If this is a non-volatile load or a cast from the same type,
131 Type *FIOpndTy = FI->getOperand(0)->getType();
132 if (TI->getOperand(0)->getType() != FIOpndTy)
134 // The select condition may be a vector. We may only change the operand
135 // type if the vector width remains the same (and matches the condition).
136 Type *CondTy = SI.getCondition()->getType();
137 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
138 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
141 return 0; // unknown unary op.
144 // Fold this by inserting a select from the input values.
145 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
146 FI->getOperand(0), SI.getName()+".v");
147 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
151 // Only handle binary operators here.
152 if (!isa<BinaryOperator>(TI))
155 // Figure out if the operations have any operands in common.
156 Value *MatchOp, *OtherOpT, *OtherOpF;
158 if (TI->getOperand(0) == FI->getOperand(0)) {
159 MatchOp = TI->getOperand(0);
160 OtherOpT = TI->getOperand(1);
161 OtherOpF = FI->getOperand(1);
162 MatchIsOpZero = true;
163 } else if (TI->getOperand(1) == FI->getOperand(1)) {
164 MatchOp = TI->getOperand(1);
165 OtherOpT = TI->getOperand(0);
166 OtherOpF = FI->getOperand(0);
167 MatchIsOpZero = false;
168 } else if (!TI->isCommutative()) {
170 } else if (TI->getOperand(0) == FI->getOperand(1)) {
171 MatchOp = TI->getOperand(0);
172 OtherOpT = TI->getOperand(1);
173 OtherOpF = FI->getOperand(0);
174 MatchIsOpZero = true;
175 } else if (TI->getOperand(1) == FI->getOperand(0)) {
176 MatchOp = TI->getOperand(1);
177 OtherOpT = TI->getOperand(0);
178 OtherOpF = FI->getOperand(1);
179 MatchIsOpZero = true;
184 // If we reach here, they do have operations in common.
185 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
186 OtherOpF, SI.getName()+".v");
188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
190 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
192 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
194 llvm_unreachable("Shouldn't get here");
197 static bool isSelect01(Constant *C1, Constant *C2) {
198 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
201 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
204 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
206 return C1I->isOne() || C1I->isAllOnesValue() ||
207 C2I->isOne() || C2I->isAllOnesValue();
210 /// FoldSelectIntoOp - Try fold the select into one of the operands to
211 /// facilitate further optimization.
212 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
214 // See the comment above GetSelectFoldableOperands for a description of the
215 // transformation we are doing here.
216 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
217 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
218 !isa<Constant>(FalseVal)) {
219 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
220 unsigned OpToFold = 0;
221 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
223 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
228 Constant *C = GetSelectFoldableConstant(TVI);
229 Value *OOp = TVI->getOperand(2-OpToFold);
230 // Avoid creating select between 2 constants unless it's selecting
231 // between 0, 1 and -1.
232 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
233 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
234 NewSel->takeName(TVI);
235 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
236 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
238 if (isa<PossiblyExactOperator>(BO))
239 BO->setIsExact(TVI_BO->isExact());
240 if (isa<OverflowingBinaryOperator>(BO)) {
241 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
242 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
251 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
252 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
253 !isa<Constant>(TrueVal)) {
254 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
255 unsigned OpToFold = 0;
256 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
258 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
263 Constant *C = GetSelectFoldableConstant(FVI);
264 Value *OOp = FVI->getOperand(2-OpToFold);
265 // Avoid creating select between 2 constants unless it's selecting
266 // between 0, 1 and -1.
267 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
268 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
269 NewSel->takeName(FVI);
270 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
271 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
273 if (isa<PossiblyExactOperator>(BO))
274 BO->setIsExact(FVI_BO->isExact());
275 if (isa<OverflowingBinaryOperator>(BO)) {
276 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
277 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
289 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
290 /// replaced with RepOp.
291 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
292 const DataLayout *TD,
293 const TargetLibraryInfo *TLI) {
294 // Trivial replacement.
298 Instruction *I = dyn_cast<Instruction>(V);
302 // If this is a binary operator, try to simplify it with the replaced op.
303 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
304 if (B->getOperand(0) == Op)
305 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
306 if (B->getOperand(1) == Op)
307 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
310 // Same for CmpInsts.
311 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
312 if (C->getOperand(0) == Op)
313 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
315 if (C->getOperand(1) == Op)
316 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
320 // TODO: We could hand off more cases to instsimplify here.
322 // If all operands are constant after substituting Op for RepOp then we can
323 // constant fold the instruction.
324 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
325 // Build a list of all constant operands.
326 SmallVector<Constant*, 8> ConstOps;
327 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
328 if (I->getOperand(i) == Op)
329 ConstOps.push_back(CRepOp);
330 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
331 ConstOps.push_back(COp);
336 // All operands were constants, fold it.
337 if (ConstOps.size() == I->getNumOperands()) {
338 if (CmpInst *C = dyn_cast<CmpInst>(I))
339 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
340 ConstOps[1], TD, TLI);
342 if (LoadInst *LI = dyn_cast<LoadInst>(I))
343 if (!LI->isVolatile())
344 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
346 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
354 /// foldSelectICmpAndOr - We want to turn:
355 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
357 /// (or (shl (and X, C1), C3), y)
359 /// C1 and C2 are both powers of 2
361 /// C3 = Log(C2) - Log(C1)
363 /// This transform handles cases where:
364 /// 1. The icmp predicate is inverted
365 /// 2. The select operands are reversed
366 /// 3. The magnitude of C2 and C1 are flipped
367 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
369 InstCombiner::BuilderTy *Builder) {
370 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
371 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
374 Value *CmpLHS = IC->getOperand(0);
375 Value *CmpRHS = IC->getOperand(1);
377 if (!match(CmpRHS, m_Zero()))
382 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
386 bool OrOnTrueVal = false;
387 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
389 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
391 if (!OrOnFalseVal && !OrOnTrueVal)
395 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
397 unsigned C1Log = C1->logBase2();
398 unsigned C2Log = C2->logBase2();
400 V = Builder->CreateZExtOrTrunc(V, Y->getType());
401 V = Builder->CreateShl(V, C2Log - C1Log);
402 } else if (C1Log > C2Log) {
403 V = Builder->CreateLShr(V, C1Log - C2Log);
404 V = Builder->CreateZExtOrTrunc(V, Y->getType());
406 V = Builder->CreateZExtOrTrunc(V, Y->getType());
408 ICmpInst::Predicate Pred = IC->getPredicate();
409 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
410 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
411 V = Builder->CreateXor(V, *C2);
413 return Builder->CreateOr(V, Y);
416 /// visitSelectInstWithICmp - Visit a SelectInst that has an
417 /// ICmpInst as its first operand.
419 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
421 bool Changed = false;
422 ICmpInst::Predicate Pred = ICI->getPredicate();
423 Value *CmpLHS = ICI->getOperand(0);
424 Value *CmpRHS = ICI->getOperand(1);
425 Value *TrueVal = SI.getTrueValue();
426 Value *FalseVal = SI.getFalseValue();
428 // Check cases where the comparison is with a constant that
429 // can be adjusted to fit the min/max idiom. We may move or edit ICI
430 // here, so make sure the select is the only user.
431 if (ICI->hasOneUse())
432 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
433 // X < MIN ? T : F --> F
434 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
435 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
436 return ReplaceInstUsesWith(SI, FalseVal);
437 // X > MAX ? T : F --> F
438 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
439 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
440 return ReplaceInstUsesWith(SI, FalseVal);
443 case ICmpInst::ICMP_ULT:
444 case ICmpInst::ICMP_SLT:
445 case ICmpInst::ICMP_UGT:
446 case ICmpInst::ICMP_SGT: {
447 // These transformations only work for selects over integers.
448 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
452 Constant *AdjustedRHS;
453 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
454 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
455 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
456 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
458 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
459 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
460 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
461 (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
462 ; // Nothing to do here. Values match without any sign/zero extension.
464 // Types do not match. Instead of calculating this with mixed types
465 // promote all to the larger type. This enables scalar evolution to
466 // analyze this expression.
467 else if (CmpRHS->getType()->getScalarSizeInBits()
468 < SelectTy->getBitWidth()) {
469 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
471 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
472 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
473 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
474 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
475 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
476 sextRHS == FalseVal) {
478 AdjustedRHS = sextRHS;
479 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
480 sextRHS == TrueVal) {
482 AdjustedRHS = sextRHS;
483 } else if (ICI->isUnsigned()) {
484 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
485 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
486 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
487 // zext + signed compare cannot be changed:
488 // 0xff <s 0x00, but 0x00ff >s 0x0000
489 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
490 zextRHS == FalseVal) {
492 AdjustedRHS = zextRHS;
493 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
494 zextRHS == TrueVal) {
496 AdjustedRHS = zextRHS;
504 Pred = ICmpInst::getSwappedPredicate(Pred);
505 CmpRHS = AdjustedRHS;
506 std::swap(FalseVal, TrueVal);
507 ICI->setPredicate(Pred);
508 ICI->setOperand(0, CmpLHS);
509 ICI->setOperand(1, CmpRHS);
510 SI.setOperand(1, TrueVal);
511 SI.setOperand(2, FalseVal);
513 // Move ICI instruction right before the select instruction. Otherwise
514 // the sext/zext value may be defined after the ICI instruction uses it.
515 ICI->moveBefore(&SI);
523 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
524 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
525 // FIXME: Type and constness constraints could be lifted, but we have to
526 // watch code size carefully. We should consider xor instead of
527 // sub/add when we decide to do that.
528 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
529 if (TrueVal->getType() == Ty) {
530 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
531 ConstantInt *C1 = NULL, *C2 = NULL;
532 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
533 C1 = dyn_cast<ConstantInt>(TrueVal);
534 C2 = dyn_cast<ConstantInt>(FalseVal);
535 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
536 C1 = dyn_cast<ConstantInt>(FalseVal);
537 C2 = dyn_cast<ConstantInt>(TrueVal);
540 // This shift results in either -1 or 0.
541 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
543 // Check if we can express the operation with a single or.
544 if (C2->isAllOnesValue())
545 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
547 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
548 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
554 // If we have an equality comparison then we know the value in one of the
555 // arms of the select. See if substituting this value into the arm and
556 // simplifying the result yields the same value as the other arm.
557 if (Pred == ICmpInst::ICMP_EQ) {
558 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
559 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
560 return ReplaceInstUsesWith(SI, FalseVal);
561 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
562 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
563 return ReplaceInstUsesWith(SI, FalseVal);
564 } else if (Pred == ICmpInst::ICMP_NE) {
565 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
566 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
567 return ReplaceInstUsesWith(SI, TrueVal);
568 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
569 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
570 return ReplaceInstUsesWith(SI, TrueVal);
573 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
575 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
576 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
577 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
578 SI.setOperand(1, CmpRHS);
580 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
581 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
582 SI.setOperand(2, CmpRHS);
587 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
588 return ReplaceInstUsesWith(SI, V);
590 return Changed ? &SI : 0;
594 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
595 /// PHI node (but the two may be in different blocks). See if the true/false
596 /// values (V) are live in all of the predecessor blocks of the PHI. For
597 /// example, cases like this cannot be mapped:
599 /// X = phi [ C1, BB1], [C2, BB2]
601 /// Z = select X, Y, 0
603 /// because Y is not live in BB1/BB2.
605 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
606 const SelectInst &SI) {
607 // If the value is a non-instruction value like a constant or argument, it
608 // can always be mapped.
609 const Instruction *I = dyn_cast<Instruction>(V);
610 if (I == 0) return true;
612 // If V is a PHI node defined in the same block as the condition PHI, we can
613 // map the arguments.
614 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
616 if (const PHINode *VP = dyn_cast<PHINode>(I))
617 if (VP->getParent() == CondPHI->getParent())
620 // Otherwise, if the PHI and select are defined in the same block and if V is
621 // defined in a different block, then we can transform it.
622 if (SI.getParent() == CondPHI->getParent() &&
623 I->getParent() != CondPHI->getParent())
626 // Otherwise we have a 'hard' case and we can't tell without doing more
627 // detailed dominator based analysis, punt.
631 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
632 /// SPF2(SPF1(A, B), C)
633 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
634 SelectPatternFlavor SPF1,
637 SelectPatternFlavor SPF2, Value *C) {
638 if (C == A || C == B) {
639 // MAX(MAX(A, B), B) -> MAX(A, B)
640 // MIN(MIN(a, b), a) -> MIN(a, b)
642 return ReplaceInstUsesWith(Outer, Inner);
644 // MAX(MIN(a, b), a) -> a
645 // MIN(MAX(a, b), a) -> a
646 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
647 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
648 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
649 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
650 return ReplaceInstUsesWith(Outer, C);
653 // TODO: MIN(MIN(A, 23), 97)
658 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
659 /// both be) and we have an icmp instruction with zero, and we have an 'and'
660 /// with the non-constant value and a power of two we can turn the select
661 /// into a shift on the result of the 'and'.
662 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
663 ConstantInt *FalseVal,
664 InstCombiner::BuilderTy *Builder) {
665 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
666 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
669 if (!match(IC->getOperand(1), m_Zero()))
673 Value *LHS = IC->getOperand(0);
674 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
677 // If both select arms are non-zero see if we have a select of the form
678 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
679 // for 'x ? 2^n : 0' and fix the thing up at the end.
680 ConstantInt *Offset = 0;
681 if (!TrueVal->isZero() && !FalseVal->isZero()) {
682 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
684 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
689 // Adjust TrueVal and FalseVal to the offset.
690 TrueVal = ConstantInt::get(Builder->getContext(),
691 TrueVal->getValue() - Offset->getValue());
692 FalseVal = ConstantInt::get(Builder->getContext(),
693 FalseVal->getValue() - Offset->getValue());
696 // Make sure the mask in the 'and' and one of the select arms is a power of 2.
697 if (!AndRHS->getValue().isPowerOf2() ||
698 (!TrueVal->getValue().isPowerOf2() &&
699 !FalseVal->getValue().isPowerOf2()))
702 // Determine which shift is needed to transform result of the 'and' into the
704 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
705 unsigned ValZeros = ValC->getValue().logBase2();
706 unsigned AndZeros = AndRHS->getValue().logBase2();
708 // If types don't match we can still convert the select by introducing a zext
709 // or a trunc of the 'and'. The trunc case requires that all of the truncated
710 // bits are zero, we can figure that out by looking at the 'and' mask.
711 if (AndZeros >= ValC->getBitWidth())
714 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
715 if (ValZeros > AndZeros)
716 V = Builder->CreateShl(V, ValZeros - AndZeros);
717 else if (ValZeros < AndZeros)
718 V = Builder->CreateLShr(V, AndZeros - ValZeros);
720 // Okay, now we know that everything is set up, we just don't know whether we
721 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
722 bool ShouldNotVal = !TrueVal->isZero();
723 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
725 V = Builder->CreateXor(V, ValC);
727 // Apply an offset if needed.
729 V = Builder->CreateAdd(V, Offset);
733 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
734 Value *CondVal = SI.getCondition();
735 Value *TrueVal = SI.getTrueValue();
736 Value *FalseVal = SI.getFalseValue();
738 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL))
739 return ReplaceInstUsesWith(SI, V);
741 if (SI.getType()->isIntegerTy(1)) {
742 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
743 if (C->getZExtValue()) {
744 // Change: A = select B, true, C --> A = or B, C
745 return BinaryOperator::CreateOr(CondVal, FalseVal);
747 // Change: A = select B, false, C --> A = and !B, C
748 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
749 return BinaryOperator::CreateAnd(NotCond, FalseVal);
751 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
752 if (C->getZExtValue() == false) {
753 // Change: A = select B, C, false --> A = and B, C
754 return BinaryOperator::CreateAnd(CondVal, TrueVal);
756 // Change: A = select B, C, true --> A = or !B, C
757 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
758 return BinaryOperator::CreateOr(NotCond, TrueVal);
761 // select a, b, a -> a&b
762 // select a, a, b -> a|b
763 if (CondVal == TrueVal)
764 return BinaryOperator::CreateOr(CondVal, FalseVal);
765 if (CondVal == FalseVal)
766 return BinaryOperator::CreateAnd(CondVal, TrueVal);
768 // select a, ~a, b -> (~a)&b
769 // select a, b, ~a -> (~a)|b
770 if (match(TrueVal, m_Not(m_Specific(CondVal))))
771 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
772 if (match(FalseVal, m_Not(m_Specific(CondVal))))
773 return BinaryOperator::CreateOr(TrueVal, FalseVal);
776 // Selecting between two integer constants?
777 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
778 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
779 // select C, 1, 0 -> zext C to int
780 if (FalseValC->isZero() && TrueValC->getValue() == 1)
781 return new ZExtInst(CondVal, SI.getType());
783 // select C, -1, 0 -> sext C to int
784 if (FalseValC->isZero() && TrueValC->isAllOnesValue())
785 return new SExtInst(CondVal, SI.getType());
787 // select C, 0, 1 -> zext !C to int
788 if (TrueValC->isZero() && FalseValC->getValue() == 1) {
789 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
790 return new ZExtInst(NotCond, SI.getType());
793 // select C, 0, -1 -> sext !C to int
794 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
795 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
796 return new SExtInst(NotCond, SI.getType());
799 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
800 return ReplaceInstUsesWith(SI, V);
803 // See if we are selecting two values based on a comparison of the two values.
804 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
805 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
806 // Transform (X == Y) ? X : Y -> Y
807 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
808 // This is not safe in general for floating point:
809 // consider X== -0, Y== +0.
810 // It becomes safe if either operand is a nonzero constant.
811 ConstantFP *CFPt, *CFPf;
812 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
813 !CFPt->getValueAPF().isZero()) ||
814 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
815 !CFPf->getValueAPF().isZero()))
816 return ReplaceInstUsesWith(SI, FalseVal);
818 // Transform (X une Y) ? X : Y -> X
819 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
820 // This is not safe in general for floating point:
821 // consider X== -0, Y== +0.
822 // It becomes safe if either operand is a nonzero constant.
823 ConstantFP *CFPt, *CFPf;
824 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
825 !CFPt->getValueAPF().isZero()) ||
826 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
827 !CFPf->getValueAPF().isZero()))
828 return ReplaceInstUsesWith(SI, TrueVal);
830 // NOTE: if we wanted to, this is where to detect MIN/MAX
832 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
833 // Transform (X == Y) ? Y : X -> X
834 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
835 // This is not safe in general for floating point:
836 // consider X== -0, Y== +0.
837 // It becomes safe if either operand is a nonzero constant.
838 ConstantFP *CFPt, *CFPf;
839 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
840 !CFPt->getValueAPF().isZero()) ||
841 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
842 !CFPf->getValueAPF().isZero()))
843 return ReplaceInstUsesWith(SI, FalseVal);
845 // Transform (X une Y) ? Y : X -> Y
846 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
847 // This is not safe in general for floating point:
848 // consider X== -0, Y== +0.
849 // It becomes safe if either operand is a nonzero constant.
850 ConstantFP *CFPt, *CFPf;
851 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
852 !CFPt->getValueAPF().isZero()) ||
853 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
854 !CFPf->getValueAPF().isZero()))
855 return ReplaceInstUsesWith(SI, TrueVal);
857 // NOTE: if we wanted to, this is where to detect MIN/MAX
859 // NOTE: if we wanted to, this is where to detect ABS
862 // See if we are selecting two values based on a comparison of the two values.
863 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
864 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
867 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
868 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
869 if (TI->hasOneUse() && FI->hasOneUse()) {
870 Instruction *AddOp = 0, *SubOp = 0;
872 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
873 if (TI->getOpcode() == FI->getOpcode())
874 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
877 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
878 // even legal for FP.
879 if ((TI->getOpcode() == Instruction::Sub &&
880 FI->getOpcode() == Instruction::Add) ||
881 (TI->getOpcode() == Instruction::FSub &&
882 FI->getOpcode() == Instruction::FAdd)) {
883 AddOp = FI; SubOp = TI;
884 } else if ((FI->getOpcode() == Instruction::Sub &&
885 TI->getOpcode() == Instruction::Add) ||
886 (FI->getOpcode() == Instruction::FSub &&
887 TI->getOpcode() == Instruction::FAdd)) {
888 AddOp = TI; SubOp = FI;
892 Value *OtherAddOp = 0;
893 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
894 OtherAddOp = AddOp->getOperand(1);
895 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
896 OtherAddOp = AddOp->getOperand(0);
900 // So at this point we know we have (Y -> OtherAddOp):
901 // select C, (add X, Y), (sub X, Z)
902 Value *NegVal; // Compute -Z
903 if (SI.getType()->isFPOrFPVectorTy()) {
904 NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
905 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
906 FastMathFlags Flags = AddOp->getFastMathFlags();
907 Flags &= SubOp->getFastMathFlags();
908 NegInst->setFastMathFlags(Flags);
911 NegVal = Builder->CreateNeg(SubOp->getOperand(1));
914 Value *NewTrueOp = OtherAddOp;
915 Value *NewFalseOp = NegVal;
917 std::swap(NewTrueOp, NewFalseOp);
919 Builder->CreateSelect(CondVal, NewTrueOp,
920 NewFalseOp, SI.getName() + ".p");
922 if (SI.getType()->isFPOrFPVectorTy()) {
924 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
926 FastMathFlags Flags = AddOp->getFastMathFlags();
927 Flags &= SubOp->getFastMathFlags();
928 RI->setFastMathFlags(Flags);
931 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
936 // See if we can fold the select into one of our operands.
937 if (SI.getType()->isIntegerTy()) {
938 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
941 // MAX(MAX(a, b), a) -> MAX(a, b)
942 // MIN(MIN(a, b), a) -> MIN(a, b)
943 // MAX(MIN(a, b), a) -> a
944 // MIN(MAX(a, b), a) -> a
945 Value *LHS, *RHS, *LHS2, *RHS2;
946 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
947 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
948 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
951 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
952 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
959 // ABS(ABS(X)) -> ABS(X)
962 // See if we can fold the select into a phi node if the condition is a select.
963 if (isa<PHINode>(SI.getCondition()))
964 // The true/false values have to be live in the PHI predecessor's blocks.
965 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
966 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
967 if (Instruction *NV = FoldOpIntoPhi(SI))
970 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
971 if (TrueSI->getCondition() == CondVal) {
972 if (SI.getTrueValue() == TrueSI->getTrueValue())
974 SI.setOperand(1, TrueSI->getTrueValue());
978 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
979 if (FalseSI->getCondition() == CondVal) {
980 if (SI.getFalseValue() == FalseSI->getFalseValue())
982 SI.setOperand(2, FalseSI->getFalseValue());
987 if (BinaryOperator::isNot(CondVal)) {
988 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
989 SI.setOperand(1, FalseVal);
990 SI.setOperand(2, TrueVal);
994 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
995 unsigned VWidth = VecTy->getNumElements();
996 APInt UndefElts(VWidth, 0);
997 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
998 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1000 return ReplaceInstUsesWith(SI, V);
1004 if (isa<ConstantAggregateZero>(CondVal)) {
1005 return ReplaceInstUsesWith(SI, FalseVal);