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