InstCombine: Make switch folding with equality compares more aggressive by trying...
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineSelect.cpp
1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitSelect function.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/Support/PatternMatch.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 using namespace llvm;
18 using namespace PatternMatch;
19
20 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
21 /// returning the kind and providing the out parameter results if we
22 /// successfully match.
23 static SelectPatternFlavor
24 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
25   SelectInst *SI = dyn_cast<SelectInst>(V);
26   if (SI == 0) return SPF_UNKNOWN;
27
28   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
29   if (ICI == 0) return SPF_UNKNOWN;
30
31   LHS = ICI->getOperand(0);
32   RHS = ICI->getOperand(1);
33
34   // (icmp X, Y) ? X : Y
35   if (SI->getTrueValue() == ICI->getOperand(0) &&
36       SI->getFalseValue() == ICI->getOperand(1)) {
37     switch (ICI->getPredicate()) {
38     default: return SPF_UNKNOWN; // Equality.
39     case ICmpInst::ICMP_UGT:
40     case ICmpInst::ICMP_UGE: return SPF_UMAX;
41     case ICmpInst::ICMP_SGT:
42     case ICmpInst::ICMP_SGE: return SPF_SMAX;
43     case ICmpInst::ICMP_ULT:
44     case ICmpInst::ICMP_ULE: return SPF_UMIN;
45     case ICmpInst::ICMP_SLT:
46     case ICmpInst::ICMP_SLE: return SPF_SMIN;
47     }
48   }
49
50   // (icmp X, Y) ? Y : X
51   if (SI->getTrueValue() == ICI->getOperand(1) &&
52       SI->getFalseValue() == ICI->getOperand(0)) {
53     switch (ICI->getPredicate()) {
54       default: return SPF_UNKNOWN; // Equality.
55       case ICmpInst::ICMP_UGT:
56       case ICmpInst::ICMP_UGE: return SPF_UMIN;
57       case ICmpInst::ICMP_SGT:
58       case ICmpInst::ICMP_SGE: return SPF_SMIN;
59       case ICmpInst::ICMP_ULT:
60       case ICmpInst::ICMP_ULE: return SPF_UMAX;
61       case ICmpInst::ICMP_SLT:
62       case ICmpInst::ICMP_SLE: return SPF_SMAX;
63     }
64   }
65
66   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
67
68   return SPF_UNKNOWN;
69 }
70
71
72 /// GetSelectFoldableOperands - We want to turn code that looks like this:
73 ///   %C = or %A, %B
74 ///   %D = select %cond, %C, %A
75 /// into:
76 ///   %C = select %cond, %B, 0
77 ///   %D = or %A, %C
78 ///
79 /// Assuming that the specified instruction is an operand to the select, return
80 /// a bitmask indicating which operands of this instruction are foldable if they
81 /// equal the other incoming value of the select.
82 ///
83 static unsigned GetSelectFoldableOperands(Instruction *I) {
84   switch (I->getOpcode()) {
85   case Instruction::Add:
86   case Instruction::Mul:
87   case Instruction::And:
88   case Instruction::Or:
89   case Instruction::Xor:
90     return 3;              // Can fold through either operand.
91   case Instruction::Sub:   // Can only fold on the amount subtracted.
92   case Instruction::Shl:   // Can only fold on the shift amount.
93   case Instruction::LShr:
94   case Instruction::AShr:
95     return 1;
96   default:
97     return 0;              // Cannot fold
98   }
99 }
100
101 /// GetSelectFoldableConstant - For the same transformation as the previous
102 /// function, return the identity constant that goes into the select.
103 static Constant *GetSelectFoldableConstant(Instruction *I) {
104   switch (I->getOpcode()) {
105   default: llvm_unreachable("This cannot happen!");
106   case Instruction::Add:
107   case Instruction::Sub:
108   case Instruction::Or:
109   case Instruction::Xor:
110   case Instruction::Shl:
111   case Instruction::LShr:
112   case Instruction::AShr:
113     return Constant::getNullValue(I->getType());
114   case Instruction::And:
115     return Constant::getAllOnesValue(I->getType());
116   case Instruction::Mul:
117     return ConstantInt::get(I->getType(), 1);
118   }
119 }
120
121 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
122 /// have the same opcode and only one use each.  Try to simplify this.
123 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124                                           Instruction *FI) {
125   if (TI->getNumOperands() == 1) {
126     // If this is a non-volatile load or a cast from the same type,
127     // merge.
128     if (TI->isCast()) {
129       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
130         return 0;
131     } else {
132       return 0;  // unknown unary op.
133     }
134
135     // Fold this by inserting a select from the input values.
136     Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
137                                          FI->getOperand(0), SI.getName()+".v");
138     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
139                             TI->getType());
140   }
141
142   // Only handle binary operators here.
143   if (!isa<BinaryOperator>(TI))
144     return 0;
145
146   // Figure out if the operations have any operands in common.
147   Value *MatchOp, *OtherOpT, *OtherOpF;
148   bool MatchIsOpZero;
149   if (TI->getOperand(0) == FI->getOperand(0)) {
150     MatchOp  = TI->getOperand(0);
151     OtherOpT = TI->getOperand(1);
152     OtherOpF = FI->getOperand(1);
153     MatchIsOpZero = true;
154   } else if (TI->getOperand(1) == FI->getOperand(1)) {
155     MatchOp  = TI->getOperand(1);
156     OtherOpT = TI->getOperand(0);
157     OtherOpF = FI->getOperand(0);
158     MatchIsOpZero = false;
159   } else if (!TI->isCommutative()) {
160     return 0;
161   } else if (TI->getOperand(0) == FI->getOperand(1)) {
162     MatchOp  = TI->getOperand(0);
163     OtherOpT = TI->getOperand(1);
164     OtherOpF = FI->getOperand(0);
165     MatchIsOpZero = true;
166   } else if (TI->getOperand(1) == FI->getOperand(0)) {
167     MatchOp  = TI->getOperand(1);
168     OtherOpT = TI->getOperand(0);
169     OtherOpF = FI->getOperand(1);
170     MatchIsOpZero = true;
171   } else {
172     return 0;
173   }
174
175   // If we reach here, they do have operations in common.
176   Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
177                                        OtherOpF, SI.getName()+".v");
178
179   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
180     if (MatchIsOpZero)
181       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
182     else
183       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
184   }
185   llvm_unreachable("Shouldn't get here");
186   return 0;
187 }
188
189 static bool isSelect01(Constant *C1, Constant *C2) {
190   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
191   if (!C1I)
192     return false;
193   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
194   if (!C2I)
195     return false;
196   if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
197     return false;
198   return C1I->isOne() || C1I->isAllOnesValue() ||
199          C2I->isOne() || C2I->isAllOnesValue();
200 }
201
202 /// FoldSelectIntoOp - Try fold the select into one of the operands to
203 /// facilitate further optimization.
204 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
205                                             Value *FalseVal) {
206   // See the comment above GetSelectFoldableOperands for a description of the
207   // transformation we are doing here.
208   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
209     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
210         !isa<Constant>(FalseVal)) {
211       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
212         unsigned OpToFold = 0;
213         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
214           OpToFold = 1;
215         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
216           OpToFold = 2;
217         }
218
219         if (OpToFold) {
220           Constant *C = GetSelectFoldableConstant(TVI);
221           Value *OOp = TVI->getOperand(2-OpToFold);
222           // Avoid creating select between 2 constants unless it's selecting
223           // between 0, 1 and -1.
224           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
225             Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
226             NewSel->takeName(TVI);
227             BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
228             BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
229                                                         FalseVal, NewSel);
230             if (isa<PossiblyExactOperator>(BO))
231               BO->setIsExact(TVI_BO->isExact());
232             if (isa<OverflowingBinaryOperator>(BO)) {
233               BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
234               BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
235             }
236             return BO;
237           }
238         }
239       }
240     }
241   }
242
243   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
244     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
245         !isa<Constant>(TrueVal)) {
246       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
247         unsigned OpToFold = 0;
248         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
249           OpToFold = 1;
250         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
251           OpToFold = 2;
252         }
253
254         if (OpToFold) {
255           Constant *C = GetSelectFoldableConstant(FVI);
256           Value *OOp = FVI->getOperand(2-OpToFold);
257           // Avoid creating select between 2 constants unless it's selecting
258           // between 0, 1 and -1.
259           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
260             Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
261             NewSel->takeName(FVI);
262             BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
263             BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
264                                                         TrueVal, NewSel);
265             if (isa<PossiblyExactOperator>(BO))
266               BO->setIsExact(FVI_BO->isExact());
267             if (isa<OverflowingBinaryOperator>(BO)) {
268               BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
269               BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
270             }
271             return BO;
272           }
273         }
274       }
275     }
276   }
277
278   return 0;
279 }
280
281 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
282 /// replaced with RepOp.
283 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
284                                      const TargetData *TD) {
285   // Trivial replacement.
286   if (V == Op)
287     return RepOp;
288
289   Instruction *I = dyn_cast<Instruction>(V);
290   if (!I)
291     return 0;
292
293   // If this is a binary operator, try to simplify it with the replaced op.
294   if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
295     if (B->getOperand(0) == Op)
296       return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD);
297     if (B->getOperand(1) == Op)
298       return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD);
299   }
300
301   // If all operands are constant after substituting Op for RepOp then we can
302   // constant fold the instruction.
303   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
304     // Build a list of all constant operands.
305     SmallVector<Constant*, 8> ConstOps;
306     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
307       if (I->getOperand(i) == Op)
308         ConstOps.push_back(CRepOp);
309       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
310         ConstOps.push_back(COp);
311       else
312         break;
313     }
314
315     // All operands were constants, fold it.
316     if (ConstOps.size() == I->getNumOperands())
317       return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
318                                       ConstOps.data(), ConstOps.size(), TD);
319   }
320
321   return 0;
322 }
323
324 /// visitSelectInstWithICmp - Visit a SelectInst that has an
325 /// ICmpInst as its first operand.
326 ///
327 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
328                                                    ICmpInst *ICI) {
329   bool Changed = false;
330   ICmpInst::Predicate Pred = ICI->getPredicate();
331   Value *CmpLHS = ICI->getOperand(0);
332   Value *CmpRHS = ICI->getOperand(1);
333   Value *TrueVal = SI.getTrueValue();
334   Value *FalseVal = SI.getFalseValue();
335
336   // Check cases where the comparison is with a constant that
337   // can be adjusted to fit the min/max idiom. We may move or edit ICI
338   // here, so make sure the select is the only user.
339   if (ICI->hasOneUse())
340     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
341       // X < MIN ? T : F  -->  F
342       if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
343           && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
344         return ReplaceInstUsesWith(SI, FalseVal);
345       // X > MAX ? T : F  -->  F
346       else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
347                && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
348         return ReplaceInstUsesWith(SI, FalseVal);
349       switch (Pred) {
350       default: break;
351       case ICmpInst::ICMP_ULT:
352       case ICmpInst::ICMP_SLT:
353       case ICmpInst::ICMP_UGT:
354       case ICmpInst::ICMP_SGT: {
355         // These transformations only work for selects over integers.
356         const IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
357         if (!SelectTy)
358           break;
359
360         Constant *AdjustedRHS;
361         if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
362           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
363         else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
364           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
365
366         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
367         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
368         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
369             (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
370           ; // Nothing to do here. Values match without any sign/zero extension.
371
372         // Types do not match. Instead of calculating this with mixed types
373         // promote all to the larger type. This enables scalar evolution to
374         // analyze this expression.
375         else if (CmpRHS->getType()->getScalarSizeInBits()
376                  < SelectTy->getBitWidth()) {
377           Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
378
379           // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
380           // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
381           // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
382           // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
383           if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
384                 sextRHS == FalseVal) {
385             CmpLHS = TrueVal;
386             AdjustedRHS = sextRHS;
387           } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
388                      sextRHS == TrueVal) {
389             CmpLHS = FalseVal;
390             AdjustedRHS = sextRHS;
391           } else if (ICI->isUnsigned()) {
392             Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
393             // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
394             // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
395             // zext + signed compare cannot be changed:
396             //    0xff <s 0x00, but 0x00ff >s 0x0000
397             if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
398                 zextRHS == FalseVal) {
399               CmpLHS = TrueVal;
400               AdjustedRHS = zextRHS;
401             } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
402                        zextRHS == TrueVal) {
403               CmpLHS = FalseVal;
404               AdjustedRHS = zextRHS;
405             } else
406               break;
407           } else
408             break;
409         } else
410           break;
411
412         Pred = ICmpInst::getSwappedPredicate(Pred);
413         CmpRHS = AdjustedRHS;
414         std::swap(FalseVal, TrueVal);
415         ICI->setPredicate(Pred);
416         ICI->setOperand(0, CmpLHS);
417         ICI->setOperand(1, CmpRHS);
418         SI.setOperand(1, TrueVal);
419         SI.setOperand(2, FalseVal);
420
421         // Move ICI instruction right before the select instruction. Otherwise
422         // the sext/zext value may be defined after the ICI instruction uses it.
423         ICI->moveBefore(&SI);
424
425         Changed = true;
426         break;
427       }
428       }
429     }
430
431   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
432   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
433   // FIXME: Type and constness constraints could be lifted, but we have to
434   //        watch code size carefully. We should consider xor instead of
435   //        sub/add when we decide to do that.
436   if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
437     if (TrueVal->getType() == Ty) {
438       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
439         ConstantInt *C1 = NULL, *C2 = NULL;
440         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
441           C1 = dyn_cast<ConstantInt>(TrueVal);
442           C2 = dyn_cast<ConstantInt>(FalseVal);
443         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
444           C1 = dyn_cast<ConstantInt>(FalseVal);
445           C2 = dyn_cast<ConstantInt>(TrueVal);
446         }
447         if (C1 && C2) {
448           // This shift results in either -1 or 0.
449           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
450
451           // Check if we can express the operation with a single or.
452           if (C2->isAllOnesValue())
453             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
454
455           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
456           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
457         }
458       }
459     }
460   }
461
462   // If we have an equality comparison then we know the value in one of the
463   // arms of the select. See if substituting this value into the arm and
464   // simplifying the result yields the same value as the other arm.
465   if (Pred == ICmpInst::ICMP_EQ) {
466     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD) == TrueVal ||
467         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD) == TrueVal)
468       return ReplaceInstUsesWith(SI, FalseVal);
469   } else if (Pred == ICmpInst::ICMP_NE) {
470     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD) == FalseVal ||
471         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD) == FalseVal)
472       return ReplaceInstUsesWith(SI, TrueVal);
473   }
474
475   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
476
477   if (isa<Constant>(CmpRHS)) {
478     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
479       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
480       SI.setOperand(1, CmpRHS);
481       Changed = true;
482     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
483       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
484       SI.setOperand(2, CmpRHS);
485       Changed = true;
486     }
487   }
488
489   return Changed ? &SI : 0;
490 }
491
492
493 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
494 /// PHI node (but the two may be in different blocks).  See if the true/false
495 /// values (V) are live in all of the predecessor blocks of the PHI.  For
496 /// example, cases like this cannot be mapped:
497 ///
498 ///   X = phi [ C1, BB1], [C2, BB2]
499 ///   Y = add
500 ///   Z = select X, Y, 0
501 ///
502 /// because Y is not live in BB1/BB2.
503 ///
504 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
505                                                    const SelectInst &SI) {
506   // If the value is a non-instruction value like a constant or argument, it
507   // can always be mapped.
508   const Instruction *I = dyn_cast<Instruction>(V);
509   if (I == 0) return true;
510
511   // If V is a PHI node defined in the same block as the condition PHI, we can
512   // map the arguments.
513   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
514
515   if (const PHINode *VP = dyn_cast<PHINode>(I))
516     if (VP->getParent() == CondPHI->getParent())
517       return true;
518
519   // Otherwise, if the PHI and select are defined in the same block and if V is
520   // defined in a different block, then we can transform it.
521   if (SI.getParent() == CondPHI->getParent() &&
522       I->getParent() != CondPHI->getParent())
523     return true;
524
525   // Otherwise we have a 'hard' case and we can't tell without doing more
526   // detailed dominator based analysis, punt.
527   return false;
528 }
529
530 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
531 ///   SPF2(SPF1(A, B), C)
532 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
533                                         SelectPatternFlavor SPF1,
534                                         Value *A, Value *B,
535                                         Instruction &Outer,
536                                         SelectPatternFlavor SPF2, Value *C) {
537   if (C == A || C == B) {
538     // MAX(MAX(A, B), B) -> MAX(A, B)
539     // MIN(MIN(a, b), a) -> MIN(a, b)
540     if (SPF1 == SPF2)
541       return ReplaceInstUsesWith(Outer, Inner);
542
543     // MAX(MIN(a, b), a) -> a
544     // MIN(MAX(a, b), a) -> a
545     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
546         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
547         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
548         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
549       return ReplaceInstUsesWith(Outer, C);
550   }
551
552   // TODO: MIN(MIN(A, 23), 97)
553   return 0;
554 }
555
556
557 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
558 /// both be) and we have an icmp instruction with zero, and we have an 'and'
559 /// with the non-constant value and a power of two we can turn the select
560 /// into a shift on the result of the 'and'.
561 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
562                                 ConstantInt *FalseVal,
563                                 InstCombiner::BuilderTy *Builder) {
564   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
565   if (!IC || !IC->isEquality())
566     return 0;
567
568   if (!match(IC->getOperand(1), m_Zero()))
569     return 0;
570
571   ConstantInt *AndRHS;
572   Value *LHS = IC->getOperand(0);
573   if (LHS->getType() != SI.getType() ||
574       !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
575     return 0;
576
577   // If both select arms are non-zero see if we have a select of the form
578   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
579   // for 'x ? 2^n : 0' and fix the thing up at the end.
580   ConstantInt *Offset = 0;
581   if (!TrueVal->isZero() && !FalseVal->isZero()) {
582     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
583       Offset = FalseVal;
584     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
585       Offset = TrueVal;
586     else
587       return 0;
588
589     // Adjust TrueVal and FalseVal to the offset.
590     TrueVal = ConstantInt::get(Builder->getContext(),
591                                TrueVal->getValue() - Offset->getValue());
592     FalseVal = ConstantInt::get(Builder->getContext(),
593                                 FalseVal->getValue() - Offset->getValue());
594   }
595
596   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
597   if (!AndRHS->getValue().isPowerOf2() ||
598       (!TrueVal->getValue().isPowerOf2() &&
599        !FalseVal->getValue().isPowerOf2()))
600     return 0;
601
602   // Determine which shift is needed to transform result of the 'and' into the
603   // desired result.
604   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
605   unsigned ValZeros = ValC->getValue().logBase2();
606   unsigned AndZeros = AndRHS->getValue().logBase2();
607
608   Value *V = LHS;
609   if (ValZeros > AndZeros)
610     V = Builder->CreateShl(V, ValZeros - AndZeros);
611   else if (ValZeros < AndZeros)
612     V = Builder->CreateLShr(V, AndZeros - ValZeros);
613
614   // Okay, now we know that everything is set up, we just don't know whether we
615   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
616   bool ShouldNotVal = !TrueVal->isZero();
617   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
618   if (ShouldNotVal)
619     V = Builder->CreateXor(V, ValC);
620
621   // Apply an offset if needed.
622   if (Offset)
623     V = Builder->CreateAdd(V, Offset);
624   return V;
625 }
626
627 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
628   Value *CondVal = SI.getCondition();
629   Value *TrueVal = SI.getTrueValue();
630   Value *FalseVal = SI.getFalseValue();
631
632   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
633     return ReplaceInstUsesWith(SI, V);
634
635   if (SI.getType()->isIntegerTy(1)) {
636     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
637       if (C->getZExtValue()) {
638         // Change: A = select B, true, C --> A = or B, C
639         return BinaryOperator::CreateOr(CondVal, FalseVal);
640       }
641       // Change: A = select B, false, C --> A = and !B, C
642       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
643       return BinaryOperator::CreateAnd(NotCond, FalseVal);
644     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
645       if (C->getZExtValue() == false) {
646         // Change: A = select B, C, false --> A = and B, C
647         return BinaryOperator::CreateAnd(CondVal, TrueVal);
648       }
649       // Change: A = select B, C, true --> A = or !B, C
650       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
651       return BinaryOperator::CreateOr(NotCond, TrueVal);
652     }
653
654     // select a, b, a  -> a&b
655     // select a, a, b  -> a|b
656     if (CondVal == TrueVal)
657       return BinaryOperator::CreateOr(CondVal, FalseVal);
658     else if (CondVal == FalseVal)
659       return BinaryOperator::CreateAnd(CondVal, TrueVal);
660   }
661
662   // Selecting between two integer constants?
663   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
664     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
665       // select C, 1, 0 -> zext C to int
666       if (FalseValC->isZero() && TrueValC->getValue() == 1)
667         return new ZExtInst(CondVal, SI.getType());
668
669       // select C, -1, 0 -> sext C to int
670       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
671         return new SExtInst(CondVal, SI.getType());
672
673       // select C, 0, 1 -> zext !C to int
674       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
675         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
676         return new ZExtInst(NotCond, SI.getType());
677       }
678
679       // select C, 0, -1 -> sext !C to int
680       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
681         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
682         return new SExtInst(NotCond, SI.getType());
683       }
684
685       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
686         return ReplaceInstUsesWith(SI, V);
687     }
688
689   // See if we are selecting two values based on a comparison of the two values.
690   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
691     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
692       // Transform (X == Y) ? X : Y  -> Y
693       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
694         // This is not safe in general for floating point:
695         // consider X== -0, Y== +0.
696         // It becomes safe if either operand is a nonzero constant.
697         ConstantFP *CFPt, *CFPf;
698         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
699               !CFPt->getValueAPF().isZero()) ||
700             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
701              !CFPf->getValueAPF().isZero()))
702         return ReplaceInstUsesWith(SI, FalseVal);
703       }
704       // Transform (X une Y) ? X : Y  -> X
705       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
706         // This is not safe in general for floating point:
707         // consider X== -0, Y== +0.
708         // It becomes safe if either operand is a nonzero constant.
709         ConstantFP *CFPt, *CFPf;
710         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
711               !CFPt->getValueAPF().isZero()) ||
712             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
713              !CFPf->getValueAPF().isZero()))
714         return ReplaceInstUsesWith(SI, TrueVal);
715       }
716       // NOTE: if we wanted to, this is where to detect MIN/MAX
717
718     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
719       // Transform (X == Y) ? Y : X  -> X
720       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
721         // This is not safe in general for floating point:
722         // consider X== -0, Y== +0.
723         // It becomes safe if either operand is a nonzero constant.
724         ConstantFP *CFPt, *CFPf;
725         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
726               !CFPt->getValueAPF().isZero()) ||
727             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
728              !CFPf->getValueAPF().isZero()))
729           return ReplaceInstUsesWith(SI, FalseVal);
730       }
731       // Transform (X une Y) ? Y : X  -> Y
732       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
733         // This is not safe in general for floating point:
734         // consider X== -0, Y== +0.
735         // It becomes safe if either operand is a nonzero constant.
736         ConstantFP *CFPt, *CFPf;
737         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
738               !CFPt->getValueAPF().isZero()) ||
739             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
740              !CFPf->getValueAPF().isZero()))
741           return ReplaceInstUsesWith(SI, TrueVal);
742       }
743       // NOTE: if we wanted to, this is where to detect MIN/MAX
744     }
745     // NOTE: if we wanted to, this is where to detect ABS
746   }
747
748   // See if we are selecting two values based on a comparison of the two values.
749   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
750     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
751       return Result;
752
753   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
754     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
755       if (TI->hasOneUse() && FI->hasOneUse()) {
756         Instruction *AddOp = 0, *SubOp = 0;
757
758         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
759         if (TI->getOpcode() == FI->getOpcode())
760           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
761             return IV;
762
763         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
764         // even legal for FP.
765         if ((TI->getOpcode() == Instruction::Sub &&
766              FI->getOpcode() == Instruction::Add) ||
767             (TI->getOpcode() == Instruction::FSub &&
768              FI->getOpcode() == Instruction::FAdd)) {
769           AddOp = FI; SubOp = TI;
770         } else if ((FI->getOpcode() == Instruction::Sub &&
771                     TI->getOpcode() == Instruction::Add) ||
772                    (FI->getOpcode() == Instruction::FSub &&
773                     TI->getOpcode() == Instruction::FAdd)) {
774           AddOp = TI; SubOp = FI;
775         }
776
777         if (AddOp) {
778           Value *OtherAddOp = 0;
779           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
780             OtherAddOp = AddOp->getOperand(1);
781           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
782             OtherAddOp = AddOp->getOperand(0);
783           }
784
785           if (OtherAddOp) {
786             // So at this point we know we have (Y -> OtherAddOp):
787             //        select C, (add X, Y), (sub X, Z)
788             Value *NegVal;  // Compute -Z
789             if (SI.getType()->isFloatingPointTy()) {
790               NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
791             } else {
792               NegVal = Builder->CreateNeg(SubOp->getOperand(1));
793             }
794
795             Value *NewTrueOp = OtherAddOp;
796             Value *NewFalseOp = NegVal;
797             if (AddOp != TI)
798               std::swap(NewTrueOp, NewFalseOp);
799             Value *NewSel = 
800               Builder->CreateSelect(CondVal, NewTrueOp,
801                                     NewFalseOp, SI.getName() + ".p");
802
803             if (SI.getType()->isFloatingPointTy())
804               return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
805             else
806               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
807           }
808         }
809       }
810
811   // See if we can fold the select into one of our operands.
812   if (SI.getType()->isIntegerTy()) {
813     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
814       return FoldI;
815
816     // MAX(MAX(a, b), a) -> MAX(a, b)
817     // MIN(MIN(a, b), a) -> MIN(a, b)
818     // MAX(MIN(a, b), a) -> a
819     // MIN(MAX(a, b), a) -> a
820     Value *LHS, *RHS, *LHS2, *RHS2;
821     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
822       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
823         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 
824                                           SI, SPF, RHS))
825           return R;
826       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
827         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
828                                           SI, SPF, LHS))
829           return R;
830     }
831
832     // TODO.
833     // ABS(-X) -> ABS(X)
834     // ABS(ABS(X)) -> ABS(X)
835   }
836
837   // See if we can fold the select into a phi node if the condition is a select.
838   if (isa<PHINode>(SI.getCondition()))
839     // The true/false values have to be live in the PHI predecessor's blocks.
840     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
841         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
842       if (Instruction *NV = FoldOpIntoPhi(SI))
843         return NV;
844
845   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
846     if (TrueSI->getCondition() == CondVal) {
847       SI.setOperand(1, TrueSI->getTrueValue());
848       return &SI;
849     }
850   }
851   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
852     if (FalseSI->getCondition() == CondVal) {
853       SI.setOperand(2, FalseSI->getFalseValue());
854       return &SI;
855     }
856   }
857
858   if (BinaryOperator::isNot(CondVal)) {
859     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
860     SI.setOperand(1, FalseVal);
861     SI.setOperand(2, TrueVal);
862     return &SI;
863   }
864
865   return 0;
866 }