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/ADT/APInt.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/CmpInstAnalysis.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/IR/User.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/KnownBits.h"
41 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
42 #include <cassert>
43 #include <utility>
44 
45 using namespace llvm;
46 using namespace PatternMatch;
47 
48 #define DEBUG_TYPE "instcombine"
49 
50 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
51                            SelectPatternFlavor SPF, Value *A, Value *B) {
52   CmpInst::Predicate Pred = getMinMaxPred(SPF);
53   assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
54   return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
55 }
56 
57 /// If one of the constants is zero (we know they can't both be) and we have an
58 /// icmp instruction with zero, and we have an 'and' with the non-constant value
59 /// and a power of two we can turn the select into a shift on the result of the
60 /// 'and'.
61 /// This folds:
62 ///  select (icmp eq (and X, C1)), C2, C3
63 ///    iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
64 /// To something like:
65 ///  (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
66 /// Or:
67 ///  (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
68 /// With some variations depending if C3 is larger than C2, or the shift
69 /// isn't needed, or the bit widths don't match.
70 static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
71                                 APInt TrueVal, APInt FalseVal,
72                                 InstCombiner::BuilderTy &Builder) {
73   assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
74 
75   // If this is a vector select, we need a vector compare.
76   if (SelType->isVectorTy() != IC->getType()->isVectorTy())
77     return nullptr;
78 
79   Value *V;
80   APInt AndMask;
81   bool CreateAnd = false;
82   ICmpInst::Predicate Pred = IC->getPredicate();
83   if (ICmpInst::isEquality(Pred)) {
84     if (!match(IC->getOperand(1), m_Zero()))
85       return nullptr;
86 
87     V = IC->getOperand(0);
88 
89     const APInt *AndRHS;
90     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
91       return nullptr;
92 
93     AndMask = *AndRHS;
94   } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
95                                   Pred, V, AndMask)) {
96     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
97 
98     if (!AndMask.isPowerOf2())
99       return nullptr;
100 
101     CreateAnd = true;
102   } else {
103     return nullptr;
104   }
105 
106   // If both select arms are non-zero see if we have a select of the form
107   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
108   // for 'x ? 2^n : 0' and fix the thing up at the end.
109   APInt Offset(TrueVal.getBitWidth(), 0);
110   if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
111     if ((TrueVal - FalseVal).isPowerOf2())
112       Offset = FalseVal;
113     else if ((FalseVal - TrueVal).isPowerOf2())
114       Offset = TrueVal;
115     else
116       return nullptr;
117 
118     // Adjust TrueVal and FalseVal to the offset.
119     TrueVal -= Offset;
120     FalseVal -= Offset;
121   }
122 
123   // Make sure one of the select arms is a power of 2.
124   if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
125     return nullptr;
126 
127   // Determine which shift is needed to transform result of the 'and' into the
128   // desired result.
129   const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
130   unsigned ValZeros = ValC.logBase2();
131   unsigned AndZeros = AndMask.logBase2();
132 
133   if (CreateAnd) {
134     // Insert the AND instruction on the input to the truncate.
135     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
136   }
137 
138   // If types don't match we can still convert the select by introducing a zext
139   // or a trunc of the 'and'.
140   if (ValZeros > AndZeros) {
141     V = Builder.CreateZExtOrTrunc(V, SelType);
142     V = Builder.CreateShl(V, ValZeros - AndZeros);
143   } else if (ValZeros < AndZeros) {
144     V = Builder.CreateLShr(V, AndZeros - ValZeros);
145     V = Builder.CreateZExtOrTrunc(V, SelType);
146   } else
147     V = Builder.CreateZExtOrTrunc(V, SelType);
148 
149   // Okay, now we know that everything is set up, we just don't know whether we
150   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
151   bool ShouldNotVal = !TrueVal.isNullValue();
152   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
153   if (ShouldNotVal)
154     V = Builder.CreateXor(V, ValC);
155 
156   // Apply an offset if needed.
157   if (!Offset.isNullValue())
158     V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
159   return V;
160 }
161 
162 /// We want to turn code that looks like this:
163 ///   %C = or %A, %B
164 ///   %D = select %cond, %C, %A
165 /// into:
166 ///   %C = select %cond, %B, 0
167 ///   %D = or %A, %C
168 ///
169 /// Assuming that the specified instruction is an operand to the select, return
170 /// a bitmask indicating which operands of this instruction are foldable if they
171 /// equal the other incoming value of the select.
172 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
173   switch (I->getOpcode()) {
174   case Instruction::Add:
175   case Instruction::Mul:
176   case Instruction::And:
177   case Instruction::Or:
178   case Instruction::Xor:
179     return 3;              // Can fold through either operand.
180   case Instruction::Sub:   // Can only fold on the amount subtracted.
181   case Instruction::Shl:   // Can only fold on the shift amount.
182   case Instruction::LShr:
183   case Instruction::AShr:
184     return 1;
185   default:
186     return 0;              // Cannot fold
187   }
188 }
189 
190 /// For the same transformation as the previous function, return the identity
191 /// constant that goes into the select.
192 static APInt getSelectFoldableConstant(BinaryOperator *I) {
193   switch (I->getOpcode()) {
194   default: llvm_unreachable("This cannot happen!");
195   case Instruction::Add:
196   case Instruction::Sub:
197   case Instruction::Or:
198   case Instruction::Xor:
199   case Instruction::Shl:
200   case Instruction::LShr:
201   case Instruction::AShr:
202     return APInt::getNullValue(I->getType()->getScalarSizeInBits());
203   case Instruction::And:
204     return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
205   case Instruction::Mul:
206     return APInt(I->getType()->getScalarSizeInBits(), 1);
207   }
208 }
209 
210 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
211 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
212                                           Instruction *FI) {
213   // Don't break up min/max patterns. The hasOneUse checks below prevent that
214   // for most cases, but vector min/max with bitcasts can be transformed. If the
215   // one-use restrictions are eased for other patterns, we still don't want to
216   // obfuscate min/max.
217   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
218        match(&SI, m_SMax(m_Value(), m_Value())) ||
219        match(&SI, m_UMin(m_Value(), m_Value())) ||
220        match(&SI, m_UMax(m_Value(), m_Value()))))
221     return nullptr;
222 
223   // If this is a cast from the same type, merge.
224   if (TI->getNumOperands() == 1 && TI->isCast()) {
225     Type *FIOpndTy = FI->getOperand(0)->getType();
226     if (TI->getOperand(0)->getType() != FIOpndTy)
227       return nullptr;
228 
229     // The select condition may be a vector. We may only change the operand
230     // type if the vector width remains the same (and matches the condition).
231     Type *CondTy = SI.getCondition()->getType();
232     if (CondTy->isVectorTy()) {
233       if (!FIOpndTy->isVectorTy())
234         return nullptr;
235       if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
236         return nullptr;
237 
238       // TODO: If the backend knew how to deal with casts better, we could
239       // remove this limitation. For now, there's too much potential to create
240       // worse codegen by promoting the select ahead of size-altering casts
241       // (PR28160).
242       //
243       // Note that ValueTracking's matchSelectPattern() looks through casts
244       // without checking 'hasOneUse' when it matches min/max patterns, so this
245       // transform may end up happening anyway.
246       if (TI->getOpcode() != Instruction::BitCast &&
247           (!TI->hasOneUse() || !FI->hasOneUse()))
248         return nullptr;
249     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
250       // TODO: The one-use restrictions for a scalar select could be eased if
251       // the fold of a select in visitLoadInst() was enhanced to match a pattern
252       // that includes a cast.
253       return nullptr;
254     }
255 
256     // Fold this by inserting a select from the input values.
257     Value *NewSI =
258         Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
259                              FI->getOperand(0), SI.getName() + ".v", &SI);
260     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
261                             TI->getType());
262   }
263 
264   // Only handle binary operators (including two-operand getelementptr) with
265   // one-use here. As with the cast case above, it may be possible to relax the
266   // one-use constraint, but that needs be examined carefully since it may not
267   // reduce the total number of instructions.
268   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
269       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
270       !TI->hasOneUse() || !FI->hasOneUse())
271     return nullptr;
272 
273   // Figure out if the operations have any operands in common.
274   Value *MatchOp, *OtherOpT, *OtherOpF;
275   bool MatchIsOpZero;
276   if (TI->getOperand(0) == FI->getOperand(0)) {
277     MatchOp  = TI->getOperand(0);
278     OtherOpT = TI->getOperand(1);
279     OtherOpF = FI->getOperand(1);
280     MatchIsOpZero = true;
281   } else if (TI->getOperand(1) == FI->getOperand(1)) {
282     MatchOp  = TI->getOperand(1);
283     OtherOpT = TI->getOperand(0);
284     OtherOpF = FI->getOperand(0);
285     MatchIsOpZero = false;
286   } else if (!TI->isCommutative()) {
287     return nullptr;
288   } else if (TI->getOperand(0) == FI->getOperand(1)) {
289     MatchOp  = TI->getOperand(0);
290     OtherOpT = TI->getOperand(1);
291     OtherOpF = FI->getOperand(0);
292     MatchIsOpZero = true;
293   } else if (TI->getOperand(1) == FI->getOperand(0)) {
294     MatchOp  = TI->getOperand(1);
295     OtherOpT = TI->getOperand(0);
296     OtherOpF = FI->getOperand(1);
297     MatchIsOpZero = true;
298   } else {
299     return nullptr;
300   }
301 
302   // If we reach here, they do have operations in common.
303   Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
304                                       SI.getName() + ".v", &SI);
305   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
306   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
307   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
308     return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
309   }
310   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
311     auto *FGEP = cast<GetElementPtrInst>(FI);
312     Type *ElementType = TGEP->getResultElementType();
313     return TGEP->isInBounds() && FGEP->isInBounds()
314                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
315                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
316   }
317   llvm_unreachable("Expected BinaryOperator or GEP");
318   return nullptr;
319 }
320 
321 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
322   if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
323     return false;
324   return C1I.isOneValue() || C1I.isAllOnesValue() ||
325          C2I.isOneValue() || C2I.isAllOnesValue();
326 }
327 
328 /// Try to fold the select into one of the operands to allow further
329 /// optimization.
330 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
331                                             Value *FalseVal) {
332   // See the comment above GetSelectFoldableOperands for a description of the
333   // transformation we are doing here.
334   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
335     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
336       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
337         unsigned OpToFold = 0;
338         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
339           OpToFold = 1;
340         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
341           OpToFold = 2;
342         }
343 
344         if (OpToFold) {
345           APInt CI = getSelectFoldableConstant(TVI);
346           Value *OOp = TVI->getOperand(2-OpToFold);
347           // Avoid creating select between 2 constants unless it's selecting
348           // between 0, 1 and -1.
349           const APInt *OOpC;
350           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
351           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
352             Value *C = ConstantInt::get(OOp->getType(), CI);
353             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
354             NewSel->takeName(TVI);
355             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
356                                                         FalseVal, NewSel);
357             BO->copyIRFlags(TVI);
358             return BO;
359           }
360         }
361       }
362     }
363   }
364 
365   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
366     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
367       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
368         unsigned OpToFold = 0;
369         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
370           OpToFold = 1;
371         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
372           OpToFold = 2;
373         }
374 
375         if (OpToFold) {
376           APInt CI = getSelectFoldableConstant(FVI);
377           Value *OOp = FVI->getOperand(2-OpToFold);
378           // Avoid creating select between 2 constants unless it's selecting
379           // between 0, 1 and -1.
380           const APInt *OOpC;
381           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
382           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
383             Value *C = ConstantInt::get(OOp->getType(), CI);
384             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
385             NewSel->takeName(FVI);
386             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
387                                                         TrueVal, NewSel);
388             BO->copyIRFlags(FVI);
389             return BO;
390           }
391         }
392       }
393     }
394   }
395 
396   return nullptr;
397 }
398 
399 /// We want to turn:
400 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
401 /// into:
402 ///   (or (shl (and X, C1), C3), Y)
403 /// iff:
404 ///   C1 and C2 are both powers of 2
405 /// where:
406 ///   C3 = Log(C2) - Log(C1)
407 ///
408 /// This transform handles cases where:
409 /// 1. The icmp predicate is inverted
410 /// 2. The select operands are reversed
411 /// 3. The magnitude of C2 and C1 are flipped
412 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
413                                   Value *FalseVal,
414                                   InstCombiner::BuilderTy &Builder) {
415   // Only handle integer compares. Also, if this is a vector select, we need a
416   // vector compare.
417   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
418       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
419     return nullptr;
420 
421   Value *CmpLHS = IC->getOperand(0);
422   Value *CmpRHS = IC->getOperand(1);
423 
424   Value *V;
425   unsigned C1Log;
426   bool IsEqualZero;
427   bool NeedAnd = false;
428   if (IC->isEquality()) {
429     if (!match(CmpRHS, m_Zero()))
430       return nullptr;
431 
432     const APInt *C1;
433     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
434       return nullptr;
435 
436     V = CmpLHS;
437     C1Log = C1->logBase2();
438     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
439   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
440              IC->getPredicate() == ICmpInst::ICMP_SGT) {
441     // We also need to recognize (icmp slt (trunc (X)), 0) and
442     // (icmp sgt (trunc (X)), -1).
443     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
444     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
445         (!IsEqualZero && !match(CmpRHS, m_Zero())))
446       return nullptr;
447 
448     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
449       return nullptr;
450 
451     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
452     NeedAnd = true;
453   } else {
454     return nullptr;
455   }
456 
457   const APInt *C2;
458   bool OrOnTrueVal = false;
459   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
460   if (!OrOnFalseVal)
461     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
462 
463   if (!OrOnFalseVal && !OrOnTrueVal)
464     return nullptr;
465 
466   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
467 
468   unsigned C2Log = C2->logBase2();
469 
470   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
471   bool NeedShift = C1Log != C2Log;
472   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
473                        V->getType()->getScalarSizeInBits();
474 
475   // Make sure we don't create more instructions than we save.
476   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
477   if ((NeedShift + NeedXor + NeedZExtTrunc) >
478       (IC->hasOneUse() + Or->hasOneUse()))
479     return nullptr;
480 
481   if (NeedAnd) {
482     // Insert the AND instruction on the input to the truncate.
483     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
484     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
485   }
486 
487   if (C2Log > C1Log) {
488     V = Builder.CreateZExtOrTrunc(V, Y->getType());
489     V = Builder.CreateShl(V, C2Log - C1Log);
490   } else if (C1Log > C2Log) {
491     V = Builder.CreateLShr(V, C1Log - C2Log);
492     V = Builder.CreateZExtOrTrunc(V, Y->getType());
493   } else
494     V = Builder.CreateZExtOrTrunc(V, Y->getType());
495 
496   if (NeedXor)
497     V = Builder.CreateXor(V, *C2);
498 
499   return Builder.CreateOr(V, Y);
500 }
501 
502 /// Transform patterns such as: (a > b) ? a - b : 0
503 /// into: ((a > b) ? a : b) - b)
504 /// This produces a canonical max pattern that is more easily recognized by the
505 /// backend and converted into saturated subtraction instructions if those
506 /// exist.
507 /// There are 8 commuted/swapped variants of this pattern.
508 /// TODO: Also support a - UMIN(a,b) patterns.
509 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
510                                             const Value *TrueVal,
511                                             const Value *FalseVal,
512                                             InstCombiner::BuilderTy &Builder) {
513   ICmpInst::Predicate Pred = ICI->getPredicate();
514   if (!ICmpInst::isUnsigned(Pred))
515     return nullptr;
516 
517   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
518   if (match(TrueVal, m_Zero())) {
519     Pred = ICmpInst::getInversePredicate(Pred);
520     std::swap(TrueVal, FalseVal);
521   }
522   if (!match(FalseVal, m_Zero()))
523     return nullptr;
524 
525   Value *A = ICI->getOperand(0);
526   Value *B = ICI->getOperand(1);
527   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
528     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
529     std::swap(A, B);
530     Pred = ICmpInst::getSwappedPredicate(Pred);
531   }
532 
533   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
534          "Unexpected isUnsigned predicate!");
535 
536   // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
537   bool IsNegative = false;
538   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
539     IsNegative = true;
540   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
541     return nullptr;
542 
543   // If sub is used anywhere else, we wouldn't be able to eliminate it
544   // afterwards.
545   if (!TrueVal->hasOneUse())
546     return nullptr;
547 
548   // All checks passed, convert to canonical unsigned saturated subtraction
549   // form: sub(max()).
550   // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b)
551   Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
552   return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B);
553 }
554 
555 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
556 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
557 ///
558 /// For example, we can fold the following code sequence:
559 /// \code
560 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
561 ///   %1 = icmp ne i32 %x, 0
562 ///   %2 = select i1 %1, i32 %0, i32 32
563 /// \code
564 ///
565 /// into:
566 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
567 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
568                                  InstCombiner::BuilderTy &Builder) {
569   ICmpInst::Predicate Pred = ICI->getPredicate();
570   Value *CmpLHS = ICI->getOperand(0);
571   Value *CmpRHS = ICI->getOperand(1);
572 
573   // Check if the condition value compares a value for equality against zero.
574   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
575     return nullptr;
576 
577   Value *Count = FalseVal;
578   Value *ValueOnZero = TrueVal;
579   if (Pred == ICmpInst::ICMP_NE)
580     std::swap(Count, ValueOnZero);
581 
582   // Skip zero extend/truncate.
583   Value *V = nullptr;
584   if (match(Count, m_ZExt(m_Value(V))) ||
585       match(Count, m_Trunc(m_Value(V))))
586     Count = V;
587 
588   // Check if the value propagated on zero is a constant number equal to the
589   // sizeof in bits of 'Count'.
590   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
591   if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
592     return nullptr;
593 
594   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
595   // input to the cttz/ctlz is used as LHS for the compare instruction.
596   if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
597       match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
598     IntrinsicInst *II = cast<IntrinsicInst>(Count);
599     // Explicitly clear the 'undef_on_zero' flag.
600     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
601     NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
602     Builder.Insert(NewI);
603     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
604   }
605 
606   return nullptr;
607 }
608 
609 /// Return true if we find and adjust an icmp+select pattern where the compare
610 /// is with a constant that can be incremented or decremented to match the
611 /// minimum or maximum idiom.
612 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
613   ICmpInst::Predicate Pred = Cmp.getPredicate();
614   Value *CmpLHS = Cmp.getOperand(0);
615   Value *CmpRHS = Cmp.getOperand(1);
616   Value *TrueVal = Sel.getTrueValue();
617   Value *FalseVal = Sel.getFalseValue();
618 
619   // We may move or edit the compare, so make sure the select is the only user.
620   const APInt *CmpC;
621   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
622     return false;
623 
624   // These transforms only work for selects of integers or vector selects of
625   // integer vectors.
626   Type *SelTy = Sel.getType();
627   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
628   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
629     return false;
630 
631   Constant *AdjustedRHS;
632   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
633     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
634   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
635     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
636   else
637     return false;
638 
639   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
640   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
641   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
642       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
643     ; // Nothing to do here. Values match without any sign/zero extension.
644   }
645   // Types do not match. Instead of calculating this with mixed types, promote
646   // all to the larger type. This enables scalar evolution to analyze this
647   // expression.
648   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
649     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
650 
651     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
652     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
653     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
654     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
655     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
656       CmpLHS = TrueVal;
657       AdjustedRHS = SextRHS;
658     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
659                SextRHS == TrueVal) {
660       CmpLHS = FalseVal;
661       AdjustedRHS = SextRHS;
662     } else if (Cmp.isUnsigned()) {
663       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
664       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
665       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
666       // zext + signed compare cannot be changed:
667       //    0xff <s 0x00, but 0x00ff >s 0x0000
668       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
669         CmpLHS = TrueVal;
670         AdjustedRHS = ZextRHS;
671       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
672                  ZextRHS == TrueVal) {
673         CmpLHS = FalseVal;
674         AdjustedRHS = ZextRHS;
675       } else {
676         return false;
677       }
678     } else {
679       return false;
680     }
681   } else {
682     return false;
683   }
684 
685   Pred = ICmpInst::getSwappedPredicate(Pred);
686   CmpRHS = AdjustedRHS;
687   std::swap(FalseVal, TrueVal);
688   Cmp.setPredicate(Pred);
689   Cmp.setOperand(0, CmpLHS);
690   Cmp.setOperand(1, CmpRHS);
691   Sel.setOperand(1, TrueVal);
692   Sel.setOperand(2, FalseVal);
693   Sel.swapProfMetadata();
694 
695   // Move the compare instruction right before the select instruction. Otherwise
696   // the sext/zext value may be defined after the compare instruction uses it.
697   Cmp.moveBefore(&Sel);
698 
699   return true;
700 }
701 
702 /// If this is an integer min/max (icmp + select) with a constant operand,
703 /// create the canonical icmp for the min/max operation and canonicalize the
704 /// constant to the 'false' operand of the select:
705 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
706 /// Note: if C1 != C2, this will change the icmp constant to the existing
707 /// constant operand of the select.
708 static Instruction *
709 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
710                                InstCombiner::BuilderTy &Builder) {
711   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
712     return nullptr;
713 
714   // Canonicalize the compare predicate based on whether we have min or max.
715   Value *LHS, *RHS;
716   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
717   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
718     return nullptr;
719 
720   // Is this already canonical?
721   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
722   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
723       Cmp.getPredicate() == CanonicalPred)
724     return nullptr;
725 
726   // Create the canonical compare and plug it into the select.
727   Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
728 
729   // If the select operands did not change, we're done.
730   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
731     return &Sel;
732 
733   // If we are swapping the select operands, swap the metadata too.
734   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
735          "Unexpected results from matchSelectPattern");
736   Sel.setTrueValue(LHS);
737   Sel.setFalseValue(RHS);
738   Sel.swapProfMetadata();
739   return &Sel;
740 }
741 
742 /// Visit a SelectInst that has an ICmpInst as its first operand.
743 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
744                                                   ICmpInst *ICI) {
745   Value *TrueVal = SI.getTrueValue();
746   Value *FalseVal = SI.getFalseValue();
747 
748   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
749     return NewSel;
750 
751   bool Changed = adjustMinMax(SI, *ICI);
752 
753   ICmpInst::Predicate Pred = ICI->getPredicate();
754   Value *CmpLHS = ICI->getOperand(0);
755   Value *CmpRHS = ICI->getOperand(1);
756 
757   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
758   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
759   // FIXME: Type and constness constraints could be lifted, but we have to
760   //        watch code size carefully. We should consider xor instead of
761   //        sub/add when we decide to do that.
762   // TODO: Merge this with foldSelectICmpAnd somehow.
763   if (CmpLHS->getType()->isIntOrIntVectorTy() &&
764       CmpLHS->getType() == TrueVal->getType()) {
765     const APInt *C1, *C2;
766     if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
767       ICmpInst::Predicate Pred = ICI->getPredicate();
768       Value *X;
769       APInt Mask;
770       if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) {
771         if (Mask.isSignMask()) {
772           assert(X == CmpLHS && "Expected to use the compare input directly");
773           assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
774 
775           if (Pred == ICmpInst::ICMP_NE)
776             std::swap(C1, C2);
777 
778           // This shift results in either -1 or 0.
779           Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
780 
781           // Check if we can express the operation with a single or.
782           if (C2->isAllOnesValue())
783             return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
784 
785           Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
786           return replaceInstUsesWith(SI, Builder.CreateAdd(And,
787                                         ConstantInt::get(And->getType(), *C1)));
788         }
789       }
790     }
791   }
792 
793   {
794     const APInt *TrueValC, *FalseValC;
795     if (match(TrueVal, m_APInt(TrueValC)) &&
796         match(FalseVal, m_APInt(FalseValC)))
797       if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
798                                        *FalseValC, Builder))
799         return replaceInstUsesWith(SI, V);
800   }
801 
802   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
803 
804   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
805     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
806       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
807       SI.setOperand(1, CmpRHS);
808       Changed = true;
809     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
810       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
811       SI.setOperand(2, CmpRHS);
812       Changed = true;
813     }
814   }
815 
816   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
817   // decomposeBitTestICmp() might help.
818   {
819     unsigned BitWidth =
820         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
821     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
822     Value *X;
823     const APInt *Y, *C;
824     bool TrueWhenUnset;
825     bool IsBitTest = false;
826     if (ICmpInst::isEquality(Pred) &&
827         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
828         match(CmpRHS, m_Zero())) {
829       IsBitTest = true;
830       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
831     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
832       X = CmpLHS;
833       Y = &MinSignedValue;
834       IsBitTest = true;
835       TrueWhenUnset = false;
836     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
837       X = CmpLHS;
838       Y = &MinSignedValue;
839       IsBitTest = true;
840       TrueWhenUnset = true;
841     }
842     if (IsBitTest) {
843       Value *V = nullptr;
844       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
845       if (TrueWhenUnset && TrueVal == X &&
846           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
847         V = Builder.CreateAnd(X, ~(*Y));
848       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
849       else if (!TrueWhenUnset && FalseVal == X &&
850                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
851         V = Builder.CreateAnd(X, ~(*Y));
852       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
853       else if (TrueWhenUnset && FalseVal == X &&
854                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
855         V = Builder.CreateOr(X, *Y);
856       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
857       else if (!TrueWhenUnset && TrueVal == X &&
858                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
859         V = Builder.CreateOr(X, *Y);
860 
861       if (V)
862         return replaceInstUsesWith(SI, V);
863     }
864   }
865 
866   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
867     return replaceInstUsesWith(SI, V);
868 
869   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
870     return replaceInstUsesWith(SI, V);
871 
872   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
873     return replaceInstUsesWith(SI, V);
874 
875   return Changed ? &SI : nullptr;
876 }
877 
878 /// SI is a select whose condition is a PHI node (but the two may be in
879 /// different blocks). See if the true/false values (V) are live in all of the
880 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
881 ///
882 ///   X = phi [ C1, BB1], [C2, BB2]
883 ///   Y = add
884 ///   Z = select X, Y, 0
885 ///
886 /// because Y is not live in BB1/BB2.
887 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
888                                                    const SelectInst &SI) {
889   // If the value is a non-instruction value like a constant or argument, it
890   // can always be mapped.
891   const Instruction *I = dyn_cast<Instruction>(V);
892   if (!I) return true;
893 
894   // If V is a PHI node defined in the same block as the condition PHI, we can
895   // map the arguments.
896   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
897 
898   if (const PHINode *VP = dyn_cast<PHINode>(I))
899     if (VP->getParent() == CondPHI->getParent())
900       return true;
901 
902   // Otherwise, if the PHI and select are defined in the same block and if V is
903   // defined in a different block, then we can transform it.
904   if (SI.getParent() == CondPHI->getParent() &&
905       I->getParent() != CondPHI->getParent())
906     return true;
907 
908   // Otherwise we have a 'hard' case and we can't tell without doing more
909   // detailed dominator based analysis, punt.
910   return false;
911 }
912 
913 /// We have an SPF (e.g. a min or max) of an SPF of the form:
914 ///   SPF2(SPF1(A, B), C)
915 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
916                                         SelectPatternFlavor SPF1,
917                                         Value *A, Value *B,
918                                         Instruction &Outer,
919                                         SelectPatternFlavor SPF2, Value *C) {
920   if (Outer.getType() != Inner->getType())
921     return nullptr;
922 
923   if (C == A || C == B) {
924     // MAX(MAX(A, B), B) -> MAX(A, B)
925     // MIN(MIN(a, b), a) -> MIN(a, b)
926     if (SPF1 == SPF2)
927       return replaceInstUsesWith(Outer, Inner);
928 
929     // MAX(MIN(a, b), a) -> a
930     // MIN(MAX(a, b), a) -> a
931     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
932         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
933         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
934         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
935       return replaceInstUsesWith(Outer, C);
936   }
937 
938   if (SPF1 == SPF2) {
939     const APInt *CB, *CC;
940     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
941       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
942       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
943       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
944           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
945           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
946           (SPF1 == SPF_SMAX && CB->sge(*CC)))
947         return replaceInstUsesWith(Outer, Inner);
948 
949       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
950       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
951       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
952           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
953           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
954           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
955         Outer.replaceUsesOfWith(Inner, A);
956         return &Outer;
957       }
958     }
959   }
960 
961   // ABS(ABS(X)) -> ABS(X)
962   // NABS(NABS(X)) -> NABS(X)
963   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
964     return replaceInstUsesWith(Outer, Inner);
965   }
966 
967   // ABS(NABS(X)) -> ABS(X)
968   // NABS(ABS(X)) -> NABS(X)
969   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
970       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
971     SelectInst *SI = cast<SelectInst>(Inner);
972     Value *NewSI =
973         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
974                              SI->getTrueValue(), SI->getName(), SI);
975     return replaceInstUsesWith(Outer, NewSI);
976   }
977 
978   auto IsFreeOrProfitableToInvert =
979       [&](Value *V, Value *&NotV, bool &ElidesXor) {
980     if (match(V, m_Not(m_Value(NotV)))) {
981       // If V has at most 2 uses then we can get rid of the xor operation
982       // entirely.
983       ElidesXor |= !V->hasNUsesOrMore(3);
984       return true;
985     }
986 
987     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
988       NotV = nullptr;
989       return true;
990     }
991 
992     return false;
993   };
994 
995   Value *NotA, *NotB, *NotC;
996   bool ElidesXor = false;
997 
998   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
999   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1000   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1001   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1002   //
1003   // This transform is performance neutral if we can elide at least one xor from
1004   // the set of three operands, since we'll be tacking on an xor at the very
1005   // end.
1006   if (SelectPatternResult::isMinOrMax(SPF1) &&
1007       SelectPatternResult::isMinOrMax(SPF2) &&
1008       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1009       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1010       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1011     if (!NotA)
1012       NotA = Builder.CreateNot(A);
1013     if (!NotB)
1014       NotB = Builder.CreateNot(B);
1015     if (!NotC)
1016       NotC = Builder.CreateNot(C);
1017 
1018     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1019                                    NotB);
1020     Value *NewOuter = Builder.CreateNot(
1021         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1022     return replaceInstUsesWith(Outer, NewOuter);
1023   }
1024 
1025   return nullptr;
1026 }
1027 
1028 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1029 /// This is even legal for FP.
1030 static Instruction *foldAddSubSelect(SelectInst &SI,
1031                                      InstCombiner::BuilderTy &Builder) {
1032   Value *CondVal = SI.getCondition();
1033   Value *TrueVal = SI.getTrueValue();
1034   Value *FalseVal = SI.getFalseValue();
1035   auto *TI = dyn_cast<Instruction>(TrueVal);
1036   auto *FI = dyn_cast<Instruction>(FalseVal);
1037   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1038     return nullptr;
1039 
1040   Instruction *AddOp = nullptr, *SubOp = nullptr;
1041   if ((TI->getOpcode() == Instruction::Sub &&
1042        FI->getOpcode() == Instruction::Add) ||
1043       (TI->getOpcode() == Instruction::FSub &&
1044        FI->getOpcode() == Instruction::FAdd)) {
1045     AddOp = FI;
1046     SubOp = TI;
1047   } else if ((FI->getOpcode() == Instruction::Sub &&
1048               TI->getOpcode() == Instruction::Add) ||
1049              (FI->getOpcode() == Instruction::FSub &&
1050               TI->getOpcode() == Instruction::FAdd)) {
1051     AddOp = TI;
1052     SubOp = FI;
1053   }
1054 
1055   if (AddOp) {
1056     Value *OtherAddOp = nullptr;
1057     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1058       OtherAddOp = AddOp->getOperand(1);
1059     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1060       OtherAddOp = AddOp->getOperand(0);
1061     }
1062 
1063     if (OtherAddOp) {
1064       // So at this point we know we have (Y -> OtherAddOp):
1065       //        select C, (add X, Y), (sub X, Z)
1066       Value *NegVal; // Compute -Z
1067       if (SI.getType()->isFPOrFPVectorTy()) {
1068         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1069         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1070           FastMathFlags Flags = AddOp->getFastMathFlags();
1071           Flags &= SubOp->getFastMathFlags();
1072           NegInst->setFastMathFlags(Flags);
1073         }
1074       } else {
1075         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1076       }
1077 
1078       Value *NewTrueOp = OtherAddOp;
1079       Value *NewFalseOp = NegVal;
1080       if (AddOp != TI)
1081         std::swap(NewTrueOp, NewFalseOp);
1082       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1083                                            SI.getName() + ".p", &SI);
1084 
1085       if (SI.getType()->isFPOrFPVectorTy()) {
1086         Instruction *RI =
1087             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1088 
1089         FastMathFlags Flags = AddOp->getFastMathFlags();
1090         Flags &= SubOp->getFastMathFlags();
1091         RI->setFastMathFlags(Flags);
1092         return RI;
1093       } else
1094         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1095     }
1096   }
1097   return nullptr;
1098 }
1099 
1100 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1101   Instruction *ExtInst;
1102   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1103       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1104     return nullptr;
1105 
1106   auto ExtOpcode = ExtInst->getOpcode();
1107   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1108     return nullptr;
1109 
1110   // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
1111   Value *X = ExtInst->getOperand(0);
1112   Type *SmallType = X->getType();
1113   if (!SmallType->isIntOrIntVectorTy(1))
1114     return nullptr;
1115 
1116   Constant *C;
1117   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1118       !match(Sel.getFalseValue(), m_Constant(C)))
1119     return nullptr;
1120 
1121   // If the constant is the same after truncation to the smaller type and
1122   // extension to the original type, we can narrow the select.
1123   Value *Cond = Sel.getCondition();
1124   Type *SelType = Sel.getType();
1125   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1126   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1127   if (ExtC == C) {
1128     Value *TruncCVal = cast<Value>(TruncC);
1129     if (ExtInst == Sel.getFalseValue())
1130       std::swap(X, TruncCVal);
1131 
1132     // select Cond, (ext X), C --> ext(select Cond, X, C')
1133     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1134     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1135     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1136   }
1137 
1138   // If one arm of the select is the extend of the condition, replace that arm
1139   // with the extension of the appropriate known bool value.
1140   if (Cond == X) {
1141     if (ExtInst == Sel.getTrueValue()) {
1142       // select X, (sext X), C --> select X, -1, C
1143       // select X, (zext X), C --> select X,  1, C
1144       Constant *One = ConstantInt::getTrue(SmallType);
1145       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1146       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1147     } else {
1148       // select X, C, (sext X) --> select X, C, 0
1149       // select X, C, (zext X) --> select X, C, 0
1150       Constant *Zero = ConstantInt::getNullValue(SelType);
1151       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1152     }
1153   }
1154 
1155   return nullptr;
1156 }
1157 
1158 /// Try to transform a vector select with a constant condition vector into a
1159 /// shuffle for easier combining with other shuffles and insert/extract.
1160 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1161   Value *CondVal = SI.getCondition();
1162   Constant *CondC;
1163   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1164     return nullptr;
1165 
1166   unsigned NumElts = CondVal->getType()->getVectorNumElements();
1167   SmallVector<Constant *, 16> Mask;
1168   Mask.reserve(NumElts);
1169   Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1170   for (unsigned i = 0; i != NumElts; ++i) {
1171     Constant *Elt = CondC->getAggregateElement(i);
1172     if (!Elt)
1173       return nullptr;
1174 
1175     if (Elt->isOneValue()) {
1176       // If the select condition element is true, choose from the 1st vector.
1177       Mask.push_back(ConstantInt::get(Int32Ty, i));
1178     } else if (Elt->isNullValue()) {
1179       // If the select condition element is false, choose from the 2nd vector.
1180       Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1181     } else if (isa<UndefValue>(Elt)) {
1182       // Undef in a select condition (choose one of the operands) does not mean
1183       // the same thing as undef in a shuffle mask (any value is acceptable), so
1184       // give up.
1185       return nullptr;
1186     } else {
1187       // Bail out on a constant expression.
1188       return nullptr;
1189     }
1190   }
1191 
1192   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1193                                ConstantVector::get(Mask));
1194 }
1195 
1196 /// Reuse bitcasted operands between a compare and select:
1197 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1198 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1199 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1200                                           InstCombiner::BuilderTy &Builder) {
1201   Value *Cond = Sel.getCondition();
1202   Value *TVal = Sel.getTrueValue();
1203   Value *FVal = Sel.getFalseValue();
1204 
1205   CmpInst::Predicate Pred;
1206   Value *A, *B;
1207   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1208     return nullptr;
1209 
1210   // The select condition is a compare instruction. If the select's true/false
1211   // values are already the same as the compare operands, there's nothing to do.
1212   if (TVal == A || TVal == B || FVal == A || FVal == B)
1213     return nullptr;
1214 
1215   Value *C, *D;
1216   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1217     return nullptr;
1218 
1219   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1220   Value *TSrc, *FSrc;
1221   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1222       !match(FVal, m_BitCast(m_Value(FSrc))))
1223     return nullptr;
1224 
1225   // If the select true/false values are *different bitcasts* of the same source
1226   // operands, make the select operands the same as the compare operands and
1227   // cast the result. This is the canonical select form for min/max.
1228   Value *NewSel;
1229   if (TSrc == C && FSrc == D) {
1230     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1231     // bitcast (select (cmp A, B), A, B)
1232     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1233   } else if (TSrc == D && FSrc == C) {
1234     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1235     // bitcast (select (cmp A, B), B, A)
1236     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1237   } else {
1238     return nullptr;
1239   }
1240   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1241 }
1242 
1243 /// Try to eliminate select instructions that test the returned flag of cmpxchg
1244 /// instructions.
1245 ///
1246 /// If a select instruction tests the returned flag of a cmpxchg instruction and
1247 /// selects between the returned value of the cmpxchg instruction its compare
1248 /// operand, the result of the select will always be equal to its false value.
1249 /// For example:
1250 ///
1251 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1252 ///   %1 = extractvalue { i64, i1 } %0, 1
1253 ///   %2 = extractvalue { i64, i1 } %0, 0
1254 ///   %3 = select i1 %1, i64 %compare, i64 %2
1255 ///   ret i64 %3
1256 ///
1257 /// The returned value of the cmpxchg instruction (%2) is the original value
1258 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1259 /// must have been equal to %compare. Thus, the result of the select is always
1260 /// equal to %2, and the code can be simplified to:
1261 ///
1262 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1263 ///   %1 = extractvalue { i64, i1 } %0, 0
1264 ///   ret i64 %1
1265 ///
1266 static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1267   // A helper that determines if V is an extractvalue instruction whose
1268   // aggregate operand is a cmpxchg instruction and whose single index is equal
1269   // to I. If such conditions are true, the helper returns the cmpxchg
1270   // instruction; otherwise, a nullptr is returned.
1271   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1272     auto *Extract = dyn_cast<ExtractValueInst>(V);
1273     if (!Extract)
1274       return nullptr;
1275     if (Extract->getIndices()[0] != I)
1276       return nullptr;
1277     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1278   };
1279 
1280   // If the select has a single user, and this user is a select instruction that
1281   // we can simplify, skip the cmpxchg simplification for now.
1282   if (SI.hasOneUse())
1283     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1284       if (Select->getCondition() == SI.getCondition())
1285         if (Select->getFalseValue() == SI.getTrueValue() ||
1286             Select->getTrueValue() == SI.getFalseValue())
1287           return nullptr;
1288 
1289   // Ensure the select condition is the returned flag of a cmpxchg instruction.
1290   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1291   if (!CmpXchg)
1292     return nullptr;
1293 
1294   // Check the true value case: The true value of the select is the returned
1295   // value of the same cmpxchg used by the condition, and the false value is the
1296   // cmpxchg instruction's compare operand.
1297   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1298     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1299       SI.setTrueValue(SI.getFalseValue());
1300       return &SI;
1301     }
1302 
1303   // Check the false value case: The false value of the select is the returned
1304   // value of the same cmpxchg used by the condition, and the true value is the
1305   // cmpxchg instruction's compare operand.
1306   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1307     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1308       SI.setTrueValue(SI.getFalseValue());
1309       return &SI;
1310     }
1311 
1312   return nullptr;
1313 }
1314 
1315 /// Reduce a sequence of min/max with a common operand.
1316 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1317                                         Value *RHS,
1318                                         InstCombiner::BuilderTy &Builder) {
1319   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1320   // TODO: Allow FP min/max with nnan/nsz.
1321   if (!LHS->getType()->isIntOrIntVectorTy())
1322     return nullptr;
1323 
1324   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1325   Value *A, *B, *C, *D;
1326   SelectPatternResult L = matchSelectPattern(LHS, A, B);
1327   SelectPatternResult R = matchSelectPattern(RHS, C, D);
1328   if (SPF != L.Flavor || L.Flavor != R.Flavor)
1329     return nullptr;
1330 
1331   // Look for a common operand. The use checks are different than usual because
1332   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1333   // the select.
1334   Value *MinMaxOp = nullptr;
1335   Value *ThirdOp = nullptr;
1336   if (LHS->getNumUses() <= 2 && RHS->getNumUses() > 2) {
1337     // If the LHS is only used in this chain and the RHS is used outside of it,
1338     // reuse the RHS min/max because that will eliminate the LHS.
1339     if (D == A || C == A) {
1340       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1341       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1342       MinMaxOp = RHS;
1343       ThirdOp = B;
1344     } else if (D == B || C == B) {
1345       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1346       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1347       MinMaxOp = RHS;
1348       ThirdOp = A;
1349     }
1350   } else if (RHS->getNumUses() <= 2) {
1351     // Reuse the LHS. This will eliminate the RHS.
1352     if (D == A || D == B) {
1353       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1354       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1355       MinMaxOp = LHS;
1356       ThirdOp = C;
1357     } else if (C == A || C == B) {
1358       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1359       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1360       MinMaxOp = LHS;
1361       ThirdOp = D;
1362     }
1363   }
1364   if (!MinMaxOp || !ThirdOp)
1365     return nullptr;
1366 
1367   CmpInst::Predicate P = getMinMaxPred(SPF);
1368   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1369   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1370 }
1371 
1372 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1373   Value *CondVal = SI.getCondition();
1374   Value *TrueVal = SI.getTrueValue();
1375   Value *FalseVal = SI.getFalseValue();
1376   Type *SelType = SI.getType();
1377 
1378   // FIXME: Remove this workaround when freeze related patches are done.
1379   // For select with undef operand which feeds into an equality comparison,
1380   // don't simplify it so loop unswitch can know the equality comparison
1381   // may have an undef operand. This is a workaround for PR31652 caused by
1382   // descrepancy about branch on undef between LoopUnswitch and GVN.
1383   if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1384     if (llvm::any_of(SI.users(), [&](User *U) {
1385           ICmpInst *CI = dyn_cast<ICmpInst>(U);
1386           if (CI && CI->isEquality())
1387             return true;
1388           return false;
1389         })) {
1390       return nullptr;
1391     }
1392   }
1393 
1394   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1395                                     SQ.getWithInstruction(&SI)))
1396     return replaceInstUsesWith(SI, V);
1397 
1398   if (Instruction *I = canonicalizeSelectToShuffle(SI))
1399     return I;
1400 
1401   // Canonicalize a one-use integer compare with a non-canonical predicate by
1402   // inverting the predicate and swapping the select operands. This matches a
1403   // compare canonicalization for conditional branches.
1404   // TODO: Should we do the same for FP compares?
1405   CmpInst::Predicate Pred;
1406   if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1407       !isCanonicalPredicate(Pred)) {
1408     // Swap true/false values and condition.
1409     CmpInst *Cond = cast<CmpInst>(CondVal);
1410     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1411     SI.setOperand(1, FalseVal);
1412     SI.setOperand(2, TrueVal);
1413     SI.swapProfMetadata();
1414     Worklist.Add(Cond);
1415     return &SI;
1416   }
1417 
1418   if (SelType->isIntOrIntVectorTy(1) &&
1419       TrueVal->getType() == CondVal->getType()) {
1420     if (match(TrueVal, m_One())) {
1421       // Change: A = select B, true, C --> A = or B, C
1422       return BinaryOperator::CreateOr(CondVal, FalseVal);
1423     }
1424     if (match(TrueVal, m_Zero())) {
1425       // Change: A = select B, false, C --> A = and !B, C
1426       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1427       return BinaryOperator::CreateAnd(NotCond, FalseVal);
1428     }
1429     if (match(FalseVal, m_Zero())) {
1430       // Change: A = select B, C, false --> A = and B, C
1431       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1432     }
1433     if (match(FalseVal, m_One())) {
1434       // Change: A = select B, C, true --> A = or !B, C
1435       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1436       return BinaryOperator::CreateOr(NotCond, TrueVal);
1437     }
1438 
1439     // select a, a, b  -> a | b
1440     // select a, b, a  -> a & b
1441     if (CondVal == TrueVal)
1442       return BinaryOperator::CreateOr(CondVal, FalseVal);
1443     if (CondVal == FalseVal)
1444       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1445 
1446     // select a, ~a, b -> (~a) & b
1447     // select a, b, ~a -> (~a) | b
1448     if (match(TrueVal, m_Not(m_Specific(CondVal))))
1449       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1450     if (match(FalseVal, m_Not(m_Specific(CondVal))))
1451       return BinaryOperator::CreateOr(TrueVal, FalseVal);
1452   }
1453 
1454   // Selecting between two integer or vector splat integer constants?
1455   //
1456   // Note that we don't handle a scalar select of vectors:
1457   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1458   // because that may need 3 instructions to splat the condition value:
1459   // extend, insertelement, shufflevector.
1460   if (SelType->isIntOrIntVectorTy() &&
1461       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1462     // select C, 1, 0 -> zext C to int
1463     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1464       return new ZExtInst(CondVal, SelType);
1465 
1466     // select C, -1, 0 -> sext C to int
1467     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1468       return new SExtInst(CondVal, SelType);
1469 
1470     // select C, 0, 1 -> zext !C to int
1471     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1472       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1473       return new ZExtInst(NotCond, SelType);
1474     }
1475 
1476     // select C, 0, -1 -> sext !C to int
1477     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1478       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1479       return new SExtInst(NotCond, SelType);
1480     }
1481   }
1482 
1483   // See if we are selecting two values based on a comparison of the two values.
1484   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1485     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1486       // Transform (X == Y) ? X : Y  -> Y
1487       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1488         // This is not safe in general for floating point:
1489         // consider X== -0, Y== +0.
1490         // It becomes safe if either operand is a nonzero constant.
1491         ConstantFP *CFPt, *CFPf;
1492         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1493               !CFPt->getValueAPF().isZero()) ||
1494             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1495              !CFPf->getValueAPF().isZero()))
1496         return replaceInstUsesWith(SI, FalseVal);
1497       }
1498       // Transform (X une Y) ? X : Y  -> X
1499       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1500         // This is not safe in general for floating point:
1501         // consider X== -0, Y== +0.
1502         // It becomes safe if either operand is a nonzero constant.
1503         ConstantFP *CFPt, *CFPf;
1504         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1505               !CFPt->getValueAPF().isZero()) ||
1506             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1507              !CFPf->getValueAPF().isZero()))
1508         return replaceInstUsesWith(SI, TrueVal);
1509       }
1510 
1511       // Canonicalize to use ordered comparisons by swapping the select
1512       // operands.
1513       //
1514       // e.g.
1515       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1516       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1517         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1518         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1519         Builder.setFastMathFlags(FCI->getFastMathFlags());
1520         Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1521                                             FCI->getName() + ".inv");
1522 
1523         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1524                                   SI.getName() + ".p");
1525       }
1526 
1527       // NOTE: if we wanted to, this is where to detect MIN/MAX
1528     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1529       // Transform (X == Y) ? Y : X  -> X
1530       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1531         // This is not safe in general for floating point:
1532         // consider X== -0, Y== +0.
1533         // It becomes safe if either operand is a nonzero constant.
1534         ConstantFP *CFPt, *CFPf;
1535         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1536               !CFPt->getValueAPF().isZero()) ||
1537             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1538              !CFPf->getValueAPF().isZero()))
1539           return replaceInstUsesWith(SI, FalseVal);
1540       }
1541       // Transform (X une Y) ? Y : X  -> Y
1542       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1543         // This is not safe in general for floating point:
1544         // consider X== -0, Y== +0.
1545         // It becomes safe if either operand is a nonzero constant.
1546         ConstantFP *CFPt, *CFPf;
1547         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1548               !CFPt->getValueAPF().isZero()) ||
1549             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1550              !CFPf->getValueAPF().isZero()))
1551           return replaceInstUsesWith(SI, TrueVal);
1552       }
1553 
1554       // Canonicalize to use ordered comparisons by swapping the select
1555       // operands.
1556       //
1557       // e.g.
1558       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1559       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1560         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1561         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1562         Builder.setFastMathFlags(FCI->getFastMathFlags());
1563         Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1564                                             FCI->getName() + ".inv");
1565 
1566         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1567                                   SI.getName() + ".p");
1568       }
1569 
1570       // NOTE: if we wanted to, this is where to detect MIN/MAX
1571     }
1572     // NOTE: if we wanted to, this is where to detect ABS
1573   }
1574 
1575   // See if we are selecting two values based on a comparison of the two values.
1576   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1577     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1578       return Result;
1579 
1580   if (Instruction *Add = foldAddSubSelect(SI, Builder))
1581     return Add;
1582 
1583   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1584   auto *TI = dyn_cast<Instruction>(TrueVal);
1585   auto *FI = dyn_cast<Instruction>(FalseVal);
1586   if (TI && FI && TI->getOpcode() == FI->getOpcode())
1587     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1588       return IV;
1589 
1590   if (Instruction *I = foldSelectExtConst(SI))
1591     return I;
1592 
1593   // See if we can fold the select into one of our operands.
1594   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1595     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1596       return FoldI;
1597 
1598     Value *LHS, *RHS, *LHS2, *RHS2;
1599     Instruction::CastOps CastOp;
1600     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1601     auto SPF = SPR.Flavor;
1602 
1603     if (SelectPatternResult::isMinOrMax(SPF)) {
1604       // Canonicalize so that
1605       // - type casts are outside select patterns.
1606       // - float clamp is transformed to min/max pattern
1607 
1608       bool IsCastNeeded = LHS->getType() != SelType;
1609       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1610       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1611       if (IsCastNeeded ||
1612           (LHS->getType()->isFPOrFPVectorTy() &&
1613            ((CmpLHS != LHS && CmpLHS != RHS) ||
1614             (CmpRHS != LHS && CmpRHS != RHS)))) {
1615         CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
1616 
1617         Value *Cmp;
1618         if (CmpInst::isIntPredicate(Pred)) {
1619           Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1620         } else {
1621           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1622           auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1623           Builder.setFastMathFlags(FMF);
1624           Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1625         }
1626 
1627         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1628         if (!IsCastNeeded)
1629           return replaceInstUsesWith(SI, NewSI);
1630 
1631         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1632         return replaceInstUsesWith(SI, NewCast);
1633       }
1634 
1635       // MAX(~a, ~b) -> ~MIN(a, b)
1636       // MIN(~a, ~b) -> ~MAX(a, b)
1637       Value *A, *B;
1638       if (match(LHS, m_Not(m_Value(A))) && match(RHS, m_Not(m_Value(B))) &&
1639           (LHS->getNumUses() <= 2 || RHS->getNumUses() <= 2)) {
1640         CmpInst::Predicate InvertedPred = getInverseMinMaxPred(SPF);
1641         Value *InvertedCmp = Builder.CreateICmp(InvertedPred, A, B);
1642         Value *NewSel = Builder.CreateSelect(InvertedCmp, A, B);
1643         return BinaryOperator::CreateNot(NewSel);
1644       }
1645 
1646       if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1647         return I;
1648     }
1649 
1650     if (SPF) {
1651       // MAX(MAX(a, b), a) -> MAX(a, b)
1652       // MIN(MIN(a, b), a) -> MIN(a, b)
1653       // MAX(MIN(a, b), a) -> a
1654       // MIN(MAX(a, b), a) -> a
1655       // ABS(ABS(a)) -> ABS(a)
1656       // NABS(NABS(a)) -> NABS(a)
1657       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1658         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1659                                           SI, SPF, RHS))
1660           return R;
1661       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1662         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1663                                           SI, SPF, LHS))
1664           return R;
1665     }
1666 
1667     // TODO.
1668     // ABS(-X) -> ABS(X)
1669   }
1670 
1671   // See if we can fold the select into a phi node if the condition is a select.
1672   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1673     // The true/false values have to be live in the PHI predecessor's blocks.
1674     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1675         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1676       if (Instruction *NV = foldOpIntoPhi(SI, PN))
1677         return NV;
1678 
1679   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1680     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1681       // select(C, select(C, a, b), c) -> select(C, a, c)
1682       if (TrueSI->getCondition() == CondVal) {
1683         if (SI.getTrueValue() == TrueSI->getTrueValue())
1684           return nullptr;
1685         SI.setOperand(1, TrueSI->getTrueValue());
1686         return &SI;
1687       }
1688       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1689       // We choose this as normal form to enable folding on the And and shortening
1690       // paths for the values (this helps GetUnderlyingObjects() for example).
1691       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1692         Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1693         SI.setOperand(0, And);
1694         SI.setOperand(1, TrueSI->getTrueValue());
1695         return &SI;
1696       }
1697     }
1698   }
1699   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1700     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1701       // select(C, a, select(C, b, c)) -> select(C, a, c)
1702       if (FalseSI->getCondition() == CondVal) {
1703         if (SI.getFalseValue() == FalseSI->getFalseValue())
1704           return nullptr;
1705         SI.setOperand(2, FalseSI->getFalseValue());
1706         return &SI;
1707       }
1708       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1709       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1710         Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1711         SI.setOperand(0, Or);
1712         SI.setOperand(2, FalseSI->getFalseValue());
1713         return &SI;
1714       }
1715     }
1716   }
1717 
1718   auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
1719     // The select might be preventing a division by 0.
1720     switch (BO->getOpcode()) {
1721     default:
1722       return true;
1723     case Instruction::SRem:
1724     case Instruction::URem:
1725     case Instruction::SDiv:
1726     case Instruction::UDiv:
1727       return false;
1728     }
1729   };
1730 
1731   // Try to simplify a binop sandwiched between 2 selects with the same
1732   // condition.
1733   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
1734   BinaryOperator *TrueBO;
1735   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
1736       canMergeSelectThroughBinop(TrueBO)) {
1737     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
1738       if (TrueBOSI->getCondition() == CondVal) {
1739         TrueBO->setOperand(0, TrueBOSI->getTrueValue());
1740         Worklist.Add(TrueBO);
1741         return &SI;
1742       }
1743     }
1744     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
1745       if (TrueBOSI->getCondition() == CondVal) {
1746         TrueBO->setOperand(1, TrueBOSI->getTrueValue());
1747         Worklist.Add(TrueBO);
1748         return &SI;
1749       }
1750     }
1751   }
1752 
1753   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
1754   BinaryOperator *FalseBO;
1755   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
1756       canMergeSelectThroughBinop(FalseBO)) {
1757     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
1758       if (FalseBOSI->getCondition() == CondVal) {
1759         FalseBO->setOperand(0, FalseBOSI->getFalseValue());
1760         Worklist.Add(FalseBO);
1761         return &SI;
1762       }
1763     }
1764     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
1765       if (FalseBOSI->getCondition() == CondVal) {
1766         FalseBO->setOperand(1, FalseBOSI->getFalseValue());
1767         Worklist.Add(FalseBO);
1768         return &SI;
1769       }
1770     }
1771   }
1772 
1773   if (BinaryOperator::isNot(CondVal)) {
1774     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1775     SI.setOperand(1, FalseVal);
1776     SI.setOperand(2, TrueVal);
1777     return &SI;
1778   }
1779 
1780   if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
1781     unsigned VWidth = VecTy->getNumElements();
1782     APInt UndefElts(VWidth, 0);
1783     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1784     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1785       if (V != &SI)
1786         return replaceInstUsesWith(SI, V);
1787       return &SI;
1788     }
1789   }
1790 
1791   // See if we can determine the result of this select based on a dominating
1792   // condition.
1793   BasicBlock *Parent = SI.getParent();
1794   if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1795     auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1796     if (PBI && PBI->isConditional() &&
1797         PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1798         (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1799       bool CondIsTrue = PBI->getSuccessor(0) == Parent;
1800       Optional<bool> Implication = isImpliedCondition(
1801           PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
1802       if (Implication) {
1803         Value *V = *Implication ? TrueVal : FalseVal;
1804         return replaceInstUsesWith(SI, V);
1805       }
1806     }
1807   }
1808 
1809   // If we can compute the condition, there's no need for a select.
1810   // Like the above fold, we are attempting to reduce compile-time cost by
1811   // putting this fold here with limitations rather than in InstSimplify.
1812   // The motivation for this call into value tracking is to take advantage of
1813   // the assumption cache, so make sure that is populated.
1814   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
1815     KnownBits Known(1);
1816     computeKnownBits(CondVal, Known, 0, &SI);
1817     if (Known.One.isOneValue())
1818       return replaceInstUsesWith(SI, TrueVal);
1819     if (Known.Zero.isOneValue())
1820       return replaceInstUsesWith(SI, FalseVal);
1821   }
1822 
1823   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
1824     return BitCastSel;
1825 
1826   // Simplify selects that test the returned flag of cmpxchg instructions.
1827   if (Instruction *Select = foldSelectCmpXchg(SI))
1828     return Select;
1829 
1830   return nullptr;
1831 }
1832