[InstCombine] Add a new formula for SMIN.
[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 "InstCombineInternal.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20
21 #define DEBUG_TYPE "instcombine"
22
23 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
24 /// returning the kind and providing the out parameter results if we
25 /// successfully match.
26 static SelectPatternFlavor
27 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
28   SelectInst *SI = dyn_cast<SelectInst>(V);
29   if (!SI) return SPF_UNKNOWN;
30
31   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
32   if (!ICI) return SPF_UNKNOWN;
33
34   ICmpInst::Predicate Pred = ICI->getPredicate();
35   Value *CmpLHS = ICI->getOperand(0);
36   Value *CmpRHS = ICI->getOperand(1);
37   Value *TrueVal = SI->getTrueValue();
38   Value *FalseVal = SI->getFalseValue();
39
40   LHS = CmpLHS;
41   RHS = CmpRHS;
42
43   // (icmp X, Y) ? X : Y
44   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
45     switch (Pred) {
46     default: return SPF_UNKNOWN; // Equality.
47     case ICmpInst::ICMP_UGT:
48     case ICmpInst::ICMP_UGE: return SPF_UMAX;
49     case ICmpInst::ICMP_SGT:
50     case ICmpInst::ICMP_SGE: return SPF_SMAX;
51     case ICmpInst::ICMP_ULT:
52     case ICmpInst::ICMP_ULE: return SPF_UMIN;
53     case ICmpInst::ICMP_SLT:
54     case ICmpInst::ICMP_SLE: return SPF_SMIN;
55     }
56   }
57
58   // (icmp X, Y) ? Y : X
59   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
60     switch (Pred) {
61     default: return SPF_UNKNOWN; // Equality.
62     case ICmpInst::ICMP_UGT:
63     case ICmpInst::ICMP_UGE: return SPF_UMIN;
64     case ICmpInst::ICMP_SGT:
65     case ICmpInst::ICMP_SGE: return SPF_SMIN;
66     case ICmpInst::ICMP_ULT:
67     case ICmpInst::ICMP_ULE: return SPF_UMAX;
68     case ICmpInst::ICMP_SLT:
69     case ICmpInst::ICMP_SLE: return SPF_SMAX;
70     }
71   }
72
73   if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
74     if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
75         (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
76
77       // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
78       // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
79       if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
80         return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS;
81       }
82
83       // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
84       // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
85       if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
86         return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS;
87       }
88     }
89
90     // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
91     if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
92       if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
93           (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
94            match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
95         LHS = TrueVal;
96         RHS = FalseVal;
97         return SPF_SMIN;
98       }
99     }
100   }
101
102   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
103
104   return SPF_UNKNOWN;
105 }
106
107
108 /// GetSelectFoldableOperands - We want to turn code that looks like this:
109 ///   %C = or %A, %B
110 ///   %D = select %cond, %C, %A
111 /// into:
112 ///   %C = select %cond, %B, 0
113 ///   %D = or %A, %C
114 ///
115 /// Assuming that the specified instruction is an operand to the select, return
116 /// a bitmask indicating which operands of this instruction are foldable if they
117 /// equal the other incoming value of the select.
118 ///
119 static unsigned GetSelectFoldableOperands(Instruction *I) {
120   switch (I->getOpcode()) {
121   case Instruction::Add:
122   case Instruction::Mul:
123   case Instruction::And:
124   case Instruction::Or:
125   case Instruction::Xor:
126     return 3;              // Can fold through either operand.
127   case Instruction::Sub:   // Can only fold on the amount subtracted.
128   case Instruction::Shl:   // Can only fold on the shift amount.
129   case Instruction::LShr:
130   case Instruction::AShr:
131     return 1;
132   default:
133     return 0;              // Cannot fold
134   }
135 }
136
137 /// GetSelectFoldableConstant - For the same transformation as the previous
138 /// function, return the identity constant that goes into the select.
139 static Constant *GetSelectFoldableConstant(Instruction *I) {
140   switch (I->getOpcode()) {
141   default: llvm_unreachable("This cannot happen!");
142   case Instruction::Add:
143   case Instruction::Sub:
144   case Instruction::Or:
145   case Instruction::Xor:
146   case Instruction::Shl:
147   case Instruction::LShr:
148   case Instruction::AShr:
149     return Constant::getNullValue(I->getType());
150   case Instruction::And:
151     return Constant::getAllOnesValue(I->getType());
152   case Instruction::Mul:
153     return ConstantInt::get(I->getType(), 1);
154   }
155 }
156
157 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
158 /// have the same opcode and only one use each.  Try to simplify this.
159 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
160                                           Instruction *FI) {
161   if (TI->getNumOperands() == 1) {
162     // If this is a non-volatile load or a cast from the same type,
163     // merge.
164     if (TI->isCast()) {
165       Type *FIOpndTy = FI->getOperand(0)->getType();
166       if (TI->getOperand(0)->getType() != FIOpndTy)
167         return nullptr;
168       // The select condition may be a vector. We may only change the operand
169       // type if the vector width remains the same (and matches the condition).
170       Type *CondTy = SI.getCondition()->getType();
171       if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
172           CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
173         return nullptr;
174     } else {
175       return nullptr;  // unknown unary op.
176     }
177
178     // Fold this by inserting a select from the input values.
179     Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
180                                          FI->getOperand(0), SI.getName()+".v");
181     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
182                             TI->getType());
183   }
184
185   // Only handle binary operators here.
186   if (!isa<BinaryOperator>(TI))
187     return nullptr;
188
189   // Figure out if the operations have any operands in common.
190   Value *MatchOp, *OtherOpT, *OtherOpF;
191   bool MatchIsOpZero;
192   if (TI->getOperand(0) == FI->getOperand(0)) {
193     MatchOp  = TI->getOperand(0);
194     OtherOpT = TI->getOperand(1);
195     OtherOpF = FI->getOperand(1);
196     MatchIsOpZero = true;
197   } else if (TI->getOperand(1) == FI->getOperand(1)) {
198     MatchOp  = TI->getOperand(1);
199     OtherOpT = TI->getOperand(0);
200     OtherOpF = FI->getOperand(0);
201     MatchIsOpZero = false;
202   } else if (!TI->isCommutative()) {
203     return nullptr;
204   } else if (TI->getOperand(0) == FI->getOperand(1)) {
205     MatchOp  = TI->getOperand(0);
206     OtherOpT = TI->getOperand(1);
207     OtherOpF = FI->getOperand(0);
208     MatchIsOpZero = true;
209   } else if (TI->getOperand(1) == FI->getOperand(0)) {
210     MatchOp  = TI->getOperand(1);
211     OtherOpT = TI->getOperand(0);
212     OtherOpF = FI->getOperand(1);
213     MatchIsOpZero = true;
214   } else {
215     return nullptr;
216   }
217
218   // If we reach here, they do have operations in common.
219   Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
220                                        OtherOpF, SI.getName()+".v");
221
222   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
223     if (MatchIsOpZero)
224       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
225     else
226       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
227   }
228   llvm_unreachable("Shouldn't get here");
229 }
230
231 static bool isSelect01(Constant *C1, Constant *C2) {
232   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
233   if (!C1I)
234     return false;
235   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
236   if (!C2I)
237     return false;
238   if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
239     return false;
240   return C1I->isOne() || C1I->isAllOnesValue() ||
241          C2I->isOne() || C2I->isAllOnesValue();
242 }
243
244 /// FoldSelectIntoOp - Try fold the select into one of the operands to
245 /// facilitate further optimization.
246 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
247                                             Value *FalseVal) {
248   // See the comment above GetSelectFoldableOperands for a description of the
249   // transformation we are doing here.
250   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
251     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
252         !isa<Constant>(FalseVal)) {
253       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
254         unsigned OpToFold = 0;
255         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
256           OpToFold = 1;
257         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
258           OpToFold = 2;
259         }
260
261         if (OpToFold) {
262           Constant *C = GetSelectFoldableConstant(TVI);
263           Value *OOp = TVI->getOperand(2-OpToFold);
264           // Avoid creating select between 2 constants unless it's selecting
265           // between 0, 1 and -1.
266           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
267             Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
268             NewSel->takeName(TVI);
269             BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
270             BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
271                                                         FalseVal, NewSel);
272             if (isa<PossiblyExactOperator>(BO))
273               BO->setIsExact(TVI_BO->isExact());
274             if (isa<OverflowingBinaryOperator>(BO)) {
275               BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
276               BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
277             }
278             return BO;
279           }
280         }
281       }
282     }
283   }
284
285   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
286     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
287         !isa<Constant>(TrueVal)) {
288       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
289         unsigned OpToFold = 0;
290         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
291           OpToFold = 1;
292         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
293           OpToFold = 2;
294         }
295
296         if (OpToFold) {
297           Constant *C = GetSelectFoldableConstant(FVI);
298           Value *OOp = FVI->getOperand(2-OpToFold);
299           // Avoid creating select between 2 constants unless it's selecting
300           // between 0, 1 and -1.
301           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
302             Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
303             NewSel->takeName(FVI);
304             BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
305             BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
306                                                         TrueVal, NewSel);
307             if (isa<PossiblyExactOperator>(BO))
308               BO->setIsExact(FVI_BO->isExact());
309             if (isa<OverflowingBinaryOperator>(BO)) {
310               BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
311               BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
312             }
313             return BO;
314           }
315         }
316       }
317     }
318   }
319
320   return nullptr;
321 }
322
323 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
324 /// replaced with RepOp.
325 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
326                                      const TargetLibraryInfo *TLI,
327                                      const DataLayout &DL, DominatorTree *DT,
328                                      AssumptionCache *AC) {
329   // Trivial replacement.
330   if (V == Op)
331     return RepOp;
332
333   Instruction *I = dyn_cast<Instruction>(V);
334   if (!I)
335     return nullptr;
336
337   // If this is a binary operator, try to simplify it with the replaced op.
338   if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
339     if (B->getOperand(0) == Op)
340       return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), DL, TLI);
341     if (B->getOperand(1) == Op)
342       return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, DL, TLI);
343   }
344
345   // Same for CmpInsts.
346   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
347     if (C->getOperand(0) == Op)
348       return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), DL,
349                              TLI, DT, AC);
350     if (C->getOperand(1) == Op)
351       return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, DL,
352                              TLI, DT, AC);
353   }
354
355   // TODO: We could hand off more cases to instsimplify here.
356
357   // If all operands are constant after substituting Op for RepOp then we can
358   // constant fold the instruction.
359   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
360     // Build a list of all constant operands.
361     SmallVector<Constant*, 8> ConstOps;
362     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
363       if (I->getOperand(i) == Op)
364         ConstOps.push_back(CRepOp);
365       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
366         ConstOps.push_back(COp);
367       else
368         break;
369     }
370
371     // All operands were constants, fold it.
372     if (ConstOps.size() == I->getNumOperands()) {
373       if (CmpInst *C = dyn_cast<CmpInst>(I))
374         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
375                                                ConstOps[1], DL, TLI);
376
377       if (LoadInst *LI = dyn_cast<LoadInst>(I))
378         if (!LI->isVolatile())
379           return ConstantFoldLoadFromConstPtr(ConstOps[0], DL);
380
381       return ConstantFoldInstOperands(I->getOpcode(), I->getType(), ConstOps,
382                                       DL, TLI);
383     }
384   }
385
386   return nullptr;
387 }
388
389 /// foldSelectICmpAndOr - We want to turn:
390 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
391 /// into:
392 ///   (or (shl (and X, C1), C3), y)
393 /// iff:
394 ///   C1 and C2 are both powers of 2
395 /// where:
396 ///   C3 = Log(C2) - Log(C1)
397 ///
398 /// This transform handles cases where:
399 /// 1. The icmp predicate is inverted
400 /// 2. The select operands are reversed
401 /// 3. The magnitude of C2 and C1 are flipped
402 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
403                                   Value *FalseVal,
404                                   InstCombiner::BuilderTy *Builder) {
405   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
406   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
407     return nullptr;
408
409   Value *CmpLHS = IC->getOperand(0);
410   Value *CmpRHS = IC->getOperand(1);
411
412   if (!match(CmpRHS, m_Zero()))
413     return nullptr;
414
415   Value *X;
416   const APInt *C1;
417   if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
418     return nullptr;
419
420   const APInt *C2;
421   bool OrOnTrueVal = false;
422   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
423   if (!OrOnFalseVal)
424     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
425
426   if (!OrOnFalseVal && !OrOnTrueVal)
427     return nullptr;
428
429   Value *V = CmpLHS;
430   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
431
432   unsigned C1Log = C1->logBase2();
433   unsigned C2Log = C2->logBase2();
434   if (C2Log > C1Log) {
435     V = Builder->CreateZExtOrTrunc(V, Y->getType());
436     V = Builder->CreateShl(V, C2Log - C1Log);
437   } else if (C1Log > C2Log) {
438     V = Builder->CreateLShr(V, C1Log - C2Log);
439     V = Builder->CreateZExtOrTrunc(V, Y->getType());
440   } else
441     V = Builder->CreateZExtOrTrunc(V, Y->getType());
442
443   ICmpInst::Predicate Pred = IC->getPredicate();
444   if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
445       (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
446     V = Builder->CreateXor(V, *C2);
447
448   return Builder->CreateOr(V, Y);
449 }
450
451 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
452 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
453 ///
454 /// For example, we can fold the following code sequence:
455 /// \code
456 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
457 ///   %1 = icmp ne i32 %x, 0
458 ///   %2 = select i1 %1, i32 %0, i32 32
459 /// \code
460 /// 
461 /// into:
462 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
463 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
464                                   InstCombiner::BuilderTy *Builder) {
465   ICmpInst::Predicate Pred = ICI->getPredicate();
466   Value *CmpLHS = ICI->getOperand(0);
467   Value *CmpRHS = ICI->getOperand(1);
468
469   // Check if the condition value compares a value for equality against zero.
470   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
471     return nullptr;
472
473   Value *Count = FalseVal;
474   Value *ValueOnZero = TrueVal;
475   if (Pred == ICmpInst::ICMP_NE)
476     std::swap(Count, ValueOnZero);
477
478   // Skip zero extend/truncate.
479   Value *V = nullptr;
480   if (match(Count, m_ZExt(m_Value(V))) ||
481       match(Count, m_Trunc(m_Value(V))))
482     Count = V;
483
484   // Check if the value propagated on zero is a constant number equal to the
485   // sizeof in bits of 'Count'.
486   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
487   if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
488     return nullptr;
489
490   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
491   // input to the cttz/ctlz is used as LHS for the compare instruction.
492   if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
493       match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
494     IntrinsicInst *II = cast<IntrinsicInst>(Count);
495     IRBuilder<> Builder(II);
496     // Explicitly clear the 'undef_on_zero' flag.
497     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
498     Type *Ty = NewI->getArgOperand(1)->getType();
499     NewI->setArgOperand(1, Constant::getNullValue(Ty));
500     Builder.Insert(NewI);
501     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
502   }
503
504   return nullptr;
505 }
506
507 /// visitSelectInstWithICmp - Visit a SelectInst that has an
508 /// ICmpInst as its first operand.
509 ///
510 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
511                                                    ICmpInst *ICI) {
512   bool Changed = false;
513   ICmpInst::Predicate Pred = ICI->getPredicate();
514   Value *CmpLHS = ICI->getOperand(0);
515   Value *CmpRHS = ICI->getOperand(1);
516   Value *TrueVal = SI.getTrueValue();
517   Value *FalseVal = SI.getFalseValue();
518
519   // Check cases where the comparison is with a constant that
520   // can be adjusted to fit the min/max idiom. We may move or edit ICI
521   // here, so make sure the select is the only user.
522   if (ICI->hasOneUse())
523     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
524       // X < MIN ? T : F  -->  F
525       if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
526           && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
527         return ReplaceInstUsesWith(SI, FalseVal);
528       // X > MAX ? T : F  -->  F
529       else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
530                && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
531         return ReplaceInstUsesWith(SI, FalseVal);
532       switch (Pred) {
533       default: break;
534       case ICmpInst::ICMP_ULT:
535       case ICmpInst::ICMP_SLT:
536       case ICmpInst::ICMP_UGT:
537       case ICmpInst::ICMP_SGT: {
538         // These transformations only work for selects over integers.
539         IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
540         if (!SelectTy)
541           break;
542
543         Constant *AdjustedRHS;
544         if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
545           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
546         else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
547           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
548
549         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
550         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
551         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
552             (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
553           ; // Nothing to do here. Values match without any sign/zero extension.
554
555         // Types do not match. Instead of calculating this with mixed types
556         // promote all to the larger type. This enables scalar evolution to
557         // analyze this expression.
558         else if (CmpRHS->getType()->getScalarSizeInBits()
559                  < SelectTy->getBitWidth()) {
560           Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
561
562           // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
563           // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
564           // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
565           // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
566           if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
567                 sextRHS == FalseVal) {
568             CmpLHS = TrueVal;
569             AdjustedRHS = sextRHS;
570           } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
571                      sextRHS == TrueVal) {
572             CmpLHS = FalseVal;
573             AdjustedRHS = sextRHS;
574           } else if (ICI->isUnsigned()) {
575             Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
576             // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
577             // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
578             // zext + signed compare cannot be changed:
579             //    0xff <s 0x00, but 0x00ff >s 0x0000
580             if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
581                 zextRHS == FalseVal) {
582               CmpLHS = TrueVal;
583               AdjustedRHS = zextRHS;
584             } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
585                        zextRHS == TrueVal) {
586               CmpLHS = FalseVal;
587               AdjustedRHS = zextRHS;
588             } else
589               break;
590           } else
591             break;
592         } else
593           break;
594
595         Pred = ICmpInst::getSwappedPredicate(Pred);
596         CmpRHS = AdjustedRHS;
597         std::swap(FalseVal, TrueVal);
598         ICI->setPredicate(Pred);
599         ICI->setOperand(0, CmpLHS);
600         ICI->setOperand(1, CmpRHS);
601         SI.setOperand(1, TrueVal);
602         SI.setOperand(2, FalseVal);
603
604         // Move ICI instruction right before the select instruction. Otherwise
605         // the sext/zext value may be defined after the ICI instruction uses it.
606         ICI->moveBefore(&SI);
607
608         Changed = true;
609         break;
610       }
611       }
612     }
613
614   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
615   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
616   // FIXME: Type and constness constraints could be lifted, but we have to
617   //        watch code size carefully. We should consider xor instead of
618   //        sub/add when we decide to do that.
619   if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
620     if (TrueVal->getType() == Ty) {
621       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
622         ConstantInt *C1 = nullptr, *C2 = nullptr;
623         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
624           C1 = dyn_cast<ConstantInt>(TrueVal);
625           C2 = dyn_cast<ConstantInt>(FalseVal);
626         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
627           C1 = dyn_cast<ConstantInt>(FalseVal);
628           C2 = dyn_cast<ConstantInt>(TrueVal);
629         }
630         if (C1 && C2) {
631           // This shift results in either -1 or 0.
632           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
633
634           // Check if we can express the operation with a single or.
635           if (C2->isAllOnesValue())
636             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
637
638           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
639           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
640         }
641       }
642     }
643   }
644
645   // If we have an equality comparison then we know the value in one of the
646   // arms of the select. See if substituting this value into the arm and
647   // simplifying the result yields the same value as the other arm.
648   if (Pred == ICmpInst::ICMP_EQ) {
649     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
650             TrueVal ||
651         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
652             TrueVal)
653       return ReplaceInstUsesWith(SI, FalseVal);
654     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
655             FalseVal ||
656         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
657             FalseVal)
658       return ReplaceInstUsesWith(SI, FalseVal);
659   } else if (Pred == ICmpInst::ICMP_NE) {
660     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
661             FalseVal ||
662         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
663             FalseVal)
664       return ReplaceInstUsesWith(SI, TrueVal);
665     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TLI, DL, DT, AC) ==
666             TrueVal ||
667         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TLI, DL, DT, AC) ==
668             TrueVal)
669       return ReplaceInstUsesWith(SI, TrueVal);
670   }
671
672   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
673
674   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
675     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
676       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
677       SI.setOperand(1, CmpRHS);
678       Changed = true;
679     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
680       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
681       SI.setOperand(2, CmpRHS);
682       Changed = true;
683     }
684   }
685
686   if (unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits()) {
687     APInt MinSignedValue = APInt::getSignBit(BitWidth);
688     Value *X;
689     const APInt *Y, *C;
690     bool TrueWhenUnset;
691     bool IsBitTest = false;
692     if (ICmpInst::isEquality(Pred) &&
693         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
694         match(CmpRHS, m_Zero())) {
695       IsBitTest = true;
696       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
697     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
698       X = CmpLHS;
699       Y = &MinSignedValue;
700       IsBitTest = true;
701       TrueWhenUnset = false;
702     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
703       X = CmpLHS;
704       Y = &MinSignedValue;
705       IsBitTest = true;
706       TrueWhenUnset = true;
707     }
708     if (IsBitTest) {
709       Value *V = nullptr;
710       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
711       if (TrueWhenUnset && TrueVal == X &&
712           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
713         V = Builder->CreateAnd(X, ~(*Y));
714       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
715       else if (!TrueWhenUnset && FalseVal == X &&
716                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
717         V = Builder->CreateAnd(X, ~(*Y));
718       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
719       else if (TrueWhenUnset && FalseVal == X &&
720                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
721         V = Builder->CreateOr(X, *Y);
722       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
723       else if (!TrueWhenUnset && TrueVal == X &&
724                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
725         V = Builder->CreateOr(X, *Y);
726
727       if (V)
728         return ReplaceInstUsesWith(SI, V);
729     }
730   }
731
732   if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
733     return ReplaceInstUsesWith(SI, V);
734
735   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
736     return ReplaceInstUsesWith(SI, V);
737
738   return Changed ? &SI : nullptr;
739 }
740
741
742 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
743 /// PHI node (but the two may be in different blocks).  See if the true/false
744 /// values (V) are live in all of the predecessor blocks of the PHI.  For
745 /// example, cases like this cannot be mapped:
746 ///
747 ///   X = phi [ C1, BB1], [C2, BB2]
748 ///   Y = add
749 ///   Z = select X, Y, 0
750 ///
751 /// because Y is not live in BB1/BB2.
752 ///
753 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
754                                                    const SelectInst &SI) {
755   // If the value is a non-instruction value like a constant or argument, it
756   // can always be mapped.
757   const Instruction *I = dyn_cast<Instruction>(V);
758   if (!I) return true;
759
760   // If V is a PHI node defined in the same block as the condition PHI, we can
761   // map the arguments.
762   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
763
764   if (const PHINode *VP = dyn_cast<PHINode>(I))
765     if (VP->getParent() == CondPHI->getParent())
766       return true;
767
768   // Otherwise, if the PHI and select are defined in the same block and if V is
769   // defined in a different block, then we can transform it.
770   if (SI.getParent() == CondPHI->getParent() &&
771       I->getParent() != CondPHI->getParent())
772     return true;
773
774   // Otherwise we have a 'hard' case and we can't tell without doing more
775   // detailed dominator based analysis, punt.
776   return false;
777 }
778
779 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
780 ///   SPF2(SPF1(A, B), C)
781 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
782                                         SelectPatternFlavor SPF1,
783                                         Value *A, Value *B,
784                                         Instruction &Outer,
785                                         SelectPatternFlavor SPF2, Value *C) {
786   if (C == A || C == B) {
787     // MAX(MAX(A, B), B) -> MAX(A, B)
788     // MIN(MIN(a, b), a) -> MIN(a, b)
789     if (SPF1 == SPF2)
790       return ReplaceInstUsesWith(Outer, Inner);
791
792     // MAX(MIN(a, b), a) -> a
793     // MIN(MAX(a, b), a) -> a
794     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
795         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
796         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
797         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
798       return ReplaceInstUsesWith(Outer, C);
799   }
800
801   if (SPF1 == SPF2) {
802     if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
803       if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
804         APInt ACB = CB->getValue();
805         APInt ACC = CC->getValue();
806
807         // MIN(MIN(A, 23), 97) -> MIN(A, 23)
808         // MAX(MAX(A, 97), 23) -> MAX(A, 97)
809         if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
810             (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
811             (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
812             (SPF1 == SPF_SMAX && ACB.sge(ACC)))
813           return ReplaceInstUsesWith(Outer, Inner);
814
815         // MIN(MIN(A, 97), 23) -> MIN(A, 23)
816         // MAX(MAX(A, 23), 97) -> MAX(A, 97)
817         if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
818             (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
819             (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
820             (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
821           Outer.replaceUsesOfWith(Inner, A);
822           return &Outer;
823         }
824       }
825     }
826   }
827
828   // ABS(ABS(X)) -> ABS(X)
829   // NABS(NABS(X)) -> NABS(X)
830   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
831     return ReplaceInstUsesWith(Outer, Inner);
832   }
833
834   // ABS(NABS(X)) -> ABS(X)
835   // NABS(ABS(X)) -> NABS(X)
836   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
837       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
838     SelectInst *SI = cast<SelectInst>(Inner);
839     Value *NewSI = Builder->CreateSelect(
840         SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
841     return ReplaceInstUsesWith(Outer, NewSI);
842   }
843   return nullptr;
844 }
845
846 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
847 /// both be) and we have an icmp instruction with zero, and we have an 'and'
848 /// with the non-constant value and a power of two we can turn the select
849 /// into a shift on the result of the 'and'.
850 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
851                                 ConstantInt *FalseVal,
852                                 InstCombiner::BuilderTy *Builder) {
853   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
854   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
855     return nullptr;
856
857   if (!match(IC->getOperand(1), m_Zero()))
858     return nullptr;
859
860   ConstantInt *AndRHS;
861   Value *LHS = IC->getOperand(0);
862   if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
863     return nullptr;
864
865   // If both select arms are non-zero see if we have a select of the form
866   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
867   // for 'x ? 2^n : 0' and fix the thing up at the end.
868   ConstantInt *Offset = nullptr;
869   if (!TrueVal->isZero() && !FalseVal->isZero()) {
870     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
871       Offset = FalseVal;
872     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
873       Offset = TrueVal;
874     else
875       return nullptr;
876
877     // Adjust TrueVal and FalseVal to the offset.
878     TrueVal = ConstantInt::get(Builder->getContext(),
879                                TrueVal->getValue() - Offset->getValue());
880     FalseVal = ConstantInt::get(Builder->getContext(),
881                                 FalseVal->getValue() - Offset->getValue());
882   }
883
884   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
885   if (!AndRHS->getValue().isPowerOf2() ||
886       (!TrueVal->getValue().isPowerOf2() &&
887        !FalseVal->getValue().isPowerOf2()))
888     return nullptr;
889
890   // Determine which shift is needed to transform result of the 'and' into the
891   // desired result.
892   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
893   unsigned ValZeros = ValC->getValue().logBase2();
894   unsigned AndZeros = AndRHS->getValue().logBase2();
895
896   // If types don't match we can still convert the select by introducing a zext
897   // or a trunc of the 'and'. The trunc case requires that all of the truncated
898   // bits are zero, we can figure that out by looking at the 'and' mask.
899   if (AndZeros >= ValC->getBitWidth())
900     return nullptr;
901
902   Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
903   if (ValZeros > AndZeros)
904     V = Builder->CreateShl(V, ValZeros - AndZeros);
905   else if (ValZeros < AndZeros)
906     V = Builder->CreateLShr(V, AndZeros - ValZeros);
907
908   // Okay, now we know that everything is set up, we just don't know whether we
909   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
910   bool ShouldNotVal = !TrueVal->isZero();
911   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
912   if (ShouldNotVal)
913     V = Builder->CreateXor(V, ValC);
914
915   // Apply an offset if needed.
916   if (Offset)
917     V = Builder->CreateAdd(V, Offset);
918   return V;
919 }
920
921 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
922   Value *CondVal = SI.getCondition();
923   Value *TrueVal = SI.getTrueValue();
924   Value *FalseVal = SI.getFalseValue();
925
926   if (Value *V =
927           SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
928     return ReplaceInstUsesWith(SI, V);
929
930   if (SI.getType()->isIntegerTy(1)) {
931     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
932       if (C->getZExtValue()) {
933         // Change: A = select B, true, C --> A = or B, C
934         return BinaryOperator::CreateOr(CondVal, FalseVal);
935       }
936       // Change: A = select B, false, C --> A = and !B, C
937       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
938       return BinaryOperator::CreateAnd(NotCond, FalseVal);
939     }
940     if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
941       if (!C->getZExtValue()) {
942         // Change: A = select B, C, false --> A = and B, C
943         return BinaryOperator::CreateAnd(CondVal, TrueVal);
944       }
945       // Change: A = select B, C, true --> A = or !B, C
946       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
947       return BinaryOperator::CreateOr(NotCond, TrueVal);
948     }
949
950     // select a, b, a  -> a&b
951     // select a, a, b  -> a|b
952     if (CondVal == TrueVal)
953       return BinaryOperator::CreateOr(CondVal, FalseVal);
954     if (CondVal == FalseVal)
955       return BinaryOperator::CreateAnd(CondVal, TrueVal);
956
957     // select a, ~a, b -> (~a)&b
958     // select a, b, ~a -> (~a)|b
959     if (match(TrueVal, m_Not(m_Specific(CondVal))))
960       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
961     if (match(FalseVal, m_Not(m_Specific(CondVal))))
962       return BinaryOperator::CreateOr(TrueVal, FalseVal);
963   }
964
965   // Selecting between two integer constants?
966   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
967     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
968       // select C, 1, 0 -> zext C to int
969       if (FalseValC->isZero() && TrueValC->getValue() == 1)
970         return new ZExtInst(CondVal, SI.getType());
971
972       // select C, -1, 0 -> sext C to int
973       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
974         return new SExtInst(CondVal, SI.getType());
975
976       // select C, 0, 1 -> zext !C to int
977       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
978         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
979         return new ZExtInst(NotCond, SI.getType());
980       }
981
982       // select C, 0, -1 -> sext !C to int
983       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
984         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
985         return new SExtInst(NotCond, SI.getType());
986       }
987
988       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
989         return ReplaceInstUsesWith(SI, V);
990     }
991
992   // See if we are selecting two values based on a comparison of the two values.
993   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
994     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
995       // Transform (X == Y) ? X : Y  -> Y
996       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
997         // This is not safe in general for floating point:
998         // consider X== -0, Y== +0.
999         // It becomes safe if either operand is a nonzero constant.
1000         ConstantFP *CFPt, *CFPf;
1001         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1002               !CFPt->getValueAPF().isZero()) ||
1003             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1004              !CFPf->getValueAPF().isZero()))
1005         return ReplaceInstUsesWith(SI, FalseVal);
1006       }
1007       // Transform (X une Y) ? X : Y  -> X
1008       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1009         // This is not safe in general for floating point:
1010         // consider X== -0, Y== +0.
1011         // It becomes safe if either operand is a nonzero constant.
1012         ConstantFP *CFPt, *CFPf;
1013         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1014               !CFPt->getValueAPF().isZero()) ||
1015             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1016              !CFPf->getValueAPF().isZero()))
1017         return ReplaceInstUsesWith(SI, TrueVal);
1018       }
1019
1020       // Canonicalize to use ordered comparisons by swapping the select
1021       // operands.
1022       //
1023       // e.g.
1024       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1025       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1026         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1027         Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1028                                              FCI->getName() + ".inv");
1029
1030         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1031                                   SI.getName() + ".p");
1032       }
1033
1034       // NOTE: if we wanted to, this is where to detect MIN/MAX
1035     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1036       // Transform (X == Y) ? Y : X  -> X
1037       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1038         // This is not safe in general for floating point:
1039         // consider X== -0, Y== +0.
1040         // It becomes safe if either operand is a nonzero constant.
1041         ConstantFP *CFPt, *CFPf;
1042         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1043               !CFPt->getValueAPF().isZero()) ||
1044             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1045              !CFPf->getValueAPF().isZero()))
1046           return ReplaceInstUsesWith(SI, FalseVal);
1047       }
1048       // Transform (X une Y) ? Y : X  -> Y
1049       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1050         // This is not safe in general for floating point:
1051         // consider X== -0, Y== +0.
1052         // It becomes safe if either operand is a nonzero constant.
1053         ConstantFP *CFPt, *CFPf;
1054         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1055               !CFPt->getValueAPF().isZero()) ||
1056             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1057              !CFPf->getValueAPF().isZero()))
1058           return ReplaceInstUsesWith(SI, TrueVal);
1059       }
1060
1061       // Canonicalize to use ordered comparisons by swapping the select
1062       // operands.
1063       //
1064       // e.g.
1065       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1066       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1067         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1068         Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1069                                              FCI->getName() + ".inv");
1070
1071         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1072                                   SI.getName() + ".p");
1073       }
1074
1075       // NOTE: if we wanted to, this is where to detect MIN/MAX
1076     }
1077     // NOTE: if we wanted to, this is where to detect ABS
1078   }
1079
1080   // See if we are selecting two values based on a comparison of the two values.
1081   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1082     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
1083       return Result;
1084
1085   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
1086     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
1087       if (TI->hasOneUse() && FI->hasOneUse()) {
1088         Instruction *AddOp = nullptr, *SubOp = nullptr;
1089
1090         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1091         if (TI->getOpcode() == FI->getOpcode())
1092           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
1093             return IV;
1094
1095         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
1096         // even legal for FP.
1097         if ((TI->getOpcode() == Instruction::Sub &&
1098              FI->getOpcode() == Instruction::Add) ||
1099             (TI->getOpcode() == Instruction::FSub &&
1100              FI->getOpcode() == Instruction::FAdd)) {
1101           AddOp = FI; SubOp = TI;
1102         } else if ((FI->getOpcode() == Instruction::Sub &&
1103                     TI->getOpcode() == Instruction::Add) ||
1104                    (FI->getOpcode() == Instruction::FSub &&
1105                     TI->getOpcode() == Instruction::FAdd)) {
1106           AddOp = TI; SubOp = FI;
1107         }
1108
1109         if (AddOp) {
1110           Value *OtherAddOp = nullptr;
1111           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1112             OtherAddOp = AddOp->getOperand(1);
1113           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1114             OtherAddOp = AddOp->getOperand(0);
1115           }
1116
1117           if (OtherAddOp) {
1118             // So at this point we know we have (Y -> OtherAddOp):
1119             //        select C, (add X, Y), (sub X, Z)
1120             Value *NegVal;  // Compute -Z
1121             if (SI.getType()->isFPOrFPVectorTy()) {
1122               NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
1123               if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1124                 FastMathFlags Flags = AddOp->getFastMathFlags();
1125                 Flags &= SubOp->getFastMathFlags();
1126                 NegInst->setFastMathFlags(Flags);
1127               }
1128             } else {
1129               NegVal = Builder->CreateNeg(SubOp->getOperand(1));
1130             }
1131
1132             Value *NewTrueOp = OtherAddOp;
1133             Value *NewFalseOp = NegVal;
1134             if (AddOp != TI)
1135               std::swap(NewTrueOp, NewFalseOp);
1136             Value *NewSel =
1137               Builder->CreateSelect(CondVal, NewTrueOp,
1138                                     NewFalseOp, SI.getName() + ".p");
1139
1140             if (SI.getType()->isFPOrFPVectorTy()) {
1141               Instruction *RI =
1142                 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1143
1144               FastMathFlags Flags = AddOp->getFastMathFlags();
1145               Flags &= SubOp->getFastMathFlags();
1146               RI->setFastMathFlags(Flags);
1147               return RI;
1148             } else
1149               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1150           }
1151         }
1152       }
1153
1154   // See if we can fold the select into one of our operands.
1155   if (SI.getType()->isIntegerTy()) {
1156     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1157       return FoldI;
1158
1159     Value *LHS, *RHS, *LHS2, *RHS2;
1160     SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS);
1161
1162     // MAX(MAX(a, b), a) -> MAX(a, b)
1163     // MIN(MIN(a, b), a) -> MIN(a, b)
1164     // MAX(MIN(a, b), a) -> a
1165     // MIN(MAX(a, b), a) -> a
1166     if (SPF) {
1167       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
1168         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1169                                           SI, SPF, RHS))
1170           return R;
1171       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
1172         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1173                                           SI, SPF, LHS))
1174           return R;
1175     }
1176
1177     // MAX(~a, ~b) -> ~MIN(a, b)
1178     if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1179       if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1180           IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1181
1182         // This transform adds a xor operation and that extra cost needs to be
1183         // justified.  We look for simplifications that will result from
1184         // applying this rule:
1185
1186         bool Profitable =
1187             (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1188             (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1189             (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1190
1191         if (Profitable) {
1192           Value *NewLHS = Builder->CreateNot(LHS);
1193           Value *NewRHS = Builder->CreateNot(RHS);
1194           Value *NewCmp = SPF == SPF_SMAX
1195                               ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1196                               : Builder->CreateICmpULT(NewLHS, NewRHS);
1197           Value *NewSI =
1198               Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1199           return ReplaceInstUsesWith(SI, NewSI);
1200         }
1201       }
1202     }
1203
1204     // TODO.
1205     // ABS(-X) -> ABS(X)
1206   }
1207
1208   // See if we can fold the select into a phi node if the condition is a select.
1209   if (isa<PHINode>(SI.getCondition()))
1210     // The true/false values have to be live in the PHI predecessor's blocks.
1211     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1212         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1213       if (Instruction *NV = FoldOpIntoPhi(SI))
1214         return NV;
1215
1216   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1217     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1218       // select(C, select(C, a, b), c) -> select(C, a, c)
1219       if (TrueSI->getCondition() == CondVal) {
1220         if (SI.getTrueValue() == TrueSI->getTrueValue())
1221           return nullptr;
1222         SI.setOperand(1, TrueSI->getTrueValue());
1223         return &SI;
1224       }
1225       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1226       // We choose this as normal form to enable folding on the And and shortening
1227       // paths for the values (this helps GetUnderlyingObjects() for example).
1228       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1229         Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1230         SI.setOperand(0, And);
1231         SI.setOperand(1, TrueSI->getTrueValue());
1232         return &SI;
1233       }
1234     }
1235   }
1236   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1237     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1238       // select(C, a, select(C, b, c)) -> select(C, a, c)
1239       if (FalseSI->getCondition() == CondVal) {
1240         if (SI.getFalseValue() == FalseSI->getFalseValue())
1241           return nullptr;
1242         SI.setOperand(2, FalseSI->getFalseValue());
1243         return &SI;
1244       }
1245       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1246       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1247         Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1248         SI.setOperand(0, Or);
1249         SI.setOperand(2, FalseSI->getFalseValue());
1250         return &SI;
1251       }
1252     }
1253   }
1254
1255   if (BinaryOperator::isNot(CondVal)) {
1256     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1257     SI.setOperand(1, FalseVal);
1258     SI.setOperand(2, TrueVal);
1259     return &SI;
1260   }
1261
1262   if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
1263     unsigned VWidth = VecTy->getNumElements();
1264     APInt UndefElts(VWidth, 0);
1265     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1266     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1267       if (V != &SI)
1268         return ReplaceInstUsesWith(SI, V);
1269       return &SI;
1270     }
1271
1272     if (isa<ConstantAggregateZero>(CondVal)) {
1273       return ReplaceInstUsesWith(SI, FalseVal);
1274     }
1275   }
1276
1277   return nullptr;
1278 }