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