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