]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
Upgrade to OpenSSH 6.8p1.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 /// foldSelectICmpAndOr - We want to turn:
280 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
281 /// into:
282 ///   (or (shl (and X, C1), C3), y)
283 /// iff:
284 ///   C1 and C2 are both powers of 2
285 /// where:
286 ///   C3 = Log(C2) - Log(C1)
287 ///
288 /// This transform handles cases where:
289 /// 1. The icmp predicate is inverted
290 /// 2. The select operands are reversed
291 /// 3. The magnitude of C2 and C1 are flipped
292 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
293                                   Value *FalseVal,
294                                   InstCombiner::BuilderTy *Builder) {
295   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
296   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
297     return nullptr;
298
299   Value *CmpLHS = IC->getOperand(0);
300   Value *CmpRHS = IC->getOperand(1);
301
302   if (!match(CmpRHS, m_Zero()))
303     return nullptr;
304
305   Value *X;
306   const APInt *C1;
307   if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
308     return nullptr;
309
310   const APInt *C2;
311   bool OrOnTrueVal = false;
312   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
313   if (!OrOnFalseVal)
314     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
315
316   if (!OrOnFalseVal && !OrOnTrueVal)
317     return nullptr;
318
319   Value *V = CmpLHS;
320   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
321
322   unsigned C1Log = C1->logBase2();
323   unsigned C2Log = C2->logBase2();
324   if (C2Log > C1Log) {
325     V = Builder->CreateZExtOrTrunc(V, Y->getType());
326     V = Builder->CreateShl(V, C2Log - C1Log);
327   } else if (C1Log > C2Log) {
328     V = Builder->CreateLShr(V, C1Log - C2Log);
329     V = Builder->CreateZExtOrTrunc(V, Y->getType());
330   } else
331     V = Builder->CreateZExtOrTrunc(V, Y->getType());
332
333   ICmpInst::Predicate Pred = IC->getPredicate();
334   if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
335       (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
336     V = Builder->CreateXor(V, *C2);
337
338   return Builder->CreateOr(V, Y);
339 }
340
341 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
342 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
343 ///
344 /// For example, we can fold the following code sequence:
345 /// \code
346 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
347 ///   %1 = icmp ne i32 %x, 0
348 ///   %2 = select i1 %1, i32 %0, i32 32
349 /// \code
350 /// 
351 /// into:
352 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
353 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
354                                   InstCombiner::BuilderTy *Builder) {
355   ICmpInst::Predicate Pred = ICI->getPredicate();
356   Value *CmpLHS = ICI->getOperand(0);
357   Value *CmpRHS = ICI->getOperand(1);
358
359   // Check if the condition value compares a value for equality against zero.
360   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
361     return nullptr;
362
363   Value *Count = FalseVal;
364   Value *ValueOnZero = TrueVal;
365   if (Pred == ICmpInst::ICMP_NE)
366     std::swap(Count, ValueOnZero);
367
368   // Skip zero extend/truncate.
369   Value *V = nullptr;
370   if (match(Count, m_ZExt(m_Value(V))) ||
371       match(Count, m_Trunc(m_Value(V))))
372     Count = V;
373
374   // Check if the value propagated on zero is a constant number equal to the
375   // sizeof in bits of 'Count'.
376   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
377   if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
378     return nullptr;
379
380   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
381   // input to the cttz/ctlz is used as LHS for the compare instruction.
382   if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
383       match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
384     IntrinsicInst *II = cast<IntrinsicInst>(Count);
385     IRBuilder<> Builder(II);
386     // Explicitly clear the 'undef_on_zero' flag.
387     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
388     Type *Ty = NewI->getArgOperand(1)->getType();
389     NewI->setArgOperand(1, Constant::getNullValue(Ty));
390     Builder.Insert(NewI);
391     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
392   }
393
394   return nullptr;
395 }
396
397 /// visitSelectInstWithICmp - Visit a SelectInst that has an
398 /// ICmpInst as its first operand.
399 ///
400 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
401                                                    ICmpInst *ICI) {
402   bool Changed = false;
403   ICmpInst::Predicate Pred = ICI->getPredicate();
404   Value *CmpLHS = ICI->getOperand(0);
405   Value *CmpRHS = ICI->getOperand(1);
406   Value *TrueVal = SI.getTrueValue();
407   Value *FalseVal = SI.getFalseValue();
408
409   // Check cases where the comparison is with a constant that
410   // can be adjusted to fit the min/max idiom. We may move or edit ICI
411   // here, so make sure the select is the only user.
412   if (ICI->hasOneUse())
413     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
414       switch (Pred) {
415       default: break;
416       case ICmpInst::ICMP_ULT:
417       case ICmpInst::ICMP_SLT:
418       case ICmpInst::ICMP_UGT:
419       case ICmpInst::ICMP_SGT: {
420         // These transformations only work for selects over integers.
421         IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
422         if (!SelectTy)
423           break;
424
425         Constant *AdjustedRHS;
426         if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
427           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
428         else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
429           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
430
431         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
432         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
433         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
434             (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
435           ; // Nothing to do here. Values match without any sign/zero extension.
436
437         // Types do not match. Instead of calculating this with mixed types
438         // promote all to the larger type. This enables scalar evolution to
439         // analyze this expression.
440         else if (CmpRHS->getType()->getScalarSizeInBits()
441                  < SelectTy->getBitWidth()) {
442           Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
443
444           // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
445           // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
446           // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
447           // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
448           if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
449                 sextRHS == FalseVal) {
450             CmpLHS = TrueVal;
451             AdjustedRHS = sextRHS;
452           } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
453                      sextRHS == TrueVal) {
454             CmpLHS = FalseVal;
455             AdjustedRHS = sextRHS;
456           } else if (ICI->isUnsigned()) {
457             Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
458             // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
459             // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
460             // zext + signed compare cannot be changed:
461             //    0xff <s 0x00, but 0x00ff >s 0x0000
462             if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
463                 zextRHS == FalseVal) {
464               CmpLHS = TrueVal;
465               AdjustedRHS = zextRHS;
466             } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
467                        zextRHS == TrueVal) {
468               CmpLHS = FalseVal;
469               AdjustedRHS = zextRHS;
470             } else
471               break;
472           } else
473             break;
474         } else
475           break;
476
477         Pred = ICmpInst::getSwappedPredicate(Pred);
478         CmpRHS = AdjustedRHS;
479         std::swap(FalseVal, TrueVal);
480         ICI->setPredicate(Pred);
481         ICI->setOperand(0, CmpLHS);
482         ICI->setOperand(1, CmpRHS);
483         SI.setOperand(1, TrueVal);
484         SI.setOperand(2, FalseVal);
485
486         // Move ICI instruction right before the select instruction. Otherwise
487         // the sext/zext value may be defined after the ICI instruction uses it.
488         ICI->moveBefore(&SI);
489
490         Changed = true;
491         break;
492       }
493       }
494     }
495
496   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
497   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
498   // FIXME: Type and constness constraints could be lifted, but we have to
499   //        watch code size carefully. We should consider xor instead of
500   //        sub/add when we decide to do that.
501   if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
502     if (TrueVal->getType() == Ty) {
503       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
504         ConstantInt *C1 = nullptr, *C2 = nullptr;
505         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
506           C1 = dyn_cast<ConstantInt>(TrueVal);
507           C2 = dyn_cast<ConstantInt>(FalseVal);
508         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
509           C1 = dyn_cast<ConstantInt>(FalseVal);
510           C2 = dyn_cast<ConstantInt>(TrueVal);
511         }
512         if (C1 && C2) {
513           // This shift results in either -1 or 0.
514           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
515
516           // Check if we can express the operation with a single or.
517           if (C2->isAllOnesValue())
518             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
519
520           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
521           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
522         }
523       }
524     }
525   }
526
527   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
528
529   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
530     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
531       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
532       SI.setOperand(1, CmpRHS);
533       Changed = true;
534     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
535       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
536       SI.setOperand(2, CmpRHS);
537       Changed = true;
538     }
539   }
540
541   {
542     unsigned BitWidth = DL.getTypeSizeInBits(TrueVal->getType());
543     APInt MinSignedValue = APInt::getSignBit(BitWidth);
544     Value *X;
545     const APInt *Y, *C;
546     bool TrueWhenUnset;
547     bool IsBitTest = false;
548     if (ICmpInst::isEquality(Pred) &&
549         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
550         match(CmpRHS, m_Zero())) {
551       IsBitTest = true;
552       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
553     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
554       X = CmpLHS;
555       Y = &MinSignedValue;
556       IsBitTest = true;
557       TrueWhenUnset = false;
558     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
559       X = CmpLHS;
560       Y = &MinSignedValue;
561       IsBitTest = true;
562       TrueWhenUnset = true;
563     }
564     if (IsBitTest) {
565       Value *V = nullptr;
566       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
567       if (TrueWhenUnset && TrueVal == X &&
568           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
569         V = Builder->CreateAnd(X, ~(*Y));
570       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
571       else if (!TrueWhenUnset && FalseVal == X &&
572                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
573         V = Builder->CreateAnd(X, ~(*Y));
574       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
575       else if (TrueWhenUnset && FalseVal == X &&
576                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
577         V = Builder->CreateOr(X, *Y);
578       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
579       else if (!TrueWhenUnset && TrueVal == X &&
580                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
581         V = Builder->CreateOr(X, *Y);
582
583       if (V)
584         return ReplaceInstUsesWith(SI, V);
585     }
586   }
587
588   if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
589     return ReplaceInstUsesWith(SI, V);
590
591   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
592     return ReplaceInstUsesWith(SI, V);
593
594   return Changed ? &SI : nullptr;
595 }
596
597
598 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
599 /// PHI node (but the two may be in different blocks).  See if the true/false
600 /// values (V) are live in all of the predecessor blocks of the PHI.  For
601 /// example, cases like this cannot be mapped:
602 ///
603 ///   X = phi [ C1, BB1], [C2, BB2]
604 ///   Y = add
605 ///   Z = select X, Y, 0
606 ///
607 /// because Y is not live in BB1/BB2.
608 ///
609 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
610                                                    const SelectInst &SI) {
611   // If the value is a non-instruction value like a constant or argument, it
612   // can always be mapped.
613   const Instruction *I = dyn_cast<Instruction>(V);
614   if (!I) return true;
615
616   // If V is a PHI node defined in the same block as the condition PHI, we can
617   // map the arguments.
618   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
619
620   if (const PHINode *VP = dyn_cast<PHINode>(I))
621     if (VP->getParent() == CondPHI->getParent())
622       return true;
623
624   // Otherwise, if the PHI and select are defined in the same block and if V is
625   // defined in a different block, then we can transform it.
626   if (SI.getParent() == CondPHI->getParent() &&
627       I->getParent() != CondPHI->getParent())
628     return true;
629
630   // Otherwise we have a 'hard' case and we can't tell without doing more
631   // detailed dominator based analysis, punt.
632   return false;
633 }
634
635 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
636 ///   SPF2(SPF1(A, B), C)
637 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
638                                         SelectPatternFlavor SPF1,
639                                         Value *A, Value *B,
640                                         Instruction &Outer,
641                                         SelectPatternFlavor SPF2, Value *C) {
642   if (C == A || C == B) {
643     // MAX(MAX(A, B), B) -> MAX(A, B)
644     // MIN(MIN(a, b), a) -> MIN(a, b)
645     if (SPF1 == SPF2)
646       return ReplaceInstUsesWith(Outer, Inner);
647
648     // MAX(MIN(a, b), a) -> a
649     // MIN(MAX(a, b), a) -> a
650     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
651         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
652         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
653         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
654       return ReplaceInstUsesWith(Outer, C);
655   }
656
657   if (SPF1 == SPF2) {
658     if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
659       if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
660         APInt ACB = CB->getValue();
661         APInt ACC = CC->getValue();
662
663         // MIN(MIN(A, 23), 97) -> MIN(A, 23)
664         // MAX(MAX(A, 97), 23) -> MAX(A, 97)
665         if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
666             (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
667             (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
668             (SPF1 == SPF_SMAX && ACB.sge(ACC)))
669           return ReplaceInstUsesWith(Outer, Inner);
670
671         // MIN(MIN(A, 97), 23) -> MIN(A, 23)
672         // MAX(MAX(A, 23), 97) -> MAX(A, 97)
673         if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
674             (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
675             (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
676             (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
677           Outer.replaceUsesOfWith(Inner, A);
678           return &Outer;
679         }
680       }
681     }
682   }
683
684   // ABS(ABS(X)) -> ABS(X)
685   // NABS(NABS(X)) -> NABS(X)
686   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
687     return ReplaceInstUsesWith(Outer, Inner);
688   }
689
690   // ABS(NABS(X)) -> ABS(X)
691   // NABS(ABS(X)) -> NABS(X)
692   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
693       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
694     SelectInst *SI = cast<SelectInst>(Inner);
695     Value *NewSI = Builder->CreateSelect(
696         SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
697     return ReplaceInstUsesWith(Outer, NewSI);
698   }
699
700   auto IsFreeOrProfitableToInvert =
701       [&](Value *V, Value *&NotV, bool &ElidesXor) {
702     if (match(V, m_Not(m_Value(NotV)))) {
703       // If V has at most 2 uses then we can get rid of the xor operation
704       // entirely.
705       ElidesXor |= !V->hasNUsesOrMore(3);
706       return true;
707     }
708
709     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
710       NotV = nullptr;
711       return true;
712     }
713
714     return false;
715   };
716
717   Value *NotA, *NotB, *NotC;
718   bool ElidesXor = false;
719
720   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
721   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
722   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
723   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
724   //
725   // This transform is performance neutral if we can elide at least one xor from
726   // the set of three operands, since we'll be tacking on an xor at the very
727   // end.
728   if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
729       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
730       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
731     if (!NotA)
732       NotA = Builder->CreateNot(A);
733     if (!NotB)
734       NotB = Builder->CreateNot(B);
735     if (!NotC)
736       NotC = Builder->CreateNot(C);
737
738     Value *NewInner = generateMinMaxSelectPattern(
739         Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
740     Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
741         Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
742     return ReplaceInstUsesWith(Outer, NewOuter);
743   }
744
745   return nullptr;
746 }
747
748 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
749 /// both be) and we have an icmp instruction with zero, and we have an 'and'
750 /// with the non-constant value and a power of two we can turn the select
751 /// into a shift on the result of the 'and'.
752 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
753                                 ConstantInt *FalseVal,
754                                 InstCombiner::BuilderTy *Builder) {
755   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
756   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
757     return nullptr;
758
759   if (!match(IC->getOperand(1), m_Zero()))
760     return nullptr;
761
762   ConstantInt *AndRHS;
763   Value *LHS = IC->getOperand(0);
764   if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
765     return nullptr;
766
767   // If both select arms are non-zero see if we have a select of the form
768   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
769   // for 'x ? 2^n : 0' and fix the thing up at the end.
770   ConstantInt *Offset = nullptr;
771   if (!TrueVal->isZero() && !FalseVal->isZero()) {
772     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
773       Offset = FalseVal;
774     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
775       Offset = TrueVal;
776     else
777       return nullptr;
778
779     // Adjust TrueVal and FalseVal to the offset.
780     TrueVal = ConstantInt::get(Builder->getContext(),
781                                TrueVal->getValue() - Offset->getValue());
782     FalseVal = ConstantInt::get(Builder->getContext(),
783                                 FalseVal->getValue() - Offset->getValue());
784   }
785
786   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
787   if (!AndRHS->getValue().isPowerOf2() ||
788       (!TrueVal->getValue().isPowerOf2() &&
789        !FalseVal->getValue().isPowerOf2()))
790     return nullptr;
791
792   // Determine which shift is needed to transform result of the 'and' into the
793   // desired result.
794   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
795   unsigned ValZeros = ValC->getValue().logBase2();
796   unsigned AndZeros = AndRHS->getValue().logBase2();
797
798   // If types don't match we can still convert the select by introducing a zext
799   // or a trunc of the 'and'. The trunc case requires that all of the truncated
800   // bits are zero, we can figure that out by looking at the 'and' mask.
801   if (AndZeros >= ValC->getBitWidth())
802     return nullptr;
803
804   Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
805   if (ValZeros > AndZeros)
806     V = Builder->CreateShl(V, ValZeros - AndZeros);
807   else if (ValZeros < AndZeros)
808     V = Builder->CreateLShr(V, AndZeros - ValZeros);
809
810   // Okay, now we know that everything is set up, we just don't know whether we
811   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
812   bool ShouldNotVal = !TrueVal->isZero();
813   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
814   if (ShouldNotVal)
815     V = Builder->CreateXor(V, ValC);
816
817   // Apply an offset if needed.
818   if (Offset)
819     V = Builder->CreateAdd(V, Offset);
820   return V;
821 }
822
823 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
824   Value *CondVal = SI.getCondition();
825   Value *TrueVal = SI.getTrueValue();
826   Value *FalseVal = SI.getFalseValue();
827
828   if (Value *V =
829           SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
830     return ReplaceInstUsesWith(SI, V);
831
832   if (SI.getType()->isIntegerTy(1)) {
833     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
834       if (C->getZExtValue()) {
835         // Change: A = select B, true, C --> A = or B, C
836         return BinaryOperator::CreateOr(CondVal, FalseVal);
837       }
838       // Change: A = select B, false, C --> A = and !B, C
839       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
840       return BinaryOperator::CreateAnd(NotCond, FalseVal);
841     }
842     if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
843       if (!C->getZExtValue()) {
844         // Change: A = select B, C, false --> A = and B, C
845         return BinaryOperator::CreateAnd(CondVal, TrueVal);
846       }
847       // Change: A = select B, C, true --> A = or !B, C
848       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
849       return BinaryOperator::CreateOr(NotCond, TrueVal);
850     }
851
852     // select a, b, a  -> a&b
853     // select a, a, b  -> a|b
854     if (CondVal == TrueVal)
855       return BinaryOperator::CreateOr(CondVal, FalseVal);
856     if (CondVal == FalseVal)
857       return BinaryOperator::CreateAnd(CondVal, TrueVal);
858
859     // select a, ~a, b -> (~a)&b
860     // select a, b, ~a -> (~a)|b
861     if (match(TrueVal, m_Not(m_Specific(CondVal))))
862       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
863     if (match(FalseVal, m_Not(m_Specific(CondVal))))
864       return BinaryOperator::CreateOr(TrueVal, FalseVal);
865   }
866
867   // Selecting between two integer constants?
868   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
869     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
870       // select C, 1, 0 -> zext C to int
871       if (FalseValC->isZero() && TrueValC->getValue() == 1)
872         return new ZExtInst(CondVal, SI.getType());
873
874       // select C, -1, 0 -> sext C to int
875       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
876         return new SExtInst(CondVal, SI.getType());
877
878       // select C, 0, 1 -> zext !C to int
879       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
880         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
881         return new ZExtInst(NotCond, SI.getType());
882       }
883
884       // select C, 0, -1 -> sext !C to int
885       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
886         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
887         return new SExtInst(NotCond, SI.getType());
888       }
889
890       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
891         return ReplaceInstUsesWith(SI, V);
892     }
893
894   // See if we are selecting two values based on a comparison of the two values.
895   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
896     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
897       // Transform (X == Y) ? X : Y  -> Y
898       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
899         // This is not safe in general for floating point:
900         // consider X== -0, Y== +0.
901         // It becomes safe if either operand is a nonzero constant.
902         ConstantFP *CFPt, *CFPf;
903         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
904               !CFPt->getValueAPF().isZero()) ||
905             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
906              !CFPf->getValueAPF().isZero()))
907         return ReplaceInstUsesWith(SI, FalseVal);
908       }
909       // Transform (X une Y) ? X : Y  -> X
910       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
911         // This is not safe in general for floating point:
912         // consider X== -0, Y== +0.
913         // It becomes safe if either operand is a nonzero constant.
914         ConstantFP *CFPt, *CFPf;
915         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
916               !CFPt->getValueAPF().isZero()) ||
917             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
918              !CFPf->getValueAPF().isZero()))
919         return ReplaceInstUsesWith(SI, TrueVal);
920       }
921
922       // Canonicalize to use ordered comparisons by swapping the select
923       // operands.
924       //
925       // e.g.
926       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
927       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
928         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
929         Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
930                                              FCI->getName() + ".inv");
931
932         return SelectInst::Create(NewCond, FalseVal, TrueVal,
933                                   SI.getName() + ".p");
934       }
935
936       // NOTE: if we wanted to, this is where to detect MIN/MAX
937     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
938       // Transform (X == Y) ? Y : X  -> X
939       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
940         // This is not safe in general for floating point:
941         // consider X== -0, Y== +0.
942         // It becomes safe if either operand is a nonzero constant.
943         ConstantFP *CFPt, *CFPf;
944         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
945               !CFPt->getValueAPF().isZero()) ||
946             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
947              !CFPf->getValueAPF().isZero()))
948           return ReplaceInstUsesWith(SI, FalseVal);
949       }
950       // Transform (X une Y) ? Y : X  -> Y
951       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
952         // This is not safe in general for floating point:
953         // consider X== -0, Y== +0.
954         // It becomes safe if either operand is a nonzero constant.
955         ConstantFP *CFPt, *CFPf;
956         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
957               !CFPt->getValueAPF().isZero()) ||
958             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
959              !CFPf->getValueAPF().isZero()))
960           return ReplaceInstUsesWith(SI, TrueVal);
961       }
962
963       // Canonicalize to use ordered comparisons by swapping the select
964       // operands.
965       //
966       // e.g.
967       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
968       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
969         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
970         Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
971                                              FCI->getName() + ".inv");
972
973         return SelectInst::Create(NewCond, FalseVal, TrueVal,
974                                   SI.getName() + ".p");
975       }
976
977       // NOTE: if we wanted to, this is where to detect MIN/MAX
978     }
979     // NOTE: if we wanted to, this is where to detect ABS
980   }
981
982   // See if we are selecting two values based on a comparison of the two values.
983   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
984     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
985       return Result;
986
987   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
988     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
989       if (TI->hasOneUse() && FI->hasOneUse()) {
990         Instruction *AddOp = nullptr, *SubOp = nullptr;
991
992         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
993         if (TI->getOpcode() == FI->getOpcode())
994           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
995             return IV;
996
997         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
998         // even legal for FP.
999         if ((TI->getOpcode() == Instruction::Sub &&
1000              FI->getOpcode() == Instruction::Add) ||
1001             (TI->getOpcode() == Instruction::FSub &&
1002              FI->getOpcode() == Instruction::FAdd)) {
1003           AddOp = FI; SubOp = TI;
1004         } else if ((FI->getOpcode() == Instruction::Sub &&
1005                     TI->getOpcode() == Instruction::Add) ||
1006                    (FI->getOpcode() == Instruction::FSub &&
1007                     TI->getOpcode() == Instruction::FAdd)) {
1008           AddOp = TI; SubOp = FI;
1009         }
1010
1011         if (AddOp) {
1012           Value *OtherAddOp = nullptr;
1013           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1014             OtherAddOp = AddOp->getOperand(1);
1015           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1016             OtherAddOp = AddOp->getOperand(0);
1017           }
1018
1019           if (OtherAddOp) {
1020             // So at this point we know we have (Y -> OtherAddOp):
1021             //        select C, (add X, Y), (sub X, Z)
1022             Value *NegVal;  // Compute -Z
1023             if (SI.getType()->isFPOrFPVectorTy()) {
1024               NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
1025               if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1026                 FastMathFlags Flags = AddOp->getFastMathFlags();
1027                 Flags &= SubOp->getFastMathFlags();
1028                 NegInst->setFastMathFlags(Flags);
1029               }
1030             } else {
1031               NegVal = Builder->CreateNeg(SubOp->getOperand(1));
1032             }
1033
1034             Value *NewTrueOp = OtherAddOp;
1035             Value *NewFalseOp = NegVal;
1036             if (AddOp != TI)
1037               std::swap(NewTrueOp, NewFalseOp);
1038             Value *NewSel =
1039               Builder->CreateSelect(CondVal, NewTrueOp,
1040                                     NewFalseOp, SI.getName() + ".p");
1041
1042             if (SI.getType()->isFPOrFPVectorTy()) {
1043               Instruction *RI =
1044                 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1045
1046               FastMathFlags Flags = AddOp->getFastMathFlags();
1047               Flags &= SubOp->getFastMathFlags();
1048               RI->setFastMathFlags(Flags);
1049               return RI;
1050             } else
1051               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1052           }
1053         }
1054       }
1055
1056   // See if we can fold the select into one of our operands.
1057   if (SI.getType()->isIntOrIntVectorTy()) {
1058     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1059       return FoldI;
1060
1061     Value *LHS, *RHS, *LHS2, *RHS2;
1062     Instruction::CastOps CastOp;
1063     SelectPatternFlavor SPF = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1064
1065     if (SPF) {
1066       // Canonicalize so that type casts are outside select patterns.
1067       if (LHS->getType()->getPrimitiveSizeInBits() !=
1068           SI.getType()->getPrimitiveSizeInBits()) {
1069         CmpInst::Predicate Pred = getICmpPredicateForMinMax(SPF);
1070         Value *Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1071         Value *NewSI = Builder->CreateCast(CastOp,
1072                                            Builder->CreateSelect(Cmp, LHS, RHS),
1073                                            SI.getType());
1074         return ReplaceInstUsesWith(SI, NewSI);
1075       }
1076
1077       // MAX(MAX(a, b), a) -> MAX(a, b)
1078       // MIN(MIN(a, b), a) -> MIN(a, b)
1079       // MAX(MIN(a, b), a) -> a
1080       // MIN(MAX(a, b), a) -> a
1081       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2))
1082         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1083                                           SI, SPF, RHS))
1084           return R;
1085       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2))
1086         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1087                                           SI, SPF, LHS))
1088           return R;
1089     }
1090
1091     // MAX(~a, ~b) -> ~MIN(a, b)
1092     if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1093       if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1094           IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1095
1096         // This transform adds a xor operation and that extra cost needs to be
1097         // justified.  We look for simplifications that will result from
1098         // applying this rule:
1099
1100         bool Profitable =
1101             (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1102             (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1103             (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1104
1105         if (Profitable) {
1106           Value *NewLHS = Builder->CreateNot(LHS);
1107           Value *NewRHS = Builder->CreateNot(RHS);
1108           Value *NewCmp = SPF == SPF_SMAX
1109                               ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1110                               : Builder->CreateICmpULT(NewLHS, NewRHS);
1111           Value *NewSI =
1112               Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1113           return ReplaceInstUsesWith(SI, NewSI);
1114         }
1115       }
1116     }
1117
1118     // TODO.
1119     // ABS(-X) -> ABS(X)
1120   }
1121
1122   // See if we can fold the select into a phi node if the condition is a select.
1123   if (isa<PHINode>(SI.getCondition()))
1124     // The true/false values have to be live in the PHI predecessor's blocks.
1125     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1126         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1127       if (Instruction *NV = FoldOpIntoPhi(SI))
1128         return NV;
1129
1130   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1131     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1132       // select(C, select(C, a, b), c) -> select(C, a, c)
1133       if (TrueSI->getCondition() == CondVal) {
1134         if (SI.getTrueValue() == TrueSI->getTrueValue())
1135           return nullptr;
1136         SI.setOperand(1, TrueSI->getTrueValue());
1137         return &SI;
1138       }
1139       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1140       // We choose this as normal form to enable folding on the And and shortening
1141       // paths for the values (this helps GetUnderlyingObjects() for example).
1142       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1143         Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1144         SI.setOperand(0, And);
1145         SI.setOperand(1, TrueSI->getTrueValue());
1146         return &SI;
1147       }
1148     }
1149   }
1150   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1151     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1152       // select(C, a, select(C, b, c)) -> select(C, a, c)
1153       if (FalseSI->getCondition() == CondVal) {
1154         if (SI.getFalseValue() == FalseSI->getFalseValue())
1155           return nullptr;
1156         SI.setOperand(2, FalseSI->getFalseValue());
1157         return &SI;
1158       }
1159       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1160       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1161         Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1162         SI.setOperand(0, Or);
1163         SI.setOperand(2, FalseSI->getFalseValue());
1164         return &SI;
1165       }
1166     }
1167   }
1168
1169   if (BinaryOperator::isNot(CondVal)) {
1170     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1171     SI.setOperand(1, FalseVal);
1172     SI.setOperand(2, TrueVal);
1173     return &SI;
1174   }
1175
1176   if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
1177     unsigned VWidth = VecTy->getNumElements();
1178     APInt UndefElts(VWidth, 0);
1179     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1180     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1181       if (V != &SI)
1182         return ReplaceInstUsesWith(SI, V);
1183       return &SI;
1184     }
1185
1186     if (isa<ConstantAggregateZero>(CondVal)) {
1187       return ReplaceInstUsesWith(SI, FalseVal);
1188     }
1189   }
1190
1191   return nullptr;
1192 }