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