Generalize the and-icmp-select instcombine further by allowing selects of the form
[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     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
137                                           FI->getOperand(0), SI.getName()+".v");
138     InsertNewInstBefore(NewSI, SI);
139     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
140                             TI->getType());
141   }
142
143   // Only handle binary operators here.
144   if (!isa<BinaryOperator>(TI))
145     return 0;
146
147   // Figure out if the operations have any operands in common.
148   Value *MatchOp, *OtherOpT, *OtherOpF;
149   bool MatchIsOpZero;
150   if (TI->getOperand(0) == FI->getOperand(0)) {
151     MatchOp  = TI->getOperand(0);
152     OtherOpT = TI->getOperand(1);
153     OtherOpF = FI->getOperand(1);
154     MatchIsOpZero = true;
155   } else if (TI->getOperand(1) == FI->getOperand(1)) {
156     MatchOp  = TI->getOperand(1);
157     OtherOpT = TI->getOperand(0);
158     OtherOpF = FI->getOperand(0);
159     MatchIsOpZero = false;
160   } else if (!TI->isCommutative()) {
161     return 0;
162   } else if (TI->getOperand(0) == FI->getOperand(1)) {
163     MatchOp  = TI->getOperand(0);
164     OtherOpT = TI->getOperand(1);
165     OtherOpF = FI->getOperand(0);
166     MatchIsOpZero = true;
167   } else if (TI->getOperand(1) == FI->getOperand(0)) {
168     MatchOp  = TI->getOperand(1);
169     OtherOpT = TI->getOperand(0);
170     OtherOpF = FI->getOperand(1);
171     MatchIsOpZero = true;
172   } else {
173     return 0;
174   }
175
176   // If we reach here, they do have operations in common.
177   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
178                                          OtherOpF, SI.getName()+".v");
179   InsertNewInstBefore(NewSI, SI);
180
181   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
182     if (MatchIsOpZero)
183       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
184     else
185       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
186   }
187   llvm_unreachable("Shouldn't get here");
188   return 0;
189 }
190
191 static bool isSelect01(Constant *C1, Constant *C2) {
192   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
193   if (!C1I)
194     return false;
195   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
196   if (!C2I)
197     return false;
198   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
199 }
200
201 /// FoldSelectIntoOp - Try fold the select into one of the operands to
202 /// facilitate further optimization.
203 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
204                                             Value *FalseVal) {
205   // See the comment above GetSelectFoldableOperands for a description of the
206   // transformation we are doing here.
207   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
208     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
209         !isa<Constant>(FalseVal)) {
210       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
211         unsigned OpToFold = 0;
212         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
213           OpToFold = 1;
214         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
215           OpToFold = 2;
216         }
217
218         if (OpToFold) {
219           Constant *C = GetSelectFoldableConstant(TVI);
220           Value *OOp = TVI->getOperand(2-OpToFold);
221           // Avoid creating select between 2 constants unless it's selecting
222           // between 0 and 1.
223           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
224             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
225             InsertNewInstBefore(NewSel, SI);
226             NewSel->takeName(TVI);
227             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
228               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
229             llvm_unreachable("Unknown instruction!!");
230           }
231         }
232       }
233     }
234   }
235
236   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
237     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
238         !isa<Constant>(TrueVal)) {
239       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
240         unsigned OpToFold = 0;
241         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
242           OpToFold = 1;
243         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
244           OpToFold = 2;
245         }
246
247         if (OpToFold) {
248           Constant *C = GetSelectFoldableConstant(FVI);
249           Value *OOp = FVI->getOperand(2-OpToFold);
250           // Avoid creating select between 2 constants unless it's selecting
251           // between 0 and 1.
252           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
253             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
254             InsertNewInstBefore(NewSel, SI);
255             NewSel->takeName(FVI);
256             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
257               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
258             llvm_unreachable("Unknown instruction!!");
259           }
260         }
261       }
262     }
263   }
264
265   return 0;
266 }
267
268 /// visitSelectInstWithICmp - Visit a SelectInst that has an
269 /// ICmpInst as its first operand.
270 ///
271 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
272                                                    ICmpInst *ICI) {
273   bool Changed = false;
274   ICmpInst::Predicate Pred = ICI->getPredicate();
275   Value *CmpLHS = ICI->getOperand(0);
276   Value *CmpRHS = ICI->getOperand(1);
277   Value *TrueVal = SI.getTrueValue();
278   Value *FalseVal = SI.getFalseValue();
279
280   // Check cases where the comparison is with a constant that
281   // can be adjusted to fit the min/max idiom. We may edit ICI in
282   // place here, so make sure the select is the only user.
283   if (ICI->hasOneUse())
284     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
285       switch (Pred) {
286       default: break;
287       case ICmpInst::ICMP_ULT:
288       case ICmpInst::ICMP_SLT: {
289         // X < MIN ? T : F  -->  F
290         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
291           return ReplaceInstUsesWith(SI, FalseVal);
292         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
293         Constant *AdjustedRHS =
294           ConstantInt::get(CI->getContext(), CI->getValue()-1);
295         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
296             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
297           Pred = ICmpInst::getSwappedPredicate(Pred);
298           CmpRHS = AdjustedRHS;
299           std::swap(FalseVal, TrueVal);
300           ICI->setPredicate(Pred);
301           ICI->setOperand(1, CmpRHS);
302           SI.setOperand(1, TrueVal);
303           SI.setOperand(2, FalseVal);
304           Changed = true;
305         }
306         break;
307       }
308       case ICmpInst::ICMP_UGT:
309       case ICmpInst::ICMP_SGT: {
310         // X > MAX ? T : F  -->  F
311         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
312           return ReplaceInstUsesWith(SI, FalseVal);
313         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
314         Constant *AdjustedRHS =
315           ConstantInt::get(CI->getContext(), CI->getValue()+1);
316         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
317             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
318           Pred = ICmpInst::getSwappedPredicate(Pred);
319           CmpRHS = AdjustedRHS;
320           std::swap(FalseVal, TrueVal);
321           ICI->setPredicate(Pred);
322           ICI->setOperand(1, CmpRHS);
323           SI.setOperand(1, TrueVal);
324           SI.setOperand(2, FalseVal);
325           Changed = true;
326         }
327         break;
328       }
329       }
330     }
331
332   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
333   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
334   // FIXME: Type and constness constraints could be lifted, but we have to
335   //        watch code size carefully. We should consider xor instead of
336   //        sub/add when we decide to do that.
337   if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
338     if (TrueVal->getType() == Ty) {
339       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
340         ConstantInt *C1 = NULL, *C2 = NULL;
341         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
342           C1 = dyn_cast<ConstantInt>(TrueVal);
343           C2 = dyn_cast<ConstantInt>(FalseVal);
344         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
345           C1 = dyn_cast<ConstantInt>(FalseVal);
346           C2 = dyn_cast<ConstantInt>(TrueVal);
347         }
348         if (C1 && C2) {
349           // This shift results in either -1 or 0.
350           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
351
352           // Check if we can express the operation with a single or.
353           if (C2->isAllOnesValue())
354             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
355
356           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
357           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
358         }
359       }
360     }
361   }
362
363   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
364     // Transform (X == Y) ? X : Y  -> Y
365     if (Pred == ICmpInst::ICMP_EQ)
366       return ReplaceInstUsesWith(SI, FalseVal);
367     // Transform (X != Y) ? X : Y  -> X
368     if (Pred == ICmpInst::ICMP_NE)
369       return ReplaceInstUsesWith(SI, TrueVal);
370     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
371
372   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
373     // Transform (X == Y) ? Y : X  -> X
374     if (Pred == ICmpInst::ICMP_EQ)
375       return ReplaceInstUsesWith(SI, FalseVal);
376     // Transform (X != Y) ? Y : X  -> Y
377     if (Pred == ICmpInst::ICMP_NE)
378       return ReplaceInstUsesWith(SI, TrueVal);
379     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
380   }
381   return Changed ? &SI : 0;
382 }
383
384
385 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
386 /// PHI node (but the two may be in different blocks).  See if the true/false
387 /// values (V) are live in all of the predecessor blocks of the PHI.  For
388 /// example, cases like this cannot be mapped:
389 ///
390 ///   X = phi [ C1, BB1], [C2, BB2]
391 ///   Y = add
392 ///   Z = select X, Y, 0
393 ///
394 /// because Y is not live in BB1/BB2.
395 ///
396 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
397                                                    const SelectInst &SI) {
398   // If the value is a non-instruction value like a constant or argument, it
399   // can always be mapped.
400   const Instruction *I = dyn_cast<Instruction>(V);
401   if (I == 0) return true;
402   
403   // If V is a PHI node defined in the same block as the condition PHI, we can
404   // map the arguments.
405   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
406   
407   if (const PHINode *VP = dyn_cast<PHINode>(I))
408     if (VP->getParent() == CondPHI->getParent())
409       return true;
410   
411   // Otherwise, if the PHI and select are defined in the same block and if V is
412   // defined in a different block, then we can transform it.
413   if (SI.getParent() == CondPHI->getParent() &&
414       I->getParent() != CondPHI->getParent())
415     return true;
416   
417   // Otherwise we have a 'hard' case and we can't tell without doing more
418   // detailed dominator based analysis, punt.
419   return false;
420 }
421
422 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
423 ///   SPF2(SPF1(A, B), C) 
424 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
425                                         SelectPatternFlavor SPF1,
426                                         Value *A, Value *B,
427                                         Instruction &Outer,
428                                         SelectPatternFlavor SPF2, Value *C) {
429   if (C == A || C == B) {
430     // MAX(MAX(A, B), B) -> MAX(A, B)
431     // MIN(MIN(a, b), a) -> MIN(a, b)
432     if (SPF1 == SPF2)
433       return ReplaceInstUsesWith(Outer, Inner);
434     
435     // MAX(MIN(a, b), a) -> a
436     // MIN(MAX(a, b), a) -> a
437     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
438         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
439         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
440         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
441       return ReplaceInstUsesWith(Outer, C);
442   }
443   
444   // TODO: MIN(MIN(A, 23), 97)
445   return 0;
446 }
447
448
449 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
450 /// both be) and we have an icmp instruction with zero, and we have an 'and'
451 /// with the non-constant value and a power of two we can turn the select
452 /// into a shift on the result of the 'and'.
453 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
454                                 ConstantInt *FalseVal,
455                                 InstCombiner::BuilderTy *Builder) {
456   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
457   if (!IC || !IC->isEquality())
458     return 0;
459
460   if (ConstantInt *C = dyn_cast<ConstantInt>(IC->getOperand(1)))
461     if (!C->isZero())
462       return 0;
463
464   ConstantInt *AndRHS;
465   Value *LHS = IC->getOperand(0);
466   if (LHS->getType() != SI.getType() ||
467       !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
468     return 0;
469
470   // If both select arms are non-zero see if we have a select of the form
471   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
472   // for 'x ? 2^n : 0' and fix the thing up at the end.
473   ConstantInt *Offset = 0;
474   if (!TrueVal->isZero() && !FalseVal->isZero()) {
475     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
476       Offset = FalseVal;
477     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
478       Offset = TrueVal;
479     else
480       return 0;
481
482     // Adjust TrueVal and FalseVal to the offset.
483     TrueVal = ConstantInt::get(Builder->getContext(),
484                                TrueVal->getValue() - Offset->getValue());
485     FalseVal = ConstantInt::get(Builder->getContext(),
486                                 FalseVal->getValue() - Offset->getValue());
487   }
488
489   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
490   if (!AndRHS->getValue().isPowerOf2() ||
491       (!TrueVal->getValue().isPowerOf2() &&
492        !FalseVal->getValue().isPowerOf2()))
493     return 0;
494
495   // Determine which shift is needed to transform result of the 'and' into the
496   // desired result.
497   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
498   unsigned ValZeros = ValC->getValue().logBase2();
499   unsigned AndZeros = AndRHS->getValue().logBase2();
500
501   Value *V = LHS;
502   if (ValZeros > AndZeros)
503     V = Builder->CreateShl(V, ValZeros - AndZeros);
504   else if (ValZeros < AndZeros)
505     V = Builder->CreateLShr(V, AndZeros - ValZeros);
506
507   // Okay, now we know that everything is set up, we just don't know whether we
508   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
509   bool ShouldNotVal = !TrueVal->isZero();
510   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
511   if (ShouldNotVal)
512     V = Builder->CreateXor(V, ValC);
513
514   // Apply an offset if needed.
515   if (Offset)
516     V = Builder->CreateAdd(V, Offset);
517   return V;
518 }
519
520 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
521   Value *CondVal = SI.getCondition();
522   Value *TrueVal = SI.getTrueValue();
523   Value *FalseVal = SI.getFalseValue();
524
525   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
526     return ReplaceInstUsesWith(SI, V);
527
528   if (SI.getType()->isIntegerTy(1)) {
529     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
530       if (C->getZExtValue()) {
531         // Change: A = select B, true, C --> A = or B, C
532         return BinaryOperator::CreateOr(CondVal, FalseVal);
533       }
534       // Change: A = select B, false, C --> A = and !B, C
535       Value *NotCond =
536         InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
537                                            "not."+CondVal->getName()), SI);
538       return BinaryOperator::CreateAnd(NotCond, FalseVal);
539     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
540       if (C->getZExtValue() == false) {
541         // Change: A = select B, C, false --> A = and B, C
542         return BinaryOperator::CreateAnd(CondVal, TrueVal);
543       }
544       // Change: A = select B, C, true --> A = or !B, C
545       Value *NotCond =
546         InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
547                                            "not."+CondVal->getName()), SI);
548       return BinaryOperator::CreateOr(NotCond, TrueVal);
549     }
550     
551     // select a, b, a  -> a&b
552     // select a, a, b  -> a|b
553     if (CondVal == TrueVal)
554       return BinaryOperator::CreateOr(CondVal, FalseVal);
555     else if (CondVal == FalseVal)
556       return BinaryOperator::CreateAnd(CondVal, TrueVal);
557   }
558
559   // Selecting between two integer constants?
560   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
561     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
562       // select C, 1, 0 -> zext C to int
563       if (FalseValC->isZero() && TrueValC->getValue() == 1)
564         return new ZExtInst(CondVal, SI.getType());
565
566       // select C, -1, 0 -> sext C to int
567       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
568         return new SExtInst(CondVal, SI.getType());
569       
570       // select C, 0, 1 -> zext !C to int
571       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
572         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
573         return new ZExtInst(NotCond, SI.getType());
574       }
575
576       // select C, 0, -1 -> sext !C to int
577       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
578         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
579         return new SExtInst(NotCond, SI.getType());
580       }
581
582       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
583         return ReplaceInstUsesWith(SI, V);
584     }
585
586   // See if we are selecting two values based on a comparison of the two values.
587   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
588     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
589       // Transform (X == Y) ? X : Y  -> Y
590       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
591         // This is not safe in general for floating point:  
592         // consider X== -0, Y== +0.
593         // It becomes safe if either operand is a nonzero constant.
594         ConstantFP *CFPt, *CFPf;
595         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
596               !CFPt->getValueAPF().isZero()) ||
597             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
598              !CFPf->getValueAPF().isZero()))
599         return ReplaceInstUsesWith(SI, FalseVal);
600       }
601       // Transform (X une Y) ? X : Y  -> X
602       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
603         // This is not safe in general for floating point:  
604         // consider X== -0, Y== +0.
605         // It becomes safe if either operand is a nonzero constant.
606         ConstantFP *CFPt, *CFPf;
607         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
608               !CFPt->getValueAPF().isZero()) ||
609             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
610              !CFPf->getValueAPF().isZero()))
611         return ReplaceInstUsesWith(SI, TrueVal);
612       }
613       // NOTE: if we wanted to, this is where to detect MIN/MAX
614
615     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
616       // Transform (X == Y) ? Y : X  -> X
617       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
618         // This is not safe in general for floating point:  
619         // consider X== -0, Y== +0.
620         // It becomes safe if either operand is a nonzero constant.
621         ConstantFP *CFPt, *CFPf;
622         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
623               !CFPt->getValueAPF().isZero()) ||
624             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
625              !CFPf->getValueAPF().isZero()))
626           return ReplaceInstUsesWith(SI, FalseVal);
627       }
628       // Transform (X une Y) ? Y : X  -> Y
629       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
630         // This is not safe in general for floating point:  
631         // consider X== -0, Y== +0.
632         // It becomes safe if either operand is a nonzero constant.
633         ConstantFP *CFPt, *CFPf;
634         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
635               !CFPt->getValueAPF().isZero()) ||
636             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
637              !CFPf->getValueAPF().isZero()))
638           return ReplaceInstUsesWith(SI, TrueVal);
639       }
640       // NOTE: if we wanted to, this is where to detect MIN/MAX
641     }
642     // NOTE: if we wanted to, this is where to detect ABS
643   }
644
645   // See if we are selecting two values based on a comparison of the two values.
646   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
647     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
648       return Result;
649
650   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
651     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
652       if (TI->hasOneUse() && FI->hasOneUse()) {
653         Instruction *AddOp = 0, *SubOp = 0;
654
655         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
656         if (TI->getOpcode() == FI->getOpcode())
657           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
658             return IV;
659
660         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
661         // even legal for FP.
662         if ((TI->getOpcode() == Instruction::Sub &&
663              FI->getOpcode() == Instruction::Add) ||
664             (TI->getOpcode() == Instruction::FSub &&
665              FI->getOpcode() == Instruction::FAdd)) {
666           AddOp = FI; SubOp = TI;
667         } else if ((FI->getOpcode() == Instruction::Sub &&
668                     TI->getOpcode() == Instruction::Add) ||
669                    (FI->getOpcode() == Instruction::FSub &&
670                     TI->getOpcode() == Instruction::FAdd)) {
671           AddOp = TI; SubOp = FI;
672         }
673
674         if (AddOp) {
675           Value *OtherAddOp = 0;
676           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
677             OtherAddOp = AddOp->getOperand(1);
678           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
679             OtherAddOp = AddOp->getOperand(0);
680           }
681
682           if (OtherAddOp) {
683             // So at this point we know we have (Y -> OtherAddOp):
684             //        select C, (add X, Y), (sub X, Z)
685             Value *NegVal;  // Compute -Z
686             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
687               NegVal = ConstantExpr::getNeg(C);
688             } else if (SI.getType()->isFloatingPointTy()) {
689               NegVal = InsertNewInstBefore(
690                     BinaryOperator::CreateFNeg(SubOp->getOperand(1),
691                                               "tmp"), SI);
692             } else {
693               NegVal = InsertNewInstBefore(
694                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
695                                               "tmp"), SI);
696             }
697
698             Value *NewTrueOp = OtherAddOp;
699             Value *NewFalseOp = NegVal;
700             if (AddOp != TI)
701               std::swap(NewTrueOp, NewFalseOp);
702             Instruction *NewSel =
703               SelectInst::Create(CondVal, NewTrueOp,
704                                  NewFalseOp, SI.getName() + ".p");
705
706             NewSel = InsertNewInstBefore(NewSel, SI);
707             if (SI.getType()->isFloatingPointTy())
708               return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
709             else
710               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
711           }
712         }
713       }
714
715   // See if we can fold the select into one of our operands.
716   if (SI.getType()->isIntegerTy()) {
717     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
718       return FoldI;
719     
720     // MAX(MAX(a, b), a) -> MAX(a, b)
721     // MIN(MIN(a, b), a) -> MIN(a, b)
722     // MAX(MIN(a, b), a) -> a
723     // MIN(MAX(a, b), a) -> a
724     Value *LHS, *RHS, *LHS2, *RHS2;
725     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
726       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
727         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 
728                                           SI, SPF, RHS))
729           return R;
730       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
731         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
732                                           SI, SPF, LHS))
733           return R;
734     }
735
736     // TODO.
737     // ABS(-X) -> ABS(X)
738     // ABS(ABS(X)) -> ABS(X)
739   }
740
741   // See if we can fold the select into a phi node if the condition is a select.
742   if (isa<PHINode>(SI.getCondition())) 
743     // The true/false values have to be live in the PHI predecessor's blocks.
744     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
745         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
746       if (Instruction *NV = FoldOpIntoPhi(SI))
747         return NV;
748
749   if (BinaryOperator::isNot(CondVal)) {
750     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
751     SI.setOperand(1, FalseVal);
752     SI.setOperand(2, TrueVal);
753     return &SI;
754   }
755
756   return 0;
757 }