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 "llvm/Transforms/InstCombine/InstCombiner.h"
42 #include <cassert>
43 #include <utility>
44 
45 using namespace llvm;
46 using namespace PatternMatch;
47 
48 #define DEBUG_TYPE "instcombine"
49 
50 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
51                            SelectPatternFlavor SPF, Value *A, Value *B) {
52   CmpInst::Predicate Pred = getMinMaxPred(SPF);
53   assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
54   return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
55 }
56 
57 /// Replace a select operand based on an equality comparison with the identity
58 /// constant of a binop.
59 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
60                                             const TargetLibraryInfo &TLI,
61                                             InstCombinerImpl &IC) {
62   // The select condition must be an equality compare with a constant operand.
63   Value *X;
64   Constant *C;
65   CmpInst::Predicate Pred;
66   if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
67     return nullptr;
68 
69   bool IsEq;
70   if (ICmpInst::isEquality(Pred))
71     IsEq = Pred == ICmpInst::ICMP_EQ;
72   else if (Pred == FCmpInst::FCMP_OEQ)
73     IsEq = true;
74   else if (Pred == FCmpInst::FCMP_UNE)
75     IsEq = false;
76   else
77     return nullptr;
78 
79   // A select operand must be a binop.
80   BinaryOperator *BO;
81   if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
82     return nullptr;
83 
84   // The compare constant must be the identity constant for that binop.
85   // If this a floating-point compare with 0.0, any zero constant will do.
86   Type *Ty = BO->getType();
87   Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
88   if (IdC != C) {
89     if (!IdC || !CmpInst::isFPPredicate(Pred))
90       return nullptr;
91     if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
92       return nullptr;
93   }
94 
95   // Last, match the compare variable operand with a binop operand.
96   Value *Y;
97   if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
98     return nullptr;
99   if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
100     return nullptr;
101 
102   // +0.0 compares equal to -0.0, and so it does not behave as required for this
103   // transform. Bail out if we can not exclude that possibility.
104   if (isa<FPMathOperator>(BO))
105     if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
106       return nullptr;
107 
108   // BO = binop Y, X
109   // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
110   // =>
111   // S = { select (cmp eq X, C),  Y, ? } or { select (cmp ne X, C), ?,  Y }
112   return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
113 }
114 
115 /// This folds:
116 ///  select (icmp eq (and X, C1)), TC, FC
117 ///    iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
118 /// To something like:
119 ///  (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
120 /// Or:
121 ///  (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
122 /// With some variations depending if FC is larger than TC, or the shift
123 /// isn't needed, or the bit widths don't match.
124 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
125                                 InstCombiner::BuilderTy &Builder) {
126   const APInt *SelTC, *SelFC;
127   if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
128       !match(Sel.getFalseValue(), m_APInt(SelFC)))
129     return nullptr;
130 
131   // If this is a vector select, we need a vector compare.
132   Type *SelType = Sel.getType();
133   if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
134     return nullptr;
135 
136   Value *V;
137   APInt AndMask;
138   bool CreateAnd = false;
139   ICmpInst::Predicate Pred = Cmp->getPredicate();
140   if (ICmpInst::isEquality(Pred)) {
141     if (!match(Cmp->getOperand(1), m_Zero()))
142       return nullptr;
143 
144     V = Cmp->getOperand(0);
145     const APInt *AndRHS;
146     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
147       return nullptr;
148 
149     AndMask = *AndRHS;
150   } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
151                                   Pred, V, AndMask)) {
152     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
153     if (!AndMask.isPowerOf2())
154       return nullptr;
155 
156     CreateAnd = true;
157   } else {
158     return nullptr;
159   }
160 
161   // In general, when both constants are non-zero, we would need an offset to
162   // replace the select. This would require more instructions than we started
163   // with. But there's one special-case that we handle here because it can
164   // simplify/reduce the instructions.
165   APInt TC = *SelTC;
166   APInt FC = *SelFC;
167   if (!TC.isNullValue() && !FC.isNullValue()) {
168     // If the select constants differ by exactly one bit and that's the same
169     // bit that is masked and checked by the select condition, the select can
170     // be replaced by bitwise logic to set/clear one bit of the constant result.
171     if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
172       return nullptr;
173     if (CreateAnd) {
174       // If we have to create an 'and', then we must kill the cmp to not
175       // increase the instruction count.
176       if (!Cmp->hasOneUse())
177         return nullptr;
178       V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
179     }
180     bool ExtraBitInTC = TC.ugt(FC);
181     if (Pred == ICmpInst::ICMP_EQ) {
182       // If the masked bit in V is clear, clear or set the bit in the result:
183       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
184       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
185       Constant *C = ConstantInt::get(SelType, TC);
186       return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
187     }
188     if (Pred == ICmpInst::ICMP_NE) {
189       // If the masked bit in V is set, set or clear the bit in the result:
190       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
191       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
192       Constant *C = ConstantInt::get(SelType, FC);
193       return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
194     }
195     llvm_unreachable("Only expecting equality predicates");
196   }
197 
198   // Make sure one of the select arms is a power-of-2.
199   if (!TC.isPowerOf2() && !FC.isPowerOf2())
200     return nullptr;
201 
202   // Determine which shift is needed to transform result of the 'and' into the
203   // desired result.
204   const APInt &ValC = !TC.isNullValue() ? TC : FC;
205   unsigned ValZeros = ValC.logBase2();
206   unsigned AndZeros = AndMask.logBase2();
207 
208   // Insert the 'and' instruction on the input to the truncate.
209   if (CreateAnd)
210     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
211 
212   // If types don't match, we can still convert the select by introducing a zext
213   // or a trunc of the 'and'.
214   if (ValZeros > AndZeros) {
215     V = Builder.CreateZExtOrTrunc(V, SelType);
216     V = Builder.CreateShl(V, ValZeros - AndZeros);
217   } else if (ValZeros < AndZeros) {
218     V = Builder.CreateLShr(V, AndZeros - ValZeros);
219     V = Builder.CreateZExtOrTrunc(V, SelType);
220   } else {
221     V = Builder.CreateZExtOrTrunc(V, SelType);
222   }
223 
224   // Okay, now we know that everything is set up, we just don't know whether we
225   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
226   bool ShouldNotVal = !TC.isNullValue();
227   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
228   if (ShouldNotVal)
229     V = Builder.CreateXor(V, ValC);
230 
231   return V;
232 }
233 
234 /// We want to turn code that looks like this:
235 ///   %C = or %A, %B
236 ///   %D = select %cond, %C, %A
237 /// into:
238 ///   %C = select %cond, %B, 0
239 ///   %D = or %A, %C
240 ///
241 /// Assuming that the specified instruction is an operand to the select, return
242 /// a bitmask indicating which operands of this instruction are foldable if they
243 /// equal the other incoming value of the select.
244 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
245   switch (I->getOpcode()) {
246   case Instruction::Add:
247   case Instruction::Mul:
248   case Instruction::And:
249   case Instruction::Or:
250   case Instruction::Xor:
251     return 3;              // Can fold through either operand.
252   case Instruction::Sub:   // Can only fold on the amount subtracted.
253   case Instruction::Shl:   // Can only fold on the shift amount.
254   case Instruction::LShr:
255   case Instruction::AShr:
256     return 1;
257   default:
258     return 0;              // Cannot fold
259   }
260 }
261 
262 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
263 Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
264                                               Instruction *FI) {
265   // Don't break up min/max patterns. The hasOneUse checks below prevent that
266   // for most cases, but vector min/max with bitcasts can be transformed. If the
267   // one-use restrictions are eased for other patterns, we still don't want to
268   // obfuscate min/max.
269   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
270        match(&SI, m_SMax(m_Value(), m_Value())) ||
271        match(&SI, m_UMin(m_Value(), m_Value())) ||
272        match(&SI, m_UMax(m_Value(), m_Value()))))
273     return nullptr;
274 
275   // If this is a cast from the same type, merge.
276   Value *Cond = SI.getCondition();
277   Type *CondTy = Cond->getType();
278   if (TI->getNumOperands() == 1 && TI->isCast()) {
279     Type *FIOpndTy = FI->getOperand(0)->getType();
280     if (TI->getOperand(0)->getType() != FIOpndTy)
281       return nullptr;
282 
283     // The select condition may be a vector. We may only change the operand
284     // type if the vector width remains the same (and matches the condition).
285     if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
286       if (!FIOpndTy->isVectorTy())
287         return nullptr;
288       if (cast<FixedVectorType>(CondVTy)->getNumElements() !=
289           cast<FixedVectorType>(FIOpndTy)->getNumElements())
290         return nullptr;
291 
292       // TODO: If the backend knew how to deal with casts better, we could
293       // remove this limitation. For now, there's too much potential to create
294       // worse codegen by promoting the select ahead of size-altering casts
295       // (PR28160).
296       //
297       // Note that ValueTracking's matchSelectPattern() looks through casts
298       // without checking 'hasOneUse' when it matches min/max patterns, so this
299       // transform may end up happening anyway.
300       if (TI->getOpcode() != Instruction::BitCast &&
301           (!TI->hasOneUse() || !FI->hasOneUse()))
302         return nullptr;
303     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
304       // TODO: The one-use restrictions for a scalar select could be eased if
305       // the fold of a select in visitLoadInst() was enhanced to match a pattern
306       // that includes a cast.
307       return nullptr;
308     }
309 
310     // Fold this by inserting a select from the input values.
311     Value *NewSI =
312         Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
313                              SI.getName() + ".v", &SI);
314     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
315                             TI->getType());
316   }
317 
318   // Cond ? -X : -Y --> -(Cond ? X : Y)
319   Value *X, *Y;
320   if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
321       (TI->hasOneUse() || FI->hasOneUse())) {
322     Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
323     return UnaryOperator::CreateFNegFMF(NewSel, TI);
324   }
325 
326   // Only handle binary operators (including two-operand getelementptr) with
327   // one-use here. As with the cast case above, it may be possible to relax the
328   // one-use constraint, but that needs be examined carefully since it may not
329   // reduce the total number of instructions.
330   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
331       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
332       !TI->hasOneUse() || !FI->hasOneUse())
333     return nullptr;
334 
335   // Figure out if the operations have any operands in common.
336   Value *MatchOp, *OtherOpT, *OtherOpF;
337   bool MatchIsOpZero;
338   if (TI->getOperand(0) == FI->getOperand(0)) {
339     MatchOp  = TI->getOperand(0);
340     OtherOpT = TI->getOperand(1);
341     OtherOpF = FI->getOperand(1);
342     MatchIsOpZero = true;
343   } else if (TI->getOperand(1) == FI->getOperand(1)) {
344     MatchOp  = TI->getOperand(1);
345     OtherOpT = TI->getOperand(0);
346     OtherOpF = FI->getOperand(0);
347     MatchIsOpZero = false;
348   } else if (!TI->isCommutative()) {
349     return nullptr;
350   } else if (TI->getOperand(0) == FI->getOperand(1)) {
351     MatchOp  = TI->getOperand(0);
352     OtherOpT = TI->getOperand(1);
353     OtherOpF = FI->getOperand(0);
354     MatchIsOpZero = true;
355   } else if (TI->getOperand(1) == FI->getOperand(0)) {
356     MatchOp  = TI->getOperand(1);
357     OtherOpT = TI->getOperand(0);
358     OtherOpF = FI->getOperand(1);
359     MatchIsOpZero = true;
360   } else {
361     return nullptr;
362   }
363 
364   // If the select condition is a vector, the operands of the original select's
365   // operands also must be vectors. This may not be the case for getelementptr
366   // for example.
367   if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
368                                !OtherOpF->getType()->isVectorTy()))
369     return nullptr;
370 
371   // If we reach here, they do have operations in common.
372   Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
373                                       SI.getName() + ".v", &SI);
374   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
375   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
376   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
377     BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
378     NewBO->copyIRFlags(TI);
379     NewBO->andIRFlags(FI);
380     return NewBO;
381   }
382   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
383     auto *FGEP = cast<GetElementPtrInst>(FI);
384     Type *ElementType = TGEP->getResultElementType();
385     return TGEP->isInBounds() && FGEP->isInBounds()
386                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
387                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
388   }
389   llvm_unreachable("Expected BinaryOperator or GEP");
390   return nullptr;
391 }
392 
393 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
394   if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
395     return false;
396   return C1I.isOneValue() || C1I.isAllOnesValue() ||
397          C2I.isOneValue() || C2I.isAllOnesValue();
398 }
399 
400 /// Try to fold the select into one of the operands to allow further
401 /// optimization.
402 Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
403                                                 Value *FalseVal) {
404   // See the comment above GetSelectFoldableOperands for a description of the
405   // transformation we are doing here.
406   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
407     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
408       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
409         unsigned OpToFold = 0;
410         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
411           OpToFold = 1;
412         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
413           OpToFold = 2;
414         }
415 
416         if (OpToFold) {
417           Constant *C = ConstantExpr::getBinOpIdentity(TVI->getOpcode(),
418                                                        TVI->getType(), true);
419           Value *OOp = TVI->getOperand(2-OpToFold);
420           // Avoid creating select between 2 constants unless it's selecting
421           // between 0, 1 and -1.
422           const APInt *OOpC;
423           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
424           if (!isa<Constant>(OOp) ||
425               (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) {
426             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
427             NewSel->takeName(TVI);
428             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
429                                                         FalseVal, NewSel);
430             BO->copyIRFlags(TVI);
431             return BO;
432           }
433         }
434       }
435     }
436   }
437 
438   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
439     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
440       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
441         unsigned OpToFold = 0;
442         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
443           OpToFold = 1;
444         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
445           OpToFold = 2;
446         }
447 
448         if (OpToFold) {
449           Constant *C = ConstantExpr::getBinOpIdentity(FVI->getOpcode(),
450                                                        FVI->getType(), true);
451           Value *OOp = FVI->getOperand(2-OpToFold);
452           // Avoid creating select between 2 constants unless it's selecting
453           // between 0, 1 and -1.
454           const APInt *OOpC;
455           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
456           if (!isa<Constant>(OOp) ||
457               (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) {
458             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
459             NewSel->takeName(FVI);
460             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
461                                                         TrueVal, NewSel);
462             BO->copyIRFlags(FVI);
463             return BO;
464           }
465         }
466       }
467     }
468   }
469 
470   return nullptr;
471 }
472 
473 /// We want to turn:
474 ///   (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
475 /// into:
476 ///   zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
477 /// Note:
478 ///   Z may be 0 if lshr is missing.
479 /// Worst-case scenario is that we will replace 5 instructions with 5 different
480 /// instructions, but we got rid of select.
481 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
482                                          Value *TVal, Value *FVal,
483                                          InstCombiner::BuilderTy &Builder) {
484   if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
485         Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
486         match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
487     return nullptr;
488 
489   // The TrueVal has general form of:  and %B, 1
490   Value *B;
491   if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
492     return nullptr;
493 
494   // Where %B may be optionally shifted:  lshr %X, %Z.
495   Value *X, *Z;
496   const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
497   if (!HasShift)
498     X = B;
499 
500   Value *Y;
501   if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
502     return nullptr;
503 
504   // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
505   // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
506   Constant *One = ConstantInt::get(SelType, 1);
507   Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
508   Value *FullMask = Builder.CreateOr(Y, MaskB);
509   Value *MaskedX = Builder.CreateAnd(X, FullMask);
510   Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
511   return new ZExtInst(ICmpNeZero, SelType);
512 }
513 
514 /// We want to turn:
515 ///   (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
516 ///   (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
517 /// into:
518 ///   ashr (X, Y)
519 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
520                                      Value *FalseVal,
521                                      InstCombiner::BuilderTy &Builder) {
522   ICmpInst::Predicate Pred = IC->getPredicate();
523   Value *CmpLHS = IC->getOperand(0);
524   Value *CmpRHS = IC->getOperand(1);
525   if (!CmpRHS->getType()->isIntOrIntVectorTy())
526     return nullptr;
527 
528   Value *X, *Y;
529   unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
530   if ((Pred != ICmpInst::ICMP_SGT ||
531        !match(CmpRHS,
532               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
533       (Pred != ICmpInst::ICMP_SLT ||
534        !match(CmpRHS,
535               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
536     return nullptr;
537 
538   // Canonicalize so that ashr is in FalseVal.
539   if (Pred == ICmpInst::ICMP_SLT)
540     std::swap(TrueVal, FalseVal);
541 
542   if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
543       match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
544       match(CmpLHS, m_Specific(X))) {
545     const auto *Ashr = cast<Instruction>(FalseVal);
546     // if lshr is not exact and ashr is, this new ashr must not be exact.
547     bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
548     return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
549   }
550 
551   return nullptr;
552 }
553 
554 /// We want to turn:
555 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
556 /// into:
557 ///   (or (shl (and X, C1), C3), Y)
558 /// iff:
559 ///   C1 and C2 are both powers of 2
560 /// where:
561 ///   C3 = Log(C2) - Log(C1)
562 ///
563 /// This transform handles cases where:
564 /// 1. The icmp predicate is inverted
565 /// 2. The select operands are reversed
566 /// 3. The magnitude of C2 and C1 are flipped
567 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
568                                   Value *FalseVal,
569                                   InstCombiner::BuilderTy &Builder) {
570   // Only handle integer compares. Also, if this is a vector select, we need a
571   // vector compare.
572   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
573       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
574     return nullptr;
575 
576   Value *CmpLHS = IC->getOperand(0);
577   Value *CmpRHS = IC->getOperand(1);
578 
579   Value *V;
580   unsigned C1Log;
581   bool IsEqualZero;
582   bool NeedAnd = false;
583   if (IC->isEquality()) {
584     if (!match(CmpRHS, m_Zero()))
585       return nullptr;
586 
587     const APInt *C1;
588     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
589       return nullptr;
590 
591     V = CmpLHS;
592     C1Log = C1->logBase2();
593     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
594   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
595              IC->getPredicate() == ICmpInst::ICMP_SGT) {
596     // We also need to recognize (icmp slt (trunc (X)), 0) and
597     // (icmp sgt (trunc (X)), -1).
598     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
599     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
600         (!IsEqualZero && !match(CmpRHS, m_Zero())))
601       return nullptr;
602 
603     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
604       return nullptr;
605 
606     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
607     NeedAnd = true;
608   } else {
609     return nullptr;
610   }
611 
612   const APInt *C2;
613   bool OrOnTrueVal = false;
614   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
615   if (!OrOnFalseVal)
616     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
617 
618   if (!OrOnFalseVal && !OrOnTrueVal)
619     return nullptr;
620 
621   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
622 
623   unsigned C2Log = C2->logBase2();
624 
625   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
626   bool NeedShift = C1Log != C2Log;
627   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
628                        V->getType()->getScalarSizeInBits();
629 
630   // Make sure we don't create more instructions than we save.
631   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
632   if ((NeedShift + NeedXor + NeedZExtTrunc) >
633       (IC->hasOneUse() + Or->hasOneUse()))
634     return nullptr;
635 
636   if (NeedAnd) {
637     // Insert the AND instruction on the input to the truncate.
638     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
639     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
640   }
641 
642   if (C2Log > C1Log) {
643     V = Builder.CreateZExtOrTrunc(V, Y->getType());
644     V = Builder.CreateShl(V, C2Log - C1Log);
645   } else if (C1Log > C2Log) {
646     V = Builder.CreateLShr(V, C1Log - C2Log);
647     V = Builder.CreateZExtOrTrunc(V, Y->getType());
648   } else
649     V = Builder.CreateZExtOrTrunc(V, Y->getType());
650 
651   if (NeedXor)
652     V = Builder.CreateXor(V, *C2);
653 
654   return Builder.CreateOr(V, Y);
655 }
656 
657 /// Canonicalize a set or clear of a masked set of constant bits to
658 /// select-of-constants form.
659 static Instruction *foldSetClearBits(SelectInst &Sel,
660                                      InstCombiner::BuilderTy &Builder) {
661   Value *Cond = Sel.getCondition();
662   Value *T = Sel.getTrueValue();
663   Value *F = Sel.getFalseValue();
664   Type *Ty = Sel.getType();
665   Value *X;
666   const APInt *NotC, *C;
667 
668   // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
669   if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
670       match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
671     Constant *Zero = ConstantInt::getNullValue(Ty);
672     Constant *OrC = ConstantInt::get(Ty, *C);
673     Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
674     return BinaryOperator::CreateOr(T, NewSel);
675   }
676 
677   // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
678   if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
679       match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
680     Constant *Zero = ConstantInt::getNullValue(Ty);
681     Constant *OrC = ConstantInt::get(Ty, *C);
682     Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
683     return BinaryOperator::CreateOr(F, NewSel);
684   }
685 
686   return nullptr;
687 }
688 
689 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
690 /// There are 8 commuted/swapped variants of this pattern.
691 /// TODO: Also support a - UMIN(a,b) patterns.
692 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
693                                             const Value *TrueVal,
694                                             const Value *FalseVal,
695                                             InstCombiner::BuilderTy &Builder) {
696   ICmpInst::Predicate Pred = ICI->getPredicate();
697   if (!ICmpInst::isUnsigned(Pred))
698     return nullptr;
699 
700   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
701   if (match(TrueVal, m_Zero())) {
702     Pred = ICmpInst::getInversePredicate(Pred);
703     std::swap(TrueVal, FalseVal);
704   }
705   if (!match(FalseVal, m_Zero()))
706     return nullptr;
707 
708   Value *A = ICI->getOperand(0);
709   Value *B = ICI->getOperand(1);
710   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
711     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
712     std::swap(A, B);
713     Pred = ICmpInst::getSwappedPredicate(Pred);
714   }
715 
716   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
717          "Unexpected isUnsigned predicate!");
718 
719   // Ensure the sub is of the form:
720   //  (a > b) ? a - b : 0 -> usub.sat(a, b)
721   //  (a > b) ? b - a : 0 -> -usub.sat(a, b)
722   // Checking for both a-b and a+(-b) as a constant.
723   bool IsNegative = false;
724   const APInt *C;
725   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
726       (match(A, m_APInt(C)) &&
727        match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
728     IsNegative = true;
729   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
730            !(match(B, m_APInt(C)) &&
731              match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
732     return nullptr;
733 
734   // If we are adding a negate and the sub and icmp are used anywhere else, we
735   // would end up with more instructions.
736   if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
737     return nullptr;
738 
739   // (a > b) ? a - b : 0 -> usub.sat(a, b)
740   // (a > b) ? b - a : 0 -> -usub.sat(a, b)
741   Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
742   if (IsNegative)
743     Result = Builder.CreateNeg(Result);
744   return Result;
745 }
746 
747 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
748                                        InstCombiner::BuilderTy &Builder) {
749   if (!Cmp->hasOneUse())
750     return nullptr;
751 
752   // Match unsigned saturated add with constant.
753   Value *Cmp0 = Cmp->getOperand(0);
754   Value *Cmp1 = Cmp->getOperand(1);
755   ICmpInst::Predicate Pred = Cmp->getPredicate();
756   Value *X;
757   const APInt *C, *CmpC;
758   if (Pred == ICmpInst::ICMP_ULT &&
759       match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
760       match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
761     // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
762     return Builder.CreateBinaryIntrinsic(
763         Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
764   }
765 
766   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
767   // There are 8 commuted variants.
768   // Canonicalize -1 (saturated result) to true value of the select. Just
769   // swapping the compare operands is legal, because the selected value is the
770   // same in case of equality, so we can interchange u< and u<=.
771   if (match(FVal, m_AllOnes())) {
772     std::swap(TVal, FVal);
773     std::swap(Cmp0, Cmp1);
774   }
775   if (!match(TVal, m_AllOnes()))
776     return nullptr;
777 
778   // Canonicalize predicate to 'ULT'.
779   if (Pred == ICmpInst::ICMP_UGT) {
780     Pred = ICmpInst::ICMP_ULT;
781     std::swap(Cmp0, Cmp1);
782   }
783   if (Pred != ICmpInst::ICMP_ULT)
784     return nullptr;
785 
786   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
787   Value *Y;
788   if (match(Cmp0, m_Not(m_Value(X))) &&
789       match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
790     // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
791     // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
792     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
793   }
794   // The 'not' op may be included in the sum but not the compare.
795   X = Cmp0;
796   Y = Cmp1;
797   if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
798     // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
799     // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
800     BinaryOperator *BO = cast<BinaryOperator>(FVal);
801     return Builder.CreateBinaryIntrinsic(
802         Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
803   }
804   // The overflow may be detected via the add wrapping round.
805   if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
806       match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
807     // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
808     // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
809     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
810   }
811 
812   return nullptr;
813 }
814 
815 /// Fold the following code sequence:
816 /// \code
817 ///   int a = ctlz(x & -x);
818 //    x ? 31 - a : a;
819 /// \code
820 ///
821 /// into:
822 ///   cttz(x)
823 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
824                                          Value *FalseVal,
825                                          InstCombiner::BuilderTy &Builder) {
826   unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
827   if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
828     return nullptr;
829 
830   if (ICI->getPredicate() == ICmpInst::ICMP_NE)
831     std::swap(TrueVal, FalseVal);
832 
833   if (!match(FalseVal,
834              m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
835     return nullptr;
836 
837   if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
838     return nullptr;
839 
840   Value *X = ICI->getOperand(0);
841   auto *II = cast<IntrinsicInst>(TrueVal);
842   if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
843     return nullptr;
844 
845   Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
846                                           II->getType());
847   return CallInst::Create(F, {X, II->getArgOperand(1)});
848 }
849 
850 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
851 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
852 ///
853 /// For example, we can fold the following code sequence:
854 /// \code
855 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
856 ///   %1 = icmp ne i32 %x, 0
857 ///   %2 = select i1 %1, i32 %0, i32 32
858 /// \code
859 ///
860 /// into:
861 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
862 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
863                                  InstCombiner::BuilderTy &Builder) {
864   ICmpInst::Predicate Pred = ICI->getPredicate();
865   Value *CmpLHS = ICI->getOperand(0);
866   Value *CmpRHS = ICI->getOperand(1);
867 
868   // Check if the condition value compares a value for equality against zero.
869   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
870     return nullptr;
871 
872   Value *SelectArg = FalseVal;
873   Value *ValueOnZero = TrueVal;
874   if (Pred == ICmpInst::ICMP_NE)
875     std::swap(SelectArg, ValueOnZero);
876 
877   // Skip zero extend/truncate.
878   Value *Count = nullptr;
879   if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
880       !match(SelectArg, m_Trunc(m_Value(Count))))
881     Count = SelectArg;
882 
883   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
884   // input to the cttz/ctlz is used as LHS for the compare instruction.
885   if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
886       !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
887     return nullptr;
888 
889   IntrinsicInst *II = cast<IntrinsicInst>(Count);
890 
891   // Check if the value propagated on zero is a constant number equal to the
892   // sizeof in bits of 'Count'.
893   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
894   if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
895     // Explicitly clear the 'undef_on_zero' flag. It's always valid to go from
896     // true to false on this flag, so we can replace it for all users.
897     II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
898     return SelectArg;
899   }
900 
901   // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
902   // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
903   // not be used if the input is zero. Relax to 'undef_on_zero' for that case.
904   if (II->hasOneUse() && SelectArg->hasOneUse() &&
905       !match(II->getArgOperand(1), m_One()))
906     II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
907 
908   return nullptr;
909 }
910 
911 /// Return true if we find and adjust an icmp+select pattern where the compare
912 /// is with a constant that can be incremented or decremented to match the
913 /// minimum or maximum idiom.
914 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
915   ICmpInst::Predicate Pred = Cmp.getPredicate();
916   Value *CmpLHS = Cmp.getOperand(0);
917   Value *CmpRHS = Cmp.getOperand(1);
918   Value *TrueVal = Sel.getTrueValue();
919   Value *FalseVal = Sel.getFalseValue();
920 
921   // We may move or edit the compare, so make sure the select is the only user.
922   const APInt *CmpC;
923   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
924     return false;
925 
926   // These transforms only work for selects of integers or vector selects of
927   // integer vectors.
928   Type *SelTy = Sel.getType();
929   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
930   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
931     return false;
932 
933   Constant *AdjustedRHS;
934   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
935     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
936   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
937     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
938   else
939     return false;
940 
941   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
942   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
943   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
944       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
945     ; // Nothing to do here. Values match without any sign/zero extension.
946   }
947   // Types do not match. Instead of calculating this with mixed types, promote
948   // all to the larger type. This enables scalar evolution to analyze this
949   // expression.
950   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
951     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
952 
953     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
954     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
955     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
956     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
957     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
958       CmpLHS = TrueVal;
959       AdjustedRHS = SextRHS;
960     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
961                SextRHS == TrueVal) {
962       CmpLHS = FalseVal;
963       AdjustedRHS = SextRHS;
964     } else if (Cmp.isUnsigned()) {
965       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
966       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
967       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
968       // zext + signed compare cannot be changed:
969       //    0xff <s 0x00, but 0x00ff >s 0x0000
970       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
971         CmpLHS = TrueVal;
972         AdjustedRHS = ZextRHS;
973       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
974                  ZextRHS == TrueVal) {
975         CmpLHS = FalseVal;
976         AdjustedRHS = ZextRHS;
977       } else {
978         return false;
979       }
980     } else {
981       return false;
982     }
983   } else {
984     return false;
985   }
986 
987   Pred = ICmpInst::getSwappedPredicate(Pred);
988   CmpRHS = AdjustedRHS;
989   std::swap(FalseVal, TrueVal);
990   Cmp.setPredicate(Pred);
991   Cmp.setOperand(0, CmpLHS);
992   Cmp.setOperand(1, CmpRHS);
993   Sel.setOperand(1, TrueVal);
994   Sel.setOperand(2, FalseVal);
995   Sel.swapProfMetadata();
996 
997   // Move the compare instruction right before the select instruction. Otherwise
998   // the sext/zext value may be defined after the compare instruction uses it.
999   Cmp.moveBefore(&Sel);
1000 
1001   return true;
1002 }
1003 
1004 /// If this is an integer min/max (icmp + select) with a constant operand,
1005 /// create the canonical icmp for the min/max operation and canonicalize the
1006 /// constant to the 'false' operand of the select:
1007 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
1008 /// Note: if C1 != C2, this will change the icmp constant to the existing
1009 /// constant operand of the select.
1010 static Instruction *canonicalizeMinMaxWithConstant(SelectInst &Sel,
1011                                                    ICmpInst &Cmp,
1012                                                    InstCombinerImpl &IC) {
1013   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1014     return nullptr;
1015 
1016   // Canonicalize the compare predicate based on whether we have min or max.
1017   Value *LHS, *RHS;
1018   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
1019   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1020     return nullptr;
1021 
1022   // Is this already canonical?
1023   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1024   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1025       Cmp.getPredicate() == CanonicalPred)
1026     return nullptr;
1027 
1028   // Bail out on unsimplified X-0 operand (due to some worklist management bug),
1029   // as this may cause an infinite combine loop. Let the sub be folded first.
1030   if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1031       match(RHS, m_Sub(m_Value(), m_Zero())))
1032     return nullptr;
1033 
1034   // Create the canonical compare and plug it into the select.
1035   IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS));
1036 
1037   // If the select operands did not change, we're done.
1038   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1039     return &Sel;
1040 
1041   // If we are swapping the select operands, swap the metadata too.
1042   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
1043          "Unexpected results from matchSelectPattern");
1044   Sel.swapValues();
1045   Sel.swapProfMetadata();
1046   return &Sel;
1047 }
1048 
1049 /// There are many select variants for each of ABS/NABS.
1050 /// In matchSelectPattern(), there are different compare constants, compare
1051 /// predicates/operands and select operands.
1052 /// In isKnownNegation(), there are different formats of negated operands.
1053 /// Canonicalize all these variants to 1 pattern.
1054 /// This makes CSE more likely.
1055 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1056                                         InstCombinerImpl &IC) {
1057   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1058     return nullptr;
1059 
1060   // Choose a sign-bit check for the compare (likely simpler for codegen).
1061   // ABS:  (X <s 0) ? -X : X
1062   // NABS: (X <s 0) ? X : -X
1063   Value *LHS, *RHS;
1064   SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1065   if (SPF != SelectPatternFlavor::SPF_ABS &&
1066       SPF != SelectPatternFlavor::SPF_NABS)
1067     return nullptr;
1068 
1069   Value *TVal = Sel.getTrueValue();
1070   Value *FVal = Sel.getFalseValue();
1071   assert(isKnownNegation(TVal, FVal) &&
1072          "Unexpected result from matchSelectPattern");
1073 
1074   // The compare may use the negated abs()/nabs() operand, or it may use
1075   // negation in non-canonical form such as: sub A, B.
1076   bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
1077                           match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
1078 
1079   bool CmpCanonicalized = !CmpUsesNegatedOp &&
1080                           match(Cmp.getOperand(1), m_ZeroInt()) &&
1081                           Cmp.getPredicate() == ICmpInst::ICMP_SLT;
1082   bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
1083 
1084   // Is this already canonical?
1085   if (CmpCanonicalized && RHSCanonicalized)
1086     return nullptr;
1087 
1088   // If RHS is not canonical but is used by other instructions, don't
1089   // canonicalize it and potentially increase the instruction count.
1090   if (!RHSCanonicalized)
1091     if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
1092       return nullptr;
1093 
1094   // Create the canonical compare: icmp slt LHS 0.
1095   if (!CmpCanonicalized) {
1096     Cmp.setPredicate(ICmpInst::ICMP_SLT);
1097     Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
1098     if (CmpUsesNegatedOp)
1099       Cmp.setOperand(0, LHS);
1100   }
1101 
1102   // Create the canonical RHS: RHS = sub (0, LHS).
1103   if (!RHSCanonicalized) {
1104     assert(RHS->hasOneUse() && "RHS use number is not right");
1105     RHS = IC.Builder.CreateNeg(LHS);
1106     if (TVal == LHS) {
1107       // Replace false value.
1108       IC.replaceOperand(Sel, 2, RHS);
1109       FVal = RHS;
1110     } else {
1111       // Replace true value.
1112       IC.replaceOperand(Sel, 1, RHS);
1113       TVal = RHS;
1114     }
1115   }
1116 
1117   // If the select operands do not change, we're done.
1118   if (SPF == SelectPatternFlavor::SPF_NABS) {
1119     if (TVal == LHS)
1120       return &Sel;
1121     assert(FVal == LHS && "Unexpected results from matchSelectPattern");
1122   } else {
1123     if (FVal == LHS)
1124       return &Sel;
1125     assert(TVal == LHS && "Unexpected results from matchSelectPattern");
1126   }
1127 
1128   // We are swapping the select operands, so swap the metadata too.
1129   Sel.swapValues();
1130   Sel.swapProfMetadata();
1131   return &Sel;
1132 }
1133 
1134 /// If we have a select with an equality comparison, then we know the value in
1135 /// one of the arms of the select. See if substituting this value into an arm
1136 /// and simplifying the result yields the same value as the other arm.
1137 ///
1138 /// To make this transform safe, we must drop poison-generating flags
1139 /// (nsw, etc) if we simplified to a binop because the select may be guarding
1140 /// that poison from propagating. If the existing binop already had no
1141 /// poison-generating flags, then this transform can be done by instsimplify.
1142 ///
1143 /// Consider:
1144 ///   %cmp = icmp eq i32 %x, 2147483647
1145 ///   %add = add nsw i32 %x, 1
1146 ///   %sel = select i1 %cmp, i32 -2147483648, i32 %add
1147 ///
1148 /// We can't replace %sel with %add unless we strip away the flags.
1149 /// TODO: Wrapping flags could be preserved in some cases with better analysis.
1150 Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1151                                                           ICmpInst &Cmp) {
1152   if (!Cmp.isEquality())
1153     return nullptr;
1154 
1155   // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1156   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1157   bool Swapped = false;
1158   if (Cmp.getPredicate() == ICmpInst::ICMP_NE) {
1159     std::swap(TrueVal, FalseVal);
1160     Swapped = true;
1161   }
1162 
1163   // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
1164   // Make sure Y cannot be undef though, as we might pick different values for
1165   // undef in the icmp and in f(Y). Additionally, take care to avoid replacing
1166   // X == Y ? X : Z with X == Y ? Y : Z, as that would lead to an infinite
1167   // replacement cycle.
1168   Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1169   if (TrueVal != CmpLHS &&
1170       isGuaranteedNotToBeUndefOrPoison(CmpRHS, SQ.AC, &Sel, &DT))
1171     if (Value *V = SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, SQ,
1172                                           /* AllowRefinement */ true))
1173       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1174   if (TrueVal != CmpRHS &&
1175       isGuaranteedNotToBeUndefOrPoison(CmpLHS, SQ.AC, &Sel, &DT))
1176     if (Value *V = SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, SQ,
1177                                           /* AllowRefinement */ true))
1178       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1179 
1180   auto *FalseInst = dyn_cast<Instruction>(FalseVal);
1181   if (!FalseInst)
1182     return nullptr;
1183 
1184   // InstSimplify already performed this fold if it was possible subject to
1185   // current poison-generating flags. Try the transform again with
1186   // poison-generating flags temporarily dropped.
1187   bool WasNUW = false, WasNSW = false, WasExact = false, WasInBounds = false;
1188   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(FalseVal)) {
1189     WasNUW = OBO->hasNoUnsignedWrap();
1190     WasNSW = OBO->hasNoSignedWrap();
1191     FalseInst->setHasNoUnsignedWrap(false);
1192     FalseInst->setHasNoSignedWrap(false);
1193   }
1194   if (auto *PEO = dyn_cast<PossiblyExactOperator>(FalseVal)) {
1195     WasExact = PEO->isExact();
1196     FalseInst->setIsExact(false);
1197   }
1198   if (auto *GEP = dyn_cast<GetElementPtrInst>(FalseVal)) {
1199     WasInBounds = GEP->isInBounds();
1200     GEP->setIsInBounds(false);
1201   }
1202 
1203   // Try each equivalence substitution possibility.
1204   // We have an 'EQ' comparison, so the select's false value will propagate.
1205   // Example:
1206   // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1207   if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, SQ,
1208                              /* AllowRefinement */ false) == TrueVal ||
1209       SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, SQ,
1210                              /* AllowRefinement */ false) == TrueVal) {
1211     return replaceInstUsesWith(Sel, FalseVal);
1212   }
1213 
1214   // Restore poison-generating flags if the transform did not apply.
1215   if (WasNUW)
1216     FalseInst->setHasNoUnsignedWrap();
1217   if (WasNSW)
1218     FalseInst->setHasNoSignedWrap();
1219   if (WasExact)
1220     FalseInst->setIsExact();
1221   if (WasInBounds)
1222     cast<GetElementPtrInst>(FalseInst)->setIsInBounds();
1223 
1224   return nullptr;
1225 }
1226 
1227 // See if this is a pattern like:
1228 //   %old_cmp1 = icmp slt i32 %x, C2
1229 //   %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1230 //   %old_x_offseted = add i32 %x, C1
1231 //   %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1232 //   %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1233 // This can be rewritten as more canonical pattern:
1234 //   %new_cmp1 = icmp slt i32 %x, -C1
1235 //   %new_cmp2 = icmp sge i32 %x, C0-C1
1236 //   %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1237 //   %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1238 // Iff -C1 s<= C2 s<= C0-C1
1239 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1240 //      SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1241 static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1242                                           InstCombiner::BuilderTy &Builder) {
1243   Value *X = Sel0.getTrueValue();
1244   Value *Sel1 = Sel0.getFalseValue();
1245 
1246   // First match the condition of the outermost select.
1247   // Said condition must be one-use.
1248   if (!Cmp0.hasOneUse())
1249     return nullptr;
1250   Value *Cmp00 = Cmp0.getOperand(0);
1251   Constant *C0;
1252   if (!match(Cmp0.getOperand(1),
1253              m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1254     return nullptr;
1255   // Canonicalize Cmp0 into the form we expect.
1256   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1257   switch (Cmp0.getPredicate()) {
1258   case ICmpInst::Predicate::ICMP_ULT:
1259     break; // Great!
1260   case ICmpInst::Predicate::ICMP_ULE:
1261     // We'd have to increment C0 by one, and for that it must not have all-ones
1262     // element, but then it would have been canonicalized to 'ult' before
1263     // we get here. So we can't do anything useful with 'ule'.
1264     return nullptr;
1265   case ICmpInst::Predicate::ICMP_UGT:
1266     // We want to canonicalize it to 'ult', so we'll need to increment C0,
1267     // which again means it must not have any all-ones elements.
1268     if (!match(C0,
1269                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1270                                   APInt::getAllOnesValue(
1271                                       C0->getType()->getScalarSizeInBits()))))
1272       return nullptr; // Can't do, have all-ones element[s].
1273     C0 = InstCombiner::AddOne(C0);
1274     std::swap(X, Sel1);
1275     break;
1276   case ICmpInst::Predicate::ICMP_UGE:
1277     // The only way we'd get this predicate if this `icmp` has extra uses,
1278     // but then we won't be able to do this fold.
1279     return nullptr;
1280   default:
1281     return nullptr; // Unknown predicate.
1282   }
1283 
1284   // Now that we've canonicalized the ICmp, we know the X we expect;
1285   // the select in other hand should be one-use.
1286   if (!Sel1->hasOneUse())
1287     return nullptr;
1288 
1289   // We now can finish matching the condition of the outermost select:
1290   // it should either be the X itself, or an addition of some constant to X.
1291   Constant *C1;
1292   if (Cmp00 == X)
1293     C1 = ConstantInt::getNullValue(Sel0.getType());
1294   else if (!match(Cmp00,
1295                   m_Add(m_Specific(X),
1296                         m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1297     return nullptr;
1298 
1299   Value *Cmp1;
1300   ICmpInst::Predicate Pred1;
1301   Constant *C2;
1302   Value *ReplacementLow, *ReplacementHigh;
1303   if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1304                             m_Value(ReplacementHigh))) ||
1305       !match(Cmp1,
1306              m_ICmp(Pred1, m_Specific(X),
1307                     m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1308     return nullptr;
1309 
1310   if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1311     return nullptr; // Not enough one-use instructions for the fold.
1312   // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1313   //        two comparisons we'll need to build.
1314 
1315   // Canonicalize Cmp1 into the form we expect.
1316   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1317   switch (Pred1) {
1318   case ICmpInst::Predicate::ICMP_SLT:
1319     break;
1320   case ICmpInst::Predicate::ICMP_SLE:
1321     // We'd have to increment C2 by one, and for that it must not have signed
1322     // max element, but then it would have been canonicalized to 'slt' before
1323     // we get here. So we can't do anything useful with 'sle'.
1324     return nullptr;
1325   case ICmpInst::Predicate::ICMP_SGT:
1326     // We want to canonicalize it to 'slt', so we'll need to increment C2,
1327     // which again means it must not have any signed max elements.
1328     if (!match(C2,
1329                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1330                                   APInt::getSignedMaxValue(
1331                                       C2->getType()->getScalarSizeInBits()))))
1332       return nullptr; // Can't do, have signed max element[s].
1333     C2 = InstCombiner::AddOne(C2);
1334     LLVM_FALLTHROUGH;
1335   case ICmpInst::Predicate::ICMP_SGE:
1336     // Also non-canonical, but here we don't need to change C2,
1337     // so we don't have any restrictions on C2, so we can just handle it.
1338     std::swap(ReplacementLow, ReplacementHigh);
1339     break;
1340   default:
1341     return nullptr; // Unknown predicate.
1342   }
1343 
1344   // The thresholds of this clamp-like pattern.
1345   auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1346   auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1347 
1348   // The fold has a precondition 1: C2 s>= ThresholdLow
1349   auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1350                                          ThresholdLowIncl);
1351   if (!match(Precond1, m_One()))
1352     return nullptr;
1353   // The fold has a precondition 2: C2 s<= ThresholdHigh
1354   auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1355                                          ThresholdHighExcl);
1356   if (!match(Precond2, m_One()))
1357     return nullptr;
1358 
1359   // All good, finally emit the new pattern.
1360   Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1361   Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1362   Value *MaybeReplacedLow =
1363       Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1364   Instruction *MaybeReplacedHigh =
1365       SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1366 
1367   return MaybeReplacedHigh;
1368 }
1369 
1370 // If we have
1371 //  %cmp = icmp [canonical predicate] i32 %x, C0
1372 //  %r = select i1 %cmp, i32 %y, i32 C1
1373 // Where C0 != C1 and %x may be different from %y, see if the constant that we
1374 // will have if we flip the strictness of the predicate (i.e. without changing
1375 // the result) is identical to the C1 in select. If it matches we can change
1376 // original comparison to one with swapped predicate, reuse the constant,
1377 // and swap the hands of select.
1378 static Instruction *
1379 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1380                                          InstCombinerImpl &IC) {
1381   ICmpInst::Predicate Pred;
1382   Value *X;
1383   Constant *C0;
1384   if (!match(&Cmp, m_OneUse(m_ICmp(
1385                        Pred, m_Value(X),
1386                        m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1387     return nullptr;
1388 
1389   // If comparison predicate is non-relational, we won't be able to do anything.
1390   if (ICmpInst::isEquality(Pred))
1391     return nullptr;
1392 
1393   // If comparison predicate is non-canonical, then we certainly won't be able
1394   // to make it canonical; canonicalizeCmpWithConstant() already tried.
1395   if (!InstCombiner::isCanonicalPredicate(Pred))
1396     return nullptr;
1397 
1398   // If the [input] type of comparison and select type are different, lets abort
1399   // for now. We could try to compare constants with trunc/[zs]ext though.
1400   if (C0->getType() != Sel.getType())
1401     return nullptr;
1402 
1403   // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1404 
1405   Value *SelVal0, *SelVal1; // We do not care which one is from where.
1406   match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1407   // At least one of these values we are selecting between must be a constant
1408   // else we'll never succeed.
1409   if (!match(SelVal0, m_AnyIntegralConstant()) &&
1410       !match(SelVal1, m_AnyIntegralConstant()))
1411     return nullptr;
1412 
1413   // Does this constant C match any of the `select` values?
1414   auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1415     return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1416   };
1417 
1418   // If C0 *already* matches true/false value of select, we are done.
1419   if (MatchesSelectValue(C0))
1420     return nullptr;
1421 
1422   // Check the constant we'd have with flipped-strictness predicate.
1423   auto FlippedStrictness =
1424       InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, C0);
1425   if (!FlippedStrictness)
1426     return nullptr;
1427 
1428   // If said constant doesn't match either, then there is no hope,
1429   if (!MatchesSelectValue(FlippedStrictness->second))
1430     return nullptr;
1431 
1432   // It matched! Lets insert the new comparison just before select.
1433   InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1434   IC.Builder.SetInsertPoint(&Sel);
1435 
1436   Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1437   Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1438                                         Cmp.getName() + ".inv");
1439   IC.replaceOperand(Sel, 0, NewCmp);
1440   Sel.swapValues();
1441   Sel.swapProfMetadata();
1442 
1443   return &Sel;
1444 }
1445 
1446 /// Visit a SelectInst that has an ICmpInst as its first operand.
1447 Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI,
1448                                                       ICmpInst *ICI) {
1449   if (Instruction *NewSel = foldSelectValueEquivalence(SI, *ICI))
1450     return NewSel;
1451 
1452   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this))
1453     return NewSel;
1454 
1455   if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, *this))
1456     return NewAbs;
1457 
1458   if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
1459     return NewAbs;
1460 
1461   if (Instruction *NewSel =
1462           tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1463     return NewSel;
1464 
1465   bool Changed = adjustMinMax(SI, *ICI);
1466 
1467   if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1468     return replaceInstUsesWith(SI, V);
1469 
1470   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1471   Value *TrueVal = SI.getTrueValue();
1472   Value *FalseVal = SI.getFalseValue();
1473   ICmpInst::Predicate Pred = ICI->getPredicate();
1474   Value *CmpLHS = ICI->getOperand(0);
1475   Value *CmpRHS = ICI->getOperand(1);
1476   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1477     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1478       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1479       SI.setOperand(1, CmpRHS);
1480       Changed = true;
1481     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1482       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1483       SI.setOperand(2, CmpRHS);
1484       Changed = true;
1485     }
1486   }
1487 
1488   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1489   // decomposeBitTestICmp() might help.
1490   {
1491     unsigned BitWidth =
1492         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1493     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1494     Value *X;
1495     const APInt *Y, *C;
1496     bool TrueWhenUnset;
1497     bool IsBitTest = false;
1498     if (ICmpInst::isEquality(Pred) &&
1499         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1500         match(CmpRHS, m_Zero())) {
1501       IsBitTest = true;
1502       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1503     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1504       X = CmpLHS;
1505       Y = &MinSignedValue;
1506       IsBitTest = true;
1507       TrueWhenUnset = false;
1508     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1509       X = CmpLHS;
1510       Y = &MinSignedValue;
1511       IsBitTest = true;
1512       TrueWhenUnset = true;
1513     }
1514     if (IsBitTest) {
1515       Value *V = nullptr;
1516       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
1517       if (TrueWhenUnset && TrueVal == X &&
1518           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1519         V = Builder.CreateAnd(X, ~(*Y));
1520       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
1521       else if (!TrueWhenUnset && FalseVal == X &&
1522                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1523         V = Builder.CreateAnd(X, ~(*Y));
1524       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
1525       else if (TrueWhenUnset && FalseVal == X &&
1526                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1527         V = Builder.CreateOr(X, *Y);
1528       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
1529       else if (!TrueWhenUnset && TrueVal == X &&
1530                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1531         V = Builder.CreateOr(X, *Y);
1532 
1533       if (V)
1534         return replaceInstUsesWith(SI, V);
1535     }
1536   }
1537 
1538   if (Instruction *V =
1539           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1540     return V;
1541 
1542   if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1543     return V;
1544 
1545   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1546     return replaceInstUsesWith(SI, V);
1547 
1548   if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1549     return replaceInstUsesWith(SI, V);
1550 
1551   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1552     return replaceInstUsesWith(SI, V);
1553 
1554   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1555     return replaceInstUsesWith(SI, V);
1556 
1557   if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1558     return replaceInstUsesWith(SI, V);
1559 
1560   return Changed ? &SI : nullptr;
1561 }
1562 
1563 /// SI is a select whose condition is a PHI node (but the two may be in
1564 /// different blocks). See if the true/false values (V) are live in all of the
1565 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1566 ///
1567 ///   X = phi [ C1, BB1], [C2, BB2]
1568 ///   Y = add
1569 ///   Z = select X, Y, 0
1570 ///
1571 /// because Y is not live in BB1/BB2.
1572 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1573                                                    const SelectInst &SI) {
1574   // If the value is a non-instruction value like a constant or argument, it
1575   // can always be mapped.
1576   const Instruction *I = dyn_cast<Instruction>(V);
1577   if (!I) return true;
1578 
1579   // If V is a PHI node defined in the same block as the condition PHI, we can
1580   // map the arguments.
1581   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1582 
1583   if (const PHINode *VP = dyn_cast<PHINode>(I))
1584     if (VP->getParent() == CondPHI->getParent())
1585       return true;
1586 
1587   // Otherwise, if the PHI and select are defined in the same block and if V is
1588   // defined in a different block, then we can transform it.
1589   if (SI.getParent() == CondPHI->getParent() &&
1590       I->getParent() != CondPHI->getParent())
1591     return true;
1592 
1593   // Otherwise we have a 'hard' case and we can't tell without doing more
1594   // detailed dominator based analysis, punt.
1595   return false;
1596 }
1597 
1598 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1599 ///   SPF2(SPF1(A, B), C)
1600 Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner,
1601                                             SelectPatternFlavor SPF1, Value *A,
1602                                             Value *B, Instruction &Outer,
1603                                             SelectPatternFlavor SPF2,
1604                                             Value *C) {
1605   if (Outer.getType() != Inner->getType())
1606     return nullptr;
1607 
1608   if (C == A || C == B) {
1609     // MAX(MAX(A, B), B) -> MAX(A, B)
1610     // MIN(MIN(a, b), a) -> MIN(a, b)
1611     // TODO: This could be done in instsimplify.
1612     if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1613       return replaceInstUsesWith(Outer, Inner);
1614 
1615     // MAX(MIN(a, b), a) -> a
1616     // MIN(MAX(a, b), a) -> a
1617     // TODO: This could be done in instsimplify.
1618     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1619         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1620         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1621         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1622       return replaceInstUsesWith(Outer, C);
1623   }
1624 
1625   if (SPF1 == SPF2) {
1626     const APInt *CB, *CC;
1627     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1628       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1629       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1630       // TODO: This could be done in instsimplify.
1631       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1632           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1633           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1634           (SPF1 == SPF_SMAX && CB->sge(*CC)))
1635         return replaceInstUsesWith(Outer, Inner);
1636 
1637       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1638       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1639       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1640           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1641           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1642           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1643         Outer.replaceUsesOfWith(Inner, A);
1644         return &Outer;
1645       }
1646     }
1647   }
1648 
1649   // max(max(A, B), min(A, B)) --> max(A, B)
1650   // min(min(A, B), max(A, B)) --> min(A, B)
1651   // TODO: This could be done in instsimplify.
1652   if (SPF1 == SPF2 &&
1653       ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1654        (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1655        (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1656        (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1657     return replaceInstUsesWith(Outer, Inner);
1658 
1659   // ABS(ABS(X)) -> ABS(X)
1660   // NABS(NABS(X)) -> NABS(X)
1661   // TODO: This could be done in instsimplify.
1662   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1663     return replaceInstUsesWith(Outer, Inner);
1664   }
1665 
1666   // ABS(NABS(X)) -> ABS(X)
1667   // NABS(ABS(X)) -> NABS(X)
1668   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1669       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1670     SelectInst *SI = cast<SelectInst>(Inner);
1671     Value *NewSI =
1672         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1673                              SI->getTrueValue(), SI->getName(), SI);
1674     return replaceInstUsesWith(Outer, NewSI);
1675   }
1676 
1677   auto IsFreeOrProfitableToInvert =
1678       [&](Value *V, Value *&NotV, bool &ElidesXor) {
1679     if (match(V, m_Not(m_Value(NotV)))) {
1680       // If V has at most 2 uses then we can get rid of the xor operation
1681       // entirely.
1682       ElidesXor |= !V->hasNUsesOrMore(3);
1683       return true;
1684     }
1685 
1686     if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1687       NotV = nullptr;
1688       return true;
1689     }
1690 
1691     return false;
1692   };
1693 
1694   Value *NotA, *NotB, *NotC;
1695   bool ElidesXor = false;
1696 
1697   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1698   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1699   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1700   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1701   //
1702   // This transform is performance neutral if we can elide at least one xor from
1703   // the set of three operands, since we'll be tacking on an xor at the very
1704   // end.
1705   if (SelectPatternResult::isMinOrMax(SPF1) &&
1706       SelectPatternResult::isMinOrMax(SPF2) &&
1707       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1708       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1709       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1710     if (!NotA)
1711       NotA = Builder.CreateNot(A);
1712     if (!NotB)
1713       NotB = Builder.CreateNot(B);
1714     if (!NotC)
1715       NotC = Builder.CreateNot(C);
1716 
1717     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1718                                    NotB);
1719     Value *NewOuter = Builder.CreateNot(
1720         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1721     return replaceInstUsesWith(Outer, NewOuter);
1722   }
1723 
1724   return nullptr;
1725 }
1726 
1727 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1728 /// This is even legal for FP.
1729 static Instruction *foldAddSubSelect(SelectInst &SI,
1730                                      InstCombiner::BuilderTy &Builder) {
1731   Value *CondVal = SI.getCondition();
1732   Value *TrueVal = SI.getTrueValue();
1733   Value *FalseVal = SI.getFalseValue();
1734   auto *TI = dyn_cast<Instruction>(TrueVal);
1735   auto *FI = dyn_cast<Instruction>(FalseVal);
1736   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1737     return nullptr;
1738 
1739   Instruction *AddOp = nullptr, *SubOp = nullptr;
1740   if ((TI->getOpcode() == Instruction::Sub &&
1741        FI->getOpcode() == Instruction::Add) ||
1742       (TI->getOpcode() == Instruction::FSub &&
1743        FI->getOpcode() == Instruction::FAdd)) {
1744     AddOp = FI;
1745     SubOp = TI;
1746   } else if ((FI->getOpcode() == Instruction::Sub &&
1747               TI->getOpcode() == Instruction::Add) ||
1748              (FI->getOpcode() == Instruction::FSub &&
1749               TI->getOpcode() == Instruction::FAdd)) {
1750     AddOp = TI;
1751     SubOp = FI;
1752   }
1753 
1754   if (AddOp) {
1755     Value *OtherAddOp = nullptr;
1756     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1757       OtherAddOp = AddOp->getOperand(1);
1758     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1759       OtherAddOp = AddOp->getOperand(0);
1760     }
1761 
1762     if (OtherAddOp) {
1763       // So at this point we know we have (Y -> OtherAddOp):
1764       //        select C, (add X, Y), (sub X, Z)
1765       Value *NegVal; // Compute -Z
1766       if (SI.getType()->isFPOrFPVectorTy()) {
1767         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1768         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1769           FastMathFlags Flags = AddOp->getFastMathFlags();
1770           Flags &= SubOp->getFastMathFlags();
1771           NegInst->setFastMathFlags(Flags);
1772         }
1773       } else {
1774         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1775       }
1776 
1777       Value *NewTrueOp = OtherAddOp;
1778       Value *NewFalseOp = NegVal;
1779       if (AddOp != TI)
1780         std::swap(NewTrueOp, NewFalseOp);
1781       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1782                                            SI.getName() + ".p", &SI);
1783 
1784       if (SI.getType()->isFPOrFPVectorTy()) {
1785         Instruction *RI =
1786             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1787 
1788         FastMathFlags Flags = AddOp->getFastMathFlags();
1789         Flags &= SubOp->getFastMathFlags();
1790         RI->setFastMathFlags(Flags);
1791         return RI;
1792       } else
1793         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1794     }
1795   }
1796   return nullptr;
1797 }
1798 
1799 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1800 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1801 /// Along with a number of patterns similar to:
1802 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1803 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1804 static Instruction *
1805 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1806   Value *CondVal = SI.getCondition();
1807   Value *TrueVal = SI.getTrueValue();
1808   Value *FalseVal = SI.getFalseValue();
1809 
1810   WithOverflowInst *II;
1811   if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1812       !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1813     return nullptr;
1814 
1815   Value *X = II->getLHS();
1816   Value *Y = II->getRHS();
1817 
1818   auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1819     Type *Ty = Limit->getType();
1820 
1821     ICmpInst::Predicate Pred;
1822     Value *TrueVal, *FalseVal, *Op;
1823     const APInt *C;
1824     if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1825                                m_Value(TrueVal), m_Value(FalseVal))))
1826       return false;
1827 
1828     auto IsZeroOrOne = [](const APInt &C) {
1829       return C.isNullValue() || C.isOneValue();
1830     };
1831     auto IsMinMax = [&](Value *Min, Value *Max) {
1832       APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1833       APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1834       return match(Min, m_SpecificInt(MinVal)) &&
1835              match(Max, m_SpecificInt(MaxVal));
1836     };
1837 
1838     if (Op != X && Op != Y)
1839       return false;
1840 
1841     if (IsAdd) {
1842       // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1843       // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1844       // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1845       // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1846       if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1847           IsMinMax(TrueVal, FalseVal))
1848         return true;
1849       // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1850       // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1851       // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1852       // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1853       if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1854           IsMinMax(FalseVal, TrueVal))
1855         return true;
1856     } else {
1857       // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1858       // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1859       if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
1860           IsMinMax(TrueVal, FalseVal))
1861         return true;
1862       // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1863       // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1864       if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
1865           IsMinMax(FalseVal, TrueVal))
1866         return true;
1867       // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1868       // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1869       if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1870           IsMinMax(FalseVal, TrueVal))
1871         return true;
1872       // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1873       // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1874       if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1875           IsMinMax(TrueVal, FalseVal))
1876         return true;
1877     }
1878 
1879     return false;
1880   };
1881 
1882   Intrinsic::ID NewIntrinsicID;
1883   if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1884       match(TrueVal, m_AllOnes()))
1885     // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1886     NewIntrinsicID = Intrinsic::uadd_sat;
1887   else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1888            match(TrueVal, m_Zero()))
1889     // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1890     NewIntrinsicID = Intrinsic::usub_sat;
1891   else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
1892            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
1893     // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1894     // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1895     // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1896     // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1897     // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1898     // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1899     // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1900     // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1901     NewIntrinsicID = Intrinsic::sadd_sat;
1902   else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
1903            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
1904     // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1905     // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1906     // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1907     // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1908     // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1909     // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1910     // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1911     // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1912     NewIntrinsicID = Intrinsic::ssub_sat;
1913   else
1914     return nullptr;
1915 
1916   Function *F =
1917       Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1918   return CallInst::Create(F, {X, Y});
1919 }
1920 
1921 Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) {
1922   Constant *C;
1923   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1924       !match(Sel.getFalseValue(), m_Constant(C)))
1925     return nullptr;
1926 
1927   Instruction *ExtInst;
1928   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1929       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1930     return nullptr;
1931 
1932   auto ExtOpcode = ExtInst->getOpcode();
1933   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1934     return nullptr;
1935 
1936   // If we are extending from a boolean type or if we can create a select that
1937   // has the same size operands as its condition, try to narrow the select.
1938   Value *X = ExtInst->getOperand(0);
1939   Type *SmallType = X->getType();
1940   Value *Cond = Sel.getCondition();
1941   auto *Cmp = dyn_cast<CmpInst>(Cond);
1942   if (!SmallType->isIntOrIntVectorTy(1) &&
1943       (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1944     return nullptr;
1945 
1946   // If the constant is the same after truncation to the smaller type and
1947   // extension to the original type, we can narrow the select.
1948   Type *SelType = Sel.getType();
1949   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1950   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1951   if (ExtC == C && ExtInst->hasOneUse()) {
1952     Value *TruncCVal = cast<Value>(TruncC);
1953     if (ExtInst == Sel.getFalseValue())
1954       std::swap(X, TruncCVal);
1955 
1956     // select Cond, (ext X), C --> ext(select Cond, X, C')
1957     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1958     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1959     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1960   }
1961 
1962   // If one arm of the select is the extend of the condition, replace that arm
1963   // with the extension of the appropriate known bool value.
1964   if (Cond == X) {
1965     if (ExtInst == Sel.getTrueValue()) {
1966       // select X, (sext X), C --> select X, -1, C
1967       // select X, (zext X), C --> select X,  1, C
1968       Constant *One = ConstantInt::getTrue(SmallType);
1969       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1970       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1971     } else {
1972       // select X, C, (sext X) --> select X, C, 0
1973       // select X, C, (zext X) --> select X, C, 0
1974       Constant *Zero = ConstantInt::getNullValue(SelType);
1975       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1976     }
1977   }
1978 
1979   return nullptr;
1980 }
1981 
1982 /// Try to transform a vector select with a constant condition vector into a
1983 /// shuffle for easier combining with other shuffles and insert/extract.
1984 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1985   Value *CondVal = SI.getCondition();
1986   Constant *CondC;
1987   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1988     return nullptr;
1989 
1990   unsigned NumElts =
1991       cast<FixedVectorType>(CondVal->getType())->getNumElements();
1992   SmallVector<int, 16> Mask;
1993   Mask.reserve(NumElts);
1994   for (unsigned i = 0; i != NumElts; ++i) {
1995     Constant *Elt = CondC->getAggregateElement(i);
1996     if (!Elt)
1997       return nullptr;
1998 
1999     if (Elt->isOneValue()) {
2000       // If the select condition element is true, choose from the 1st vector.
2001       Mask.push_back(i);
2002     } else if (Elt->isNullValue()) {
2003       // If the select condition element is false, choose from the 2nd vector.
2004       Mask.push_back(i + NumElts);
2005     } else if (isa<UndefValue>(Elt)) {
2006       // Undef in a select condition (choose one of the operands) does not mean
2007       // the same thing as undef in a shuffle mask (any value is acceptable), so
2008       // give up.
2009       return nullptr;
2010     } else {
2011       // Bail out on a constant expression.
2012       return nullptr;
2013     }
2014   }
2015 
2016   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2017 }
2018 
2019 /// If we have a select of vectors with a scalar condition, try to convert that
2020 /// to a vector select by splatting the condition. A splat may get folded with
2021 /// other operations in IR and having all operands of a select be vector types
2022 /// is likely better for vector codegen.
2023 static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
2024                                                    InstCombinerImpl &IC) {
2025   auto *Ty = dyn_cast<VectorType>(Sel.getType());
2026   if (!Ty)
2027     return nullptr;
2028 
2029   // We can replace a single-use extract with constant index.
2030   Value *Cond = Sel.getCondition();
2031   if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
2032     return nullptr;
2033 
2034   // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2035   // Splatting the extracted condition reduces code (we could directly create a
2036   // splat shuffle of the source vector to eliminate the intermediate step).
2037   return IC.replaceOperand(
2038       Sel, 0, IC.Builder.CreateVectorSplat(Ty->getElementCount(), Cond));
2039 }
2040 
2041 /// Reuse bitcasted operands between a compare and select:
2042 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2043 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2044 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2045                                           InstCombiner::BuilderTy &Builder) {
2046   Value *Cond = Sel.getCondition();
2047   Value *TVal = Sel.getTrueValue();
2048   Value *FVal = Sel.getFalseValue();
2049 
2050   CmpInst::Predicate Pred;
2051   Value *A, *B;
2052   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2053     return nullptr;
2054 
2055   // The select condition is a compare instruction. If the select's true/false
2056   // values are already the same as the compare operands, there's nothing to do.
2057   if (TVal == A || TVal == B || FVal == A || FVal == B)
2058     return nullptr;
2059 
2060   Value *C, *D;
2061   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2062     return nullptr;
2063 
2064   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2065   Value *TSrc, *FSrc;
2066   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2067       !match(FVal, m_BitCast(m_Value(FSrc))))
2068     return nullptr;
2069 
2070   // If the select true/false values are *different bitcasts* of the same source
2071   // operands, make the select operands the same as the compare operands and
2072   // cast the result. This is the canonical select form for min/max.
2073   Value *NewSel;
2074   if (TSrc == C && FSrc == D) {
2075     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2076     // bitcast (select (cmp A, B), A, B)
2077     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2078   } else if (TSrc == D && FSrc == C) {
2079     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2080     // bitcast (select (cmp A, B), B, A)
2081     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2082   } else {
2083     return nullptr;
2084   }
2085   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2086 }
2087 
2088 /// Try to eliminate select instructions that test the returned flag of cmpxchg
2089 /// instructions.
2090 ///
2091 /// If a select instruction tests the returned flag of a cmpxchg instruction and
2092 /// selects between the returned value of the cmpxchg instruction its compare
2093 /// operand, the result of the select will always be equal to its false value.
2094 /// For example:
2095 ///
2096 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2097 ///   %1 = extractvalue { i64, i1 } %0, 1
2098 ///   %2 = extractvalue { i64, i1 } %0, 0
2099 ///   %3 = select i1 %1, i64 %compare, i64 %2
2100 ///   ret i64 %3
2101 ///
2102 /// The returned value of the cmpxchg instruction (%2) is the original value
2103 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2104 /// must have been equal to %compare. Thus, the result of the select is always
2105 /// equal to %2, and the code can be simplified to:
2106 ///
2107 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2108 ///   %1 = extractvalue { i64, i1 } %0, 0
2109 ///   ret i64 %1
2110 ///
2111 static Value *foldSelectCmpXchg(SelectInst &SI) {
2112   // A helper that determines if V is an extractvalue instruction whose
2113   // aggregate operand is a cmpxchg instruction and whose single index is equal
2114   // to I. If such conditions are true, the helper returns the cmpxchg
2115   // instruction; otherwise, a nullptr is returned.
2116   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2117     auto *Extract = dyn_cast<ExtractValueInst>(V);
2118     if (!Extract)
2119       return nullptr;
2120     if (Extract->getIndices()[0] != I)
2121       return nullptr;
2122     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2123   };
2124 
2125   // If the select has a single user, and this user is a select instruction that
2126   // we can simplify, skip the cmpxchg simplification for now.
2127   if (SI.hasOneUse())
2128     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2129       if (Select->getCondition() == SI.getCondition())
2130         if (Select->getFalseValue() == SI.getTrueValue() ||
2131             Select->getTrueValue() == SI.getFalseValue())
2132           return nullptr;
2133 
2134   // Ensure the select condition is the returned flag of a cmpxchg instruction.
2135   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2136   if (!CmpXchg)
2137     return nullptr;
2138 
2139   // Check the true value case: The true value of the select is the returned
2140   // value of the same cmpxchg used by the condition, and the false value is the
2141   // cmpxchg instruction's compare operand.
2142   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2143     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2144       return SI.getFalseValue();
2145 
2146   // Check the false value case: The false value of the select is the returned
2147   // value of the same cmpxchg used by the condition, and the true value is the
2148   // cmpxchg instruction's compare operand.
2149   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2150     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2151       return SI.getFalseValue();
2152 
2153   return nullptr;
2154 }
2155 
2156 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2157                                        Value *Y,
2158                                        InstCombiner::BuilderTy &Builder) {
2159   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
2160   bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2161                     SPF == SelectPatternFlavor::SPF_UMAX;
2162   // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2163   // the constant value check to an assert.
2164   Value *A;
2165   const APInt *C1, *C2;
2166   if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2167       match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2168     // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2169     // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2170     Value *NewMinMax = createMinMax(Builder, SPF, A,
2171                                     ConstantInt::get(X->getType(), *C2 - *C1));
2172     return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2173                                      ConstantInt::get(X->getType(), *C1));
2174   }
2175 
2176   if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2177       match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2178     bool Overflow;
2179     APInt Diff = C2->ssub_ov(*C1, Overflow);
2180     if (!Overflow) {
2181       // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2182       // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2183       Value *NewMinMax = createMinMax(Builder, SPF, A,
2184                                       ConstantInt::get(X->getType(), Diff));
2185       return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2186                                        ConstantInt::get(X->getType(), *C1));
2187     }
2188   }
2189 
2190   return nullptr;
2191 }
2192 
2193 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
2194 Instruction *InstCombinerImpl::matchSAddSubSat(SelectInst &MinMax1) {
2195   Type *Ty = MinMax1.getType();
2196 
2197   // We are looking for a tree of:
2198   // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2199   // Where the min and max could be reversed
2200   Instruction *MinMax2;
2201   BinaryOperator *AddSub;
2202   const APInt *MinValue, *MaxValue;
2203   if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2204     if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2205       return nullptr;
2206   } else if (match(&MinMax1,
2207                    m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2208     if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2209       return nullptr;
2210   } else
2211     return nullptr;
2212 
2213   // Check that the constants clamp a saturate, and that the new type would be
2214   // sensible to convert to.
2215   if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2216     return nullptr;
2217   // In what bitwidth can this be treated as saturating arithmetics?
2218   unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2219   // FIXME: This isn't quite right for vectors, but using the scalar type is a
2220   // good first approximation for what should be done there.
2221   if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2222     return nullptr;
2223 
2224   // Also make sure that the number of uses is as expected. The "3"s are for the
2225   // the two items of min/max (the compare and the select).
2226   if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3))
2227     return nullptr;
2228 
2229   // Create the new type (which can be a vector type)
2230   Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2231   // Match the two extends from the add/sub
2232   Value *A, *B;
2233   if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B)))))
2234     return nullptr;
2235   // And check the incoming values are of a type smaller than or equal to the
2236   // size of the saturation. Otherwise the higher bits can cause different
2237   // results.
2238   if (A->getType()->getScalarSizeInBits() > NewBitWidth ||
2239       B->getType()->getScalarSizeInBits() > NewBitWidth)
2240     return nullptr;
2241 
2242   Intrinsic::ID IntrinsicID;
2243   if (AddSub->getOpcode() == Instruction::Add)
2244     IntrinsicID = Intrinsic::sadd_sat;
2245   else if (AddSub->getOpcode() == Instruction::Sub)
2246     IntrinsicID = Intrinsic::ssub_sat;
2247   else
2248     return nullptr;
2249 
2250   // Finally create and return the sat intrinsic, truncated to the new type
2251   Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2252   Value *AT = Builder.CreateSExt(A, NewTy);
2253   Value *BT = Builder.CreateSExt(B, NewTy);
2254   Value *Sat = Builder.CreateCall(F, {AT, BT});
2255   return CastInst::Create(Instruction::SExt, Sat, Ty);
2256 }
2257 
2258 /// Reduce a sequence of min/max with a common operand.
2259 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2260                                         Value *RHS,
2261                                         InstCombiner::BuilderTy &Builder) {
2262   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
2263   // TODO: Allow FP min/max with nnan/nsz.
2264   if (!LHS->getType()->isIntOrIntVectorTy())
2265     return nullptr;
2266 
2267   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2268   Value *A, *B, *C, *D;
2269   SelectPatternResult L = matchSelectPattern(LHS, A, B);
2270   SelectPatternResult R = matchSelectPattern(RHS, C, D);
2271   if (SPF != L.Flavor || L.Flavor != R.Flavor)
2272     return nullptr;
2273 
2274   // Look for a common operand. The use checks are different than usual because
2275   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2276   // the select.
2277   Value *MinMaxOp = nullptr;
2278   Value *ThirdOp = nullptr;
2279   if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2280     // If the LHS is only used in this chain and the RHS is used outside of it,
2281     // reuse the RHS min/max because that will eliminate the LHS.
2282     if (D == A || C == A) {
2283       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2284       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2285       MinMaxOp = RHS;
2286       ThirdOp = B;
2287     } else if (D == B || C == B) {
2288       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2289       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2290       MinMaxOp = RHS;
2291       ThirdOp = A;
2292     }
2293   } else if (!RHS->hasNUsesOrMore(3)) {
2294     // Reuse the LHS. This will eliminate the RHS.
2295     if (D == A || D == B) {
2296       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2297       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2298       MinMaxOp = LHS;
2299       ThirdOp = C;
2300     } else if (C == A || C == B) {
2301       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2302       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2303       MinMaxOp = LHS;
2304       ThirdOp = D;
2305     }
2306   }
2307   if (!MinMaxOp || !ThirdOp)
2308     return nullptr;
2309 
2310   CmpInst::Predicate P = getMinMaxPred(SPF);
2311   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2312   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2313 }
2314 
2315 /// Try to reduce a funnel/rotate pattern that includes a compare and select
2316 /// into a funnel shift intrinsic. Example:
2317 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2318 ///              --> call llvm.fshl.i32(a, a, b)
2319 /// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c)))
2320 ///                 --> call llvm.fshl.i32(a, b, c)
2321 /// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c)))
2322 ///                 --> call llvm.fshr.i32(a, b, c)
2323 static Instruction *foldSelectFunnelShift(SelectInst &Sel,
2324                                           InstCombiner::BuilderTy &Builder) {
2325   // This must be a power-of-2 type for a bitmasking transform to be valid.
2326   unsigned Width = Sel.getType()->getScalarSizeInBits();
2327   if (!isPowerOf2_32(Width))
2328     return nullptr;
2329 
2330   BinaryOperator *Or0, *Or1;
2331   if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
2332     return nullptr;
2333 
2334   Value *SV0, *SV1, *SA0, *SA1;
2335   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(SV0),
2336                                           m_ZExtOrSelf(m_Value(SA0))))) ||
2337       !match(Or1, m_OneUse(m_LogicalShift(m_Value(SV1),
2338                                           m_ZExtOrSelf(m_Value(SA1))))) ||
2339       Or0->getOpcode() == Or1->getOpcode())
2340     return nullptr;
2341 
2342   // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)).
2343   if (Or0->getOpcode() == BinaryOperator::LShr) {
2344     std::swap(Or0, Or1);
2345     std::swap(SV0, SV1);
2346     std::swap(SA0, SA1);
2347   }
2348   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2349          Or1->getOpcode() == BinaryOperator::LShr &&
2350          "Illegal or(shift,shift) pair");
2351 
2352   // Check the shift amounts to see if they are an opposite pair.
2353   Value *ShAmt;
2354   if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2355     ShAmt = SA0;
2356   else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2357     ShAmt = SA1;
2358   else
2359     return nullptr;
2360 
2361   // We should now have this pattern:
2362   // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1))
2363   // The false value of the select must be a funnel-shift of the true value:
2364   // IsFShl -> TVal must be SV0 else TVal must be SV1.
2365   bool IsFshl = (ShAmt == SA0);
2366   Value *TVal = Sel.getTrueValue();
2367   if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1))
2368     return nullptr;
2369 
2370   // Finally, see if the select is filtering out a shift-by-zero.
2371   Value *Cond = Sel.getCondition();
2372   ICmpInst::Predicate Pred;
2373   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2374       Pred != ICmpInst::ICMP_EQ)
2375     return nullptr;
2376 
2377   // If this is not a rotate then the select was blocking poison from the
2378   // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
2379   if (SV0 != SV1) {
2380     if (IsFshl && !llvm::isGuaranteedNotToBePoison(SV1))
2381       SV1 = Builder.CreateFreeze(SV1);
2382     else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(SV0))
2383       SV0 = Builder.CreateFreeze(SV0);
2384   }
2385 
2386   // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2387   // Convert to funnel shift intrinsic.
2388   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2389   Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2390   ShAmt = Builder.CreateZExt(ShAmt, Sel.getType());
2391   return IntrinsicInst::Create(F, { SV0, SV1, ShAmt });
2392 }
2393 
2394 static Instruction *foldSelectToCopysign(SelectInst &Sel,
2395                                          InstCombiner::BuilderTy &Builder) {
2396   Value *Cond = Sel.getCondition();
2397   Value *TVal = Sel.getTrueValue();
2398   Value *FVal = Sel.getFalseValue();
2399   Type *SelType = Sel.getType();
2400 
2401   // Match select ?, TC, FC where the constants are equal but negated.
2402   // TODO: Generalize to handle a negated variable operand?
2403   const APFloat *TC, *FC;
2404   if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) ||
2405       !abs(*TC).bitwiseIsEqual(abs(*FC)))
2406     return nullptr;
2407 
2408   assert(TC != FC && "Expected equal select arms to simplify");
2409 
2410   Value *X;
2411   const APInt *C;
2412   bool IsTrueIfSignSet;
2413   ICmpInst::Predicate Pred;
2414   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
2415       !InstCombiner::isSignBitCheck(Pred, *C, IsTrueIfSignSet) ||
2416       X->getType() != SelType)
2417     return nullptr;
2418 
2419   // If needed, negate the value that will be the sign argument of the copysign:
2420   // (bitcast X) <  0 ? -TC :  TC --> copysign(TC,  X)
2421   // (bitcast X) <  0 ?  TC : -TC --> copysign(TC, -X)
2422   // (bitcast X) >= 0 ? -TC :  TC --> copysign(TC, -X)
2423   // (bitcast X) >= 0 ?  TC : -TC --> copysign(TC,  X)
2424   if (IsTrueIfSignSet ^ TC->isNegative())
2425     X = Builder.CreateFNegFMF(X, &Sel);
2426 
2427   // Canonicalize the magnitude argument as the positive constant since we do
2428   // not care about its sign.
2429   Value *MagArg = TC->isNegative() ? FVal : TVal;
2430   Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
2431                                           Sel.getType());
2432   Instruction *CopySign = IntrinsicInst::Create(F, { MagArg, X });
2433   CopySign->setFastMathFlags(Sel.getFastMathFlags());
2434   return CopySign;
2435 }
2436 
2437 Instruction *InstCombinerImpl::foldVectorSelect(SelectInst &Sel) {
2438   auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
2439   if (!VecTy)
2440     return nullptr;
2441 
2442   unsigned NumElts = VecTy->getNumElements();
2443   APInt UndefElts(NumElts, 0);
2444   APInt AllOnesEltMask(APInt::getAllOnesValue(NumElts));
2445   if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) {
2446     if (V != &Sel)
2447       return replaceInstUsesWith(Sel, V);
2448     return &Sel;
2449   }
2450 
2451   // A select of a "select shuffle" with a common operand can be rearranged
2452   // to select followed by "select shuffle". Because of poison, this only works
2453   // in the case of a shuffle with no undefined mask elements.
2454   Value *Cond = Sel.getCondition();
2455   Value *TVal = Sel.getTrueValue();
2456   Value *FVal = Sel.getFalseValue();
2457   Value *X, *Y;
2458   ArrayRef<int> Mask;
2459   if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2460       !is_contained(Mask, UndefMaskElem) &&
2461       cast<ShuffleVectorInst>(TVal)->isSelect()) {
2462     if (X == FVal) {
2463       // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
2464       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2465       return new ShuffleVectorInst(X, NewSel, Mask);
2466     }
2467     if (Y == FVal) {
2468       // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
2469       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2470       return new ShuffleVectorInst(NewSel, Y, Mask);
2471     }
2472   }
2473   if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2474       !is_contained(Mask, UndefMaskElem) &&
2475       cast<ShuffleVectorInst>(FVal)->isSelect()) {
2476     if (X == TVal) {
2477       // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
2478       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2479       return new ShuffleVectorInst(X, NewSel, Mask);
2480     }
2481     if (Y == TVal) {
2482       // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
2483       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2484       return new ShuffleVectorInst(NewSel, Y, Mask);
2485     }
2486   }
2487 
2488   return nullptr;
2489 }
2490 
2491 static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
2492                                         const DominatorTree &DT,
2493                                         InstCombiner::BuilderTy &Builder) {
2494   // Find the block's immediate dominator that ends with a conditional branch
2495   // that matches select's condition (maybe inverted).
2496   auto *IDomNode = DT[BB]->getIDom();
2497   if (!IDomNode)
2498     return nullptr;
2499   BasicBlock *IDom = IDomNode->getBlock();
2500 
2501   Value *Cond = Sel.getCondition();
2502   Value *IfTrue, *IfFalse;
2503   BasicBlock *TrueSucc, *FalseSucc;
2504   if (match(IDom->getTerminator(),
2505             m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
2506                  m_BasicBlock(FalseSucc)))) {
2507     IfTrue = Sel.getTrueValue();
2508     IfFalse = Sel.getFalseValue();
2509   } else if (match(IDom->getTerminator(),
2510                    m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
2511                         m_BasicBlock(FalseSucc)))) {
2512     IfTrue = Sel.getFalseValue();
2513     IfFalse = Sel.getTrueValue();
2514   } else
2515     return nullptr;
2516 
2517   // Make sure the branches are actually different.
2518   if (TrueSucc == FalseSucc)
2519     return nullptr;
2520 
2521   // We want to replace select %cond, %a, %b with a phi that takes value %a
2522   // for all incoming edges that are dominated by condition `%cond == true`,
2523   // and value %b for edges dominated by condition `%cond == false`. If %a
2524   // or %b are also phis from the same basic block, we can go further and take
2525   // their incoming values from the corresponding blocks.
2526   BasicBlockEdge TrueEdge(IDom, TrueSucc);
2527   BasicBlockEdge FalseEdge(IDom, FalseSucc);
2528   DenseMap<BasicBlock *, Value *> Inputs;
2529   for (auto *Pred : predecessors(BB)) {
2530     // Check implication.
2531     BasicBlockEdge Incoming(Pred, BB);
2532     if (DT.dominates(TrueEdge, Incoming))
2533       Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
2534     else if (DT.dominates(FalseEdge, Incoming))
2535       Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
2536     else
2537       return nullptr;
2538     // Check availability.
2539     if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
2540       if (!DT.dominates(Insn, Pred->getTerminator()))
2541         return nullptr;
2542   }
2543 
2544   Builder.SetInsertPoint(&*BB->begin());
2545   auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
2546   for (auto *Pred : predecessors(BB))
2547     PN->addIncoming(Inputs[Pred], Pred);
2548   PN->takeName(&Sel);
2549   return PN;
2550 }
2551 
2552 static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
2553                                     InstCombiner::BuilderTy &Builder) {
2554   // Try to replace this select with Phi in one of these blocks.
2555   SmallSetVector<BasicBlock *, 4> CandidateBlocks;
2556   CandidateBlocks.insert(Sel.getParent());
2557   for (Value *V : Sel.operands())
2558     if (auto *I = dyn_cast<Instruction>(V))
2559       CandidateBlocks.insert(I->getParent());
2560 
2561   for (BasicBlock *BB : CandidateBlocks)
2562     if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
2563       return PN;
2564   return nullptr;
2565 }
2566 
2567 static Value *foldSelectWithFrozenICmp(SelectInst &Sel, InstCombiner::BuilderTy &Builder) {
2568   FreezeInst *FI = dyn_cast<FreezeInst>(Sel.getCondition());
2569   if (!FI)
2570     return nullptr;
2571 
2572   Value *Cond = FI->getOperand(0);
2573   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
2574 
2575   //   select (freeze(x == y)), x, y --> y
2576   //   select (freeze(x != y)), x, y --> x
2577   // The freeze should be only used by this select. Otherwise, remaining uses of
2578   // the freeze can observe a contradictory value.
2579   //   c = freeze(x == y)   ; Let's assume that y = poison & x = 42; c is 0 or 1
2580   //   a = select c, x, y   ;
2581   //   f(a, c)              ; f(poison, 1) cannot happen, but if a is folded
2582   //                        ; to y, this can happen.
2583   CmpInst::Predicate Pred;
2584   if (FI->hasOneUse() &&
2585       match(Cond, m_c_ICmp(Pred, m_Specific(TrueVal), m_Specific(FalseVal))) &&
2586       (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)) {
2587     return Pred == ICmpInst::ICMP_EQ ? FalseVal : TrueVal;
2588   }
2589 
2590   return nullptr;
2591 }
2592 
2593 Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
2594   Value *CondVal = SI.getCondition();
2595   Value *TrueVal = SI.getTrueValue();
2596   Value *FalseVal = SI.getFalseValue();
2597   Type *SelType = SI.getType();
2598 
2599   // FIXME: Remove this workaround when freeze related patches are done.
2600   // For select with undef operand which feeds into an equality comparison,
2601   // don't simplify it so loop unswitch can know the equality comparison
2602   // may have an undef operand. This is a workaround for PR31652 caused by
2603   // descrepancy about branch on undef between LoopUnswitch and GVN.
2604   if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
2605     if (llvm::any_of(SI.users(), [&](User *U) {
2606           ICmpInst *CI = dyn_cast<ICmpInst>(U);
2607           if (CI && CI->isEquality())
2608             return true;
2609           return false;
2610         })) {
2611       return nullptr;
2612     }
2613   }
2614 
2615   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
2616                                     SQ.getWithInstruction(&SI)))
2617     return replaceInstUsesWith(SI, V);
2618 
2619   if (Instruction *I = canonicalizeSelectToShuffle(SI))
2620     return I;
2621 
2622   if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
2623     return I;
2624 
2625   CmpInst::Predicate Pred;
2626 
2627   if (SelType->isIntOrIntVectorTy(1) &&
2628       TrueVal->getType() == CondVal->getType()) {
2629     if (match(TrueVal, m_One())) {
2630       // Change: A = select B, true, C --> A = or B, C
2631       return BinaryOperator::CreateOr(CondVal, FalseVal);
2632     }
2633     if (match(TrueVal, m_Zero())) {
2634       // Change: A = select B, false, C --> A = and !B, C
2635       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2636       return BinaryOperator::CreateAnd(NotCond, FalseVal);
2637     }
2638     if (match(FalseVal, m_Zero())) {
2639       // Change: A = select B, C, false --> A = and B, C
2640       return BinaryOperator::CreateAnd(CondVal, TrueVal);
2641     }
2642     if (match(FalseVal, m_One())) {
2643       // Change: A = select B, C, true --> A = or !B, C
2644       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2645       return BinaryOperator::CreateOr(NotCond, TrueVal);
2646     }
2647 
2648     // select a, a, b  -> a | b
2649     // select a, b, a  -> a & b
2650     if (CondVal == TrueVal)
2651       return BinaryOperator::CreateOr(CondVal, FalseVal);
2652     if (CondVal == FalseVal)
2653       return BinaryOperator::CreateAnd(CondVal, TrueVal);
2654 
2655     // select a, ~a, b -> (~a) & b
2656     // select a, b, ~a -> (~a) | b
2657     if (match(TrueVal, m_Not(m_Specific(CondVal))))
2658       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
2659     if (match(FalseVal, m_Not(m_Specific(CondVal))))
2660       return BinaryOperator::CreateOr(TrueVal, FalseVal);
2661   }
2662 
2663   // Selecting between two integer or vector splat integer constants?
2664   //
2665   // Note that we don't handle a scalar select of vectors:
2666   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
2667   // because that may need 3 instructions to splat the condition value:
2668   // extend, insertelement, shufflevector.
2669   if (SelType->isIntOrIntVectorTy() &&
2670       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
2671     // select C, 1, 0 -> zext C to int
2672     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
2673       return new ZExtInst(CondVal, SelType);
2674 
2675     // select C, -1, 0 -> sext C to int
2676     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
2677       return new SExtInst(CondVal, SelType);
2678 
2679     // select C, 0, 1 -> zext !C to int
2680     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
2681       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2682       return new ZExtInst(NotCond, SelType);
2683     }
2684 
2685     // select C, 0, -1 -> sext !C to int
2686     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
2687       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2688       return new SExtInst(NotCond, SelType);
2689     }
2690   }
2691 
2692   // See if we are selecting two values based on a comparison of the two values.
2693   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
2694     Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1);
2695     if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
2696         (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
2697       // Canonicalize to use ordered comparisons by swapping the select
2698       // operands.
2699       //
2700       // e.g.
2701       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
2702       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
2703         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
2704         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2705         // FIXME: The FMF should propagate from the select, not the fcmp.
2706         Builder.setFastMathFlags(FCI->getFastMathFlags());
2707         Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
2708                                             FCI->getName() + ".inv");
2709         Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
2710         return replaceInstUsesWith(SI, NewSel);
2711       }
2712 
2713       // NOTE: if we wanted to, this is where to detect MIN/MAX
2714     }
2715   }
2716 
2717   // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2718   // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
2719   // also require nnan because we do not want to unintentionally change the
2720   // sign of a NaN value.
2721   // FIXME: These folds should test/propagate FMF from the select, not the
2722   //        fsub or fneg.
2723   // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
2724   Instruction *FSub;
2725   if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2726       match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
2727       match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2728       (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2729     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub);
2730     return replaceInstUsesWith(SI, Fabs);
2731   }
2732   // (X >  +/-0.0) ? X : (0.0 - X) --> fabs(X)
2733   if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2734       match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
2735       match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2736       (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2737     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub);
2738     return replaceInstUsesWith(SI, Fabs);
2739   }
2740   // With nnan and nsz:
2741   // (X <  +/-0.0) ? -X : X --> fabs(X)
2742   // (X <= +/-0.0) ? -X : X --> fabs(X)
2743   Instruction *FNeg;
2744   if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2745       match(TrueVal, m_FNeg(m_Specific(FalseVal))) &&
2746       match(TrueVal, m_Instruction(FNeg)) &&
2747       FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2748       (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2749        Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
2750     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg);
2751     return replaceInstUsesWith(SI, Fabs);
2752   }
2753   // With nnan and nsz:
2754   // (X >  +/-0.0) ? X : -X --> fabs(X)
2755   // (X >= +/-0.0) ? X : -X --> fabs(X)
2756   if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2757       match(FalseVal, m_FNeg(m_Specific(TrueVal))) &&
2758       match(FalseVal, m_Instruction(FNeg)) &&
2759       FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2760       (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2761        Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
2762     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg);
2763     return replaceInstUsesWith(SI, Fabs);
2764   }
2765 
2766   // See if we are selecting two values based on a comparison of the two values.
2767   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
2768     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
2769       return Result;
2770 
2771   if (Instruction *Add = foldAddSubSelect(SI, Builder))
2772     return Add;
2773   if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
2774     return Add;
2775   if (Instruction *Or = foldSetClearBits(SI, Builder))
2776     return Or;
2777 
2778   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
2779   auto *TI = dyn_cast<Instruction>(TrueVal);
2780   auto *FI = dyn_cast<Instruction>(FalseVal);
2781   if (TI && FI && TI->getOpcode() == FI->getOpcode())
2782     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
2783       return IV;
2784 
2785   if (Instruction *I = foldSelectExtConst(SI))
2786     return I;
2787 
2788   // See if we can fold the select into one of our operands.
2789   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
2790     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
2791       return FoldI;
2792 
2793     Value *LHS, *RHS;
2794     Instruction::CastOps CastOp;
2795     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
2796     auto SPF = SPR.Flavor;
2797     if (SPF) {
2798       Value *LHS2, *RHS2;
2799       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
2800         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
2801                                           RHS2, SI, SPF, RHS))
2802           return R;
2803       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
2804         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
2805                                           RHS2, SI, SPF, LHS))
2806           return R;
2807       // TODO.
2808       // ABS(-X) -> ABS(X)
2809     }
2810 
2811     if (SelectPatternResult::isMinOrMax(SPF)) {
2812       // Canonicalize so that
2813       // - type casts are outside select patterns.
2814       // - float clamp is transformed to min/max pattern
2815 
2816       bool IsCastNeeded = LHS->getType() != SelType;
2817       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
2818       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
2819       if (IsCastNeeded ||
2820           (LHS->getType()->isFPOrFPVectorTy() &&
2821            ((CmpLHS != LHS && CmpLHS != RHS) ||
2822             (CmpRHS != LHS && CmpRHS != RHS)))) {
2823         CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
2824 
2825         Value *Cmp;
2826         if (CmpInst::isIntPredicate(MinMaxPred)) {
2827           Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
2828         } else {
2829           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2830           auto FMF =
2831               cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
2832           Builder.setFastMathFlags(FMF);
2833           Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
2834         }
2835 
2836         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
2837         if (!IsCastNeeded)
2838           return replaceInstUsesWith(SI, NewSI);
2839 
2840         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
2841         return replaceInstUsesWith(SI, NewCast);
2842       }
2843 
2844       // MAX(~a, ~b) -> ~MIN(a, b)
2845       // MAX(~a, C)  -> ~MIN(a, ~C)
2846       // MIN(~a, ~b) -> ~MAX(a, b)
2847       // MIN(~a, C)  -> ~MAX(a, ~C)
2848       auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2849         Value *A;
2850         if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
2851             !isFreeToInvert(A, A->hasOneUse()) &&
2852             // Passing false to only consider m_Not and constants.
2853             isFreeToInvert(Y, false)) {
2854           Value *B = Builder.CreateNot(Y);
2855           Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
2856                                           A, B);
2857           // Copy the profile metadata.
2858           if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
2859             cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
2860             // Swap the metadata if the operands are swapped.
2861             if (X == SI.getFalseValue() && Y == SI.getTrueValue())
2862               cast<SelectInst>(NewMinMax)->swapProfMetadata();
2863           }
2864 
2865           return BinaryOperator::CreateNot(NewMinMax);
2866         }
2867 
2868         return nullptr;
2869       };
2870 
2871       if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
2872         return I;
2873       if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
2874         return I;
2875 
2876       if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
2877         return I;
2878 
2879       if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
2880         return I;
2881       if (Instruction *I = matchSAddSubSat(SI))
2882         return I;
2883     }
2884   }
2885 
2886   // Canonicalize select of FP values where NaN and -0.0 are not valid as
2887   // minnum/maxnum intrinsics.
2888   if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
2889     Value *X, *Y;
2890     if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
2891       return replaceInstUsesWith(
2892           SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
2893 
2894     if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
2895       return replaceInstUsesWith(
2896           SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
2897   }
2898 
2899   // See if we can fold the select into a phi node if the condition is a select.
2900   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
2901     // The true/false values have to be live in the PHI predecessor's blocks.
2902     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
2903         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
2904       if (Instruction *NV = foldOpIntoPhi(SI, PN))
2905         return NV;
2906 
2907   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
2908     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
2909       // select(C, select(C, a, b), c) -> select(C, a, c)
2910       if (TrueSI->getCondition() == CondVal) {
2911         if (SI.getTrueValue() == TrueSI->getTrueValue())
2912           return nullptr;
2913         return replaceOperand(SI, 1, TrueSI->getTrueValue());
2914       }
2915       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
2916       // We choose this as normal form to enable folding on the And and
2917       // shortening paths for the values (this helps getUnderlyingObjects() for
2918       // example).
2919       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
2920         Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
2921         replaceOperand(SI, 0, And);
2922         replaceOperand(SI, 1, TrueSI->getTrueValue());
2923         return &SI;
2924       }
2925     }
2926   }
2927   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
2928     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
2929       // select(C, a, select(C, b, c)) -> select(C, a, c)
2930       if (FalseSI->getCondition() == CondVal) {
2931         if (SI.getFalseValue() == FalseSI->getFalseValue())
2932           return nullptr;
2933         return replaceOperand(SI, 2, FalseSI->getFalseValue());
2934       }
2935       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
2936       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
2937         Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
2938         replaceOperand(SI, 0, Or);
2939         replaceOperand(SI, 2, FalseSI->getFalseValue());
2940         return &SI;
2941       }
2942     }
2943   }
2944 
2945   auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2946     // The select might be preventing a division by 0.
2947     switch (BO->getOpcode()) {
2948     default:
2949       return true;
2950     case Instruction::SRem:
2951     case Instruction::URem:
2952     case Instruction::SDiv:
2953     case Instruction::UDiv:
2954       return false;
2955     }
2956   };
2957 
2958   // Try to simplify a binop sandwiched between 2 selects with the same
2959   // condition.
2960   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2961   BinaryOperator *TrueBO;
2962   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2963       canMergeSelectThroughBinop(TrueBO)) {
2964     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2965       if (TrueBOSI->getCondition() == CondVal) {
2966         replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
2967         Worklist.push(TrueBO);
2968         return &SI;
2969       }
2970     }
2971     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2972       if (TrueBOSI->getCondition() == CondVal) {
2973         replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
2974         Worklist.push(TrueBO);
2975         return &SI;
2976       }
2977     }
2978   }
2979 
2980   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2981   BinaryOperator *FalseBO;
2982   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2983       canMergeSelectThroughBinop(FalseBO)) {
2984     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2985       if (FalseBOSI->getCondition() == CondVal) {
2986         replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
2987         Worklist.push(FalseBO);
2988         return &SI;
2989       }
2990     }
2991     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2992       if (FalseBOSI->getCondition() == CondVal) {
2993         replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
2994         Worklist.push(FalseBO);
2995         return &SI;
2996       }
2997     }
2998   }
2999 
3000   Value *NotCond;
3001   if (match(CondVal, m_Not(m_Value(NotCond)))) {
3002     replaceOperand(SI, 0, NotCond);
3003     SI.swapValues();
3004     SI.swapProfMetadata();
3005     return &SI;
3006   }
3007 
3008   if (Instruction *I = foldVectorSelect(SI))
3009     return I;
3010 
3011   // If we can compute the condition, there's no need for a select.
3012   // Like the above fold, we are attempting to reduce compile-time cost by
3013   // putting this fold here with limitations rather than in InstSimplify.
3014   // The motivation for this call into value tracking is to take advantage of
3015   // the assumption cache, so make sure that is populated.
3016   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
3017     KnownBits Known(1);
3018     computeKnownBits(CondVal, Known, 0, &SI);
3019     if (Known.One.isOneValue())
3020       return replaceInstUsesWith(SI, TrueVal);
3021     if (Known.Zero.isOneValue())
3022       return replaceInstUsesWith(SI, FalseVal);
3023   }
3024 
3025   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
3026     return BitCastSel;
3027 
3028   // Simplify selects that test the returned flag of cmpxchg instructions.
3029   if (Value *V = foldSelectCmpXchg(SI))
3030     return replaceInstUsesWith(SI, V);
3031 
3032   if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
3033     return Select;
3034 
3035   if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder))
3036     return Funnel;
3037 
3038   if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
3039     return Copysign;
3040 
3041   if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
3042     return replaceInstUsesWith(SI, PN);
3043 
3044   if (Value *Fr = foldSelectWithFrozenICmp(SI, Builder))
3045     return replaceInstUsesWith(SI, Fr);
3046 
3047   return nullptr;
3048 }
3049