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 /// For the same transformation as the previous function, return the identity
263 /// constant that goes into the select.
264 static APInt getSelectFoldableConstant(BinaryOperator *I) {
265   switch (I->getOpcode()) {
266   default: llvm_unreachable("This cannot happen!");
267   case Instruction::Add:
268   case Instruction::Sub:
269   case Instruction::Or:
270   case Instruction::Xor:
271   case Instruction::Shl:
272   case Instruction::LShr:
273   case Instruction::AShr:
274     return APInt::getNullValue(I->getType()->getScalarSizeInBits());
275   case Instruction::And:
276     return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
277   case Instruction::Mul:
278     return APInt(I->getType()->getScalarSizeInBits(), 1);
279   }
280 }
281 
282 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
283 Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
284                                               Instruction *FI) {
285   // Don't break up min/max patterns. The hasOneUse checks below prevent that
286   // for most cases, but vector min/max with bitcasts can be transformed. If the
287   // one-use restrictions are eased for other patterns, we still don't want to
288   // obfuscate min/max.
289   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
290        match(&SI, m_SMax(m_Value(), m_Value())) ||
291        match(&SI, m_UMin(m_Value(), m_Value())) ||
292        match(&SI, m_UMax(m_Value(), m_Value()))))
293     return nullptr;
294 
295   // If this is a cast from the same type, merge.
296   Value *Cond = SI.getCondition();
297   Type *CondTy = Cond->getType();
298   if (TI->getNumOperands() == 1 && TI->isCast()) {
299     Type *FIOpndTy = FI->getOperand(0)->getType();
300     if (TI->getOperand(0)->getType() != FIOpndTy)
301       return nullptr;
302 
303     // The select condition may be a vector. We may only change the operand
304     // type if the vector width remains the same (and matches the condition).
305     if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
306       if (!FIOpndTy->isVectorTy())
307         return nullptr;
308       if (cast<FixedVectorType>(CondVTy)->getNumElements() !=
309           cast<FixedVectorType>(FIOpndTy)->getNumElements())
310         return nullptr;
311 
312       // TODO: If the backend knew how to deal with casts better, we could
313       // remove this limitation. For now, there's too much potential to create
314       // worse codegen by promoting the select ahead of size-altering casts
315       // (PR28160).
316       //
317       // Note that ValueTracking's matchSelectPattern() looks through casts
318       // without checking 'hasOneUse' when it matches min/max patterns, so this
319       // transform may end up happening anyway.
320       if (TI->getOpcode() != Instruction::BitCast &&
321           (!TI->hasOneUse() || !FI->hasOneUse()))
322         return nullptr;
323     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
324       // TODO: The one-use restrictions for a scalar select could be eased if
325       // the fold of a select in visitLoadInst() was enhanced to match a pattern
326       // that includes a cast.
327       return nullptr;
328     }
329 
330     // Fold this by inserting a select from the input values.
331     Value *NewSI =
332         Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
333                              SI.getName() + ".v", &SI);
334     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
335                             TI->getType());
336   }
337 
338   // Cond ? -X : -Y --> -(Cond ? X : Y)
339   Value *X, *Y;
340   if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
341       (TI->hasOneUse() || FI->hasOneUse())) {
342     Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
343     return UnaryOperator::CreateFNegFMF(NewSel, TI);
344   }
345 
346   // Only handle binary operators (including two-operand getelementptr) with
347   // one-use here. As with the cast case above, it may be possible to relax the
348   // one-use constraint, but that needs be examined carefully since it may not
349   // reduce the total number of instructions.
350   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
351       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
352       !TI->hasOneUse() || !FI->hasOneUse())
353     return nullptr;
354 
355   // Figure out if the operations have any operands in common.
356   Value *MatchOp, *OtherOpT, *OtherOpF;
357   bool MatchIsOpZero;
358   if (TI->getOperand(0) == FI->getOperand(0)) {
359     MatchOp  = TI->getOperand(0);
360     OtherOpT = TI->getOperand(1);
361     OtherOpF = FI->getOperand(1);
362     MatchIsOpZero = true;
363   } else if (TI->getOperand(1) == FI->getOperand(1)) {
364     MatchOp  = TI->getOperand(1);
365     OtherOpT = TI->getOperand(0);
366     OtherOpF = FI->getOperand(0);
367     MatchIsOpZero = false;
368   } else if (!TI->isCommutative()) {
369     return nullptr;
370   } else if (TI->getOperand(0) == FI->getOperand(1)) {
371     MatchOp  = TI->getOperand(0);
372     OtherOpT = TI->getOperand(1);
373     OtherOpF = FI->getOperand(0);
374     MatchIsOpZero = true;
375   } else if (TI->getOperand(1) == FI->getOperand(0)) {
376     MatchOp  = TI->getOperand(1);
377     OtherOpT = TI->getOperand(0);
378     OtherOpF = FI->getOperand(1);
379     MatchIsOpZero = true;
380   } else {
381     return nullptr;
382   }
383 
384   // If the select condition is a vector, the operands of the original select's
385   // operands also must be vectors. This may not be the case for getelementptr
386   // for example.
387   if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
388                                !OtherOpF->getType()->isVectorTy()))
389     return nullptr;
390 
391   // If we reach here, they do have operations in common.
392   Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
393                                       SI.getName() + ".v", &SI);
394   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
395   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
396   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
397     BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
398     NewBO->copyIRFlags(TI);
399     NewBO->andIRFlags(FI);
400     return NewBO;
401   }
402   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
403     auto *FGEP = cast<GetElementPtrInst>(FI);
404     Type *ElementType = TGEP->getResultElementType();
405     return TGEP->isInBounds() && FGEP->isInBounds()
406                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
407                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
408   }
409   llvm_unreachable("Expected BinaryOperator or GEP");
410   return nullptr;
411 }
412 
413 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
414   if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
415     return false;
416   return C1I.isOneValue() || C1I.isAllOnesValue() ||
417          C2I.isOneValue() || C2I.isAllOnesValue();
418 }
419 
420 /// Try to fold the select into one of the operands to allow further
421 /// optimization.
422 Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
423                                                 Value *FalseVal) {
424   // See the comment above GetSelectFoldableOperands for a description of the
425   // transformation we are doing here.
426   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
427     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
428       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
429         unsigned OpToFold = 0;
430         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
431           OpToFold = 1;
432         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
433           OpToFold = 2;
434         }
435 
436         if (OpToFold) {
437           APInt CI = getSelectFoldableConstant(TVI);
438           Value *OOp = TVI->getOperand(2-OpToFold);
439           // Avoid creating select between 2 constants unless it's selecting
440           // between 0, 1 and -1.
441           const APInt *OOpC;
442           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
443           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
444             Value *C = ConstantInt::get(OOp->getType(), CI);
445             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
446             NewSel->takeName(TVI);
447             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
448                                                         FalseVal, NewSel);
449             BO->copyIRFlags(TVI);
450             return BO;
451           }
452         }
453       }
454     }
455   }
456 
457   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
458     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
459       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
460         unsigned OpToFold = 0;
461         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
462           OpToFold = 1;
463         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
464           OpToFold = 2;
465         }
466 
467         if (OpToFold) {
468           APInt CI = getSelectFoldableConstant(FVI);
469           Value *OOp = FVI->getOperand(2-OpToFold);
470           // Avoid creating select between 2 constants unless it's selecting
471           // between 0, 1 and -1.
472           const APInt *OOpC;
473           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
474           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
475             Value *C = ConstantInt::get(OOp->getType(), CI);
476             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
477             NewSel->takeName(FVI);
478             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
479                                                         TrueVal, NewSel);
480             BO->copyIRFlags(FVI);
481             return BO;
482           }
483         }
484       }
485     }
486   }
487 
488   return nullptr;
489 }
490 
491 /// We want to turn:
492 ///   (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
493 /// into:
494 ///   zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
495 /// Note:
496 ///   Z may be 0 if lshr is missing.
497 /// Worst-case scenario is that we will replace 5 instructions with 5 different
498 /// instructions, but we got rid of select.
499 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
500                                          Value *TVal, Value *FVal,
501                                          InstCombiner::BuilderTy &Builder) {
502   if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
503         Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
504         match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
505     return nullptr;
506 
507   // The TrueVal has general form of:  and %B, 1
508   Value *B;
509   if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
510     return nullptr;
511 
512   // Where %B may be optionally shifted:  lshr %X, %Z.
513   Value *X, *Z;
514   const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
515   if (!HasShift)
516     X = B;
517 
518   Value *Y;
519   if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
520     return nullptr;
521 
522   // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
523   // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
524   Constant *One = ConstantInt::get(SelType, 1);
525   Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
526   Value *FullMask = Builder.CreateOr(Y, MaskB);
527   Value *MaskedX = Builder.CreateAnd(X, FullMask);
528   Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
529   return new ZExtInst(ICmpNeZero, SelType);
530 }
531 
532 /// We want to turn:
533 ///   (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
534 ///   (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
535 /// into:
536 ///   ashr (X, Y)
537 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
538                                      Value *FalseVal,
539                                      InstCombiner::BuilderTy &Builder) {
540   ICmpInst::Predicate Pred = IC->getPredicate();
541   Value *CmpLHS = IC->getOperand(0);
542   Value *CmpRHS = IC->getOperand(1);
543   if (!CmpRHS->getType()->isIntOrIntVectorTy())
544     return nullptr;
545 
546   Value *X, *Y;
547   unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
548   if ((Pred != ICmpInst::ICMP_SGT ||
549        !match(CmpRHS,
550               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
551       (Pred != ICmpInst::ICMP_SLT ||
552        !match(CmpRHS,
553               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
554     return nullptr;
555 
556   // Canonicalize so that ashr is in FalseVal.
557   if (Pred == ICmpInst::ICMP_SLT)
558     std::swap(TrueVal, FalseVal);
559 
560   if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
561       match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
562       match(CmpLHS, m_Specific(X))) {
563     const auto *Ashr = cast<Instruction>(FalseVal);
564     // if lshr is not exact and ashr is, this new ashr must not be exact.
565     bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
566     return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
567   }
568 
569   return nullptr;
570 }
571 
572 /// We want to turn:
573 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
574 /// into:
575 ///   (or (shl (and X, C1), C3), Y)
576 /// iff:
577 ///   C1 and C2 are both powers of 2
578 /// where:
579 ///   C3 = Log(C2) - Log(C1)
580 ///
581 /// This transform handles cases where:
582 /// 1. The icmp predicate is inverted
583 /// 2. The select operands are reversed
584 /// 3. The magnitude of C2 and C1 are flipped
585 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
586                                   Value *FalseVal,
587                                   InstCombiner::BuilderTy &Builder) {
588   // Only handle integer compares. Also, if this is a vector select, we need a
589   // vector compare.
590   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
591       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
592     return nullptr;
593 
594   Value *CmpLHS = IC->getOperand(0);
595   Value *CmpRHS = IC->getOperand(1);
596 
597   Value *V;
598   unsigned C1Log;
599   bool IsEqualZero;
600   bool NeedAnd = false;
601   if (IC->isEquality()) {
602     if (!match(CmpRHS, m_Zero()))
603       return nullptr;
604 
605     const APInt *C1;
606     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
607       return nullptr;
608 
609     V = CmpLHS;
610     C1Log = C1->logBase2();
611     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
612   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
613              IC->getPredicate() == ICmpInst::ICMP_SGT) {
614     // We also need to recognize (icmp slt (trunc (X)), 0) and
615     // (icmp sgt (trunc (X)), -1).
616     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
617     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
618         (!IsEqualZero && !match(CmpRHS, m_Zero())))
619       return nullptr;
620 
621     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
622       return nullptr;
623 
624     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
625     NeedAnd = true;
626   } else {
627     return nullptr;
628   }
629 
630   const APInt *C2;
631   bool OrOnTrueVal = false;
632   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
633   if (!OrOnFalseVal)
634     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
635 
636   if (!OrOnFalseVal && !OrOnTrueVal)
637     return nullptr;
638 
639   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
640 
641   unsigned C2Log = C2->logBase2();
642 
643   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
644   bool NeedShift = C1Log != C2Log;
645   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
646                        V->getType()->getScalarSizeInBits();
647 
648   // Make sure we don't create more instructions than we save.
649   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
650   if ((NeedShift + NeedXor + NeedZExtTrunc) >
651       (IC->hasOneUse() + Or->hasOneUse()))
652     return nullptr;
653 
654   if (NeedAnd) {
655     // Insert the AND instruction on the input to the truncate.
656     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
657     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
658   }
659 
660   if (C2Log > C1Log) {
661     V = Builder.CreateZExtOrTrunc(V, Y->getType());
662     V = Builder.CreateShl(V, C2Log - C1Log);
663   } else if (C1Log > C2Log) {
664     V = Builder.CreateLShr(V, C1Log - C2Log);
665     V = Builder.CreateZExtOrTrunc(V, Y->getType());
666   } else
667     V = Builder.CreateZExtOrTrunc(V, Y->getType());
668 
669   if (NeedXor)
670     V = Builder.CreateXor(V, *C2);
671 
672   return Builder.CreateOr(V, Y);
673 }
674 
675 /// Canonicalize a set or clear of a masked set of constant bits to
676 /// select-of-constants form.
677 static Instruction *foldSetClearBits(SelectInst &Sel,
678                                      InstCombiner::BuilderTy &Builder) {
679   Value *Cond = Sel.getCondition();
680   Value *T = Sel.getTrueValue();
681   Value *F = Sel.getFalseValue();
682   Type *Ty = Sel.getType();
683   Value *X;
684   const APInt *NotC, *C;
685 
686   // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
687   if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
688       match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
689     Constant *Zero = ConstantInt::getNullValue(Ty);
690     Constant *OrC = ConstantInt::get(Ty, *C);
691     Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
692     return BinaryOperator::CreateOr(T, NewSel);
693   }
694 
695   // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
696   if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
697       match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
698     Constant *Zero = ConstantInt::getNullValue(Ty);
699     Constant *OrC = ConstantInt::get(Ty, *C);
700     Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
701     return BinaryOperator::CreateOr(F, NewSel);
702   }
703 
704   return nullptr;
705 }
706 
707 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
708 /// There are 8 commuted/swapped variants of this pattern.
709 /// TODO: Also support a - UMIN(a,b) patterns.
710 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
711                                             const Value *TrueVal,
712                                             const Value *FalseVal,
713                                             InstCombiner::BuilderTy &Builder) {
714   ICmpInst::Predicate Pred = ICI->getPredicate();
715   if (!ICmpInst::isUnsigned(Pred))
716     return nullptr;
717 
718   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
719   if (match(TrueVal, m_Zero())) {
720     Pred = ICmpInst::getInversePredicate(Pred);
721     std::swap(TrueVal, FalseVal);
722   }
723   if (!match(FalseVal, m_Zero()))
724     return nullptr;
725 
726   Value *A = ICI->getOperand(0);
727   Value *B = ICI->getOperand(1);
728   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
729     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
730     std::swap(A, B);
731     Pred = ICmpInst::getSwappedPredicate(Pred);
732   }
733 
734   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
735          "Unexpected isUnsigned predicate!");
736 
737   // Ensure the sub is of the form:
738   //  (a > b) ? a - b : 0 -> usub.sat(a, b)
739   //  (a > b) ? b - a : 0 -> -usub.sat(a, b)
740   // Checking for both a-b and a+(-b) as a constant.
741   bool IsNegative = false;
742   const APInt *C;
743   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
744       (match(A, m_APInt(C)) &&
745        match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
746     IsNegative = true;
747   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
748            !(match(B, m_APInt(C)) &&
749              match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
750     return nullptr;
751 
752   // If we are adding a negate and the sub and icmp are used anywhere else, we
753   // would end up with more instructions.
754   if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
755     return nullptr;
756 
757   // (a > b) ? a - b : 0 -> usub.sat(a, b)
758   // (a > b) ? b - a : 0 -> -usub.sat(a, b)
759   Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
760   if (IsNegative)
761     Result = Builder.CreateNeg(Result);
762   return Result;
763 }
764 
765 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
766                                        InstCombiner::BuilderTy &Builder) {
767   if (!Cmp->hasOneUse())
768     return nullptr;
769 
770   // Match unsigned saturated add with constant.
771   Value *Cmp0 = Cmp->getOperand(0);
772   Value *Cmp1 = Cmp->getOperand(1);
773   ICmpInst::Predicate Pred = Cmp->getPredicate();
774   Value *X;
775   const APInt *C, *CmpC;
776   if (Pred == ICmpInst::ICMP_ULT &&
777       match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
778       match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
779     // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
780     return Builder.CreateBinaryIntrinsic(
781         Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
782   }
783 
784   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
785   // There are 8 commuted variants.
786   // Canonicalize -1 (saturated result) to true value of the select. Just
787   // swapping the compare operands is legal, because the selected value is the
788   // same in case of equality, so we can interchange u< and u<=.
789   if (match(FVal, m_AllOnes())) {
790     std::swap(TVal, FVal);
791     std::swap(Cmp0, Cmp1);
792   }
793   if (!match(TVal, m_AllOnes()))
794     return nullptr;
795 
796   // Canonicalize predicate to 'ULT'.
797   if (Pred == ICmpInst::ICMP_UGT) {
798     Pred = ICmpInst::ICMP_ULT;
799     std::swap(Cmp0, Cmp1);
800   }
801   if (Pred != ICmpInst::ICMP_ULT)
802     return nullptr;
803 
804   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
805   Value *Y;
806   if (match(Cmp0, m_Not(m_Value(X))) &&
807       match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
808     // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
809     // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
810     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
811   }
812   // The 'not' op may be included in the sum but not the compare.
813   X = Cmp0;
814   Y = Cmp1;
815   if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
816     // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
817     // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
818     BinaryOperator *BO = cast<BinaryOperator>(FVal);
819     return Builder.CreateBinaryIntrinsic(
820         Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
821   }
822   // The overflow may be detected via the add wrapping round.
823   if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
824       match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
825     // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
826     // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
827     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
828   }
829 
830   return nullptr;
831 }
832 
833 /// Fold the following code sequence:
834 /// \code
835 ///   int a = ctlz(x & -x);
836 //    x ? 31 - a : a;
837 /// \code
838 ///
839 /// into:
840 ///   cttz(x)
841 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
842                                          Value *FalseVal,
843                                          InstCombiner::BuilderTy &Builder) {
844   unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
845   if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
846     return nullptr;
847 
848   if (ICI->getPredicate() == ICmpInst::ICMP_NE)
849     std::swap(TrueVal, FalseVal);
850 
851   if (!match(FalseVal,
852              m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
853     return nullptr;
854 
855   if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
856     return nullptr;
857 
858   Value *X = ICI->getOperand(0);
859   auto *II = cast<IntrinsicInst>(TrueVal);
860   if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
861     return nullptr;
862 
863   Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
864                                           II->getType());
865   return CallInst::Create(F, {X, II->getArgOperand(1)});
866 }
867 
868 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
869 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
870 ///
871 /// For example, we can fold the following code sequence:
872 /// \code
873 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
874 ///   %1 = icmp ne i32 %x, 0
875 ///   %2 = select i1 %1, i32 %0, i32 32
876 /// \code
877 ///
878 /// into:
879 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
880 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
881                                  InstCombiner::BuilderTy &Builder) {
882   ICmpInst::Predicate Pred = ICI->getPredicate();
883   Value *CmpLHS = ICI->getOperand(0);
884   Value *CmpRHS = ICI->getOperand(1);
885 
886   // Check if the condition value compares a value for equality against zero.
887   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
888     return nullptr;
889 
890   Value *SelectArg = FalseVal;
891   Value *ValueOnZero = TrueVal;
892   if (Pred == ICmpInst::ICMP_NE)
893     std::swap(SelectArg, ValueOnZero);
894 
895   // Skip zero extend/truncate.
896   Value *Count = nullptr;
897   if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
898       !match(SelectArg, m_Trunc(m_Value(Count))))
899     Count = SelectArg;
900 
901   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
902   // input to the cttz/ctlz is used as LHS for the compare instruction.
903   if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
904       !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
905     return nullptr;
906 
907   IntrinsicInst *II = cast<IntrinsicInst>(Count);
908 
909   // Check if the value propagated on zero is a constant number equal to the
910   // sizeof in bits of 'Count'.
911   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
912   if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
913     // Explicitly clear the 'undef_on_zero' flag. It's always valid to go from
914     // true to false on this flag, so we can replace it for all users.
915     II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
916     return SelectArg;
917   }
918 
919   // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
920   // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
921   // not be used if the input is zero. Relax to 'undef_on_zero' for that case.
922   if (II->hasOneUse() && SelectArg->hasOneUse() &&
923       !match(II->getArgOperand(1), m_One()))
924     II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
925 
926   return nullptr;
927 }
928 
929 /// Return true if we find and adjust an icmp+select pattern where the compare
930 /// is with a constant that can be incremented or decremented to match the
931 /// minimum or maximum idiom.
932 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
933   ICmpInst::Predicate Pred = Cmp.getPredicate();
934   Value *CmpLHS = Cmp.getOperand(0);
935   Value *CmpRHS = Cmp.getOperand(1);
936   Value *TrueVal = Sel.getTrueValue();
937   Value *FalseVal = Sel.getFalseValue();
938 
939   // We may move or edit the compare, so make sure the select is the only user.
940   const APInt *CmpC;
941   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
942     return false;
943 
944   // These transforms only work for selects of integers or vector selects of
945   // integer vectors.
946   Type *SelTy = Sel.getType();
947   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
948   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
949     return false;
950 
951   Constant *AdjustedRHS;
952   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
953     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
954   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
955     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
956   else
957     return false;
958 
959   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
960   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
961   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
962       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
963     ; // Nothing to do here. Values match without any sign/zero extension.
964   }
965   // Types do not match. Instead of calculating this with mixed types, promote
966   // all to the larger type. This enables scalar evolution to analyze this
967   // expression.
968   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
969     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
970 
971     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
972     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
973     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
974     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
975     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
976       CmpLHS = TrueVal;
977       AdjustedRHS = SextRHS;
978     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
979                SextRHS == TrueVal) {
980       CmpLHS = FalseVal;
981       AdjustedRHS = SextRHS;
982     } else if (Cmp.isUnsigned()) {
983       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
984       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
985       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
986       // zext + signed compare cannot be changed:
987       //    0xff <s 0x00, but 0x00ff >s 0x0000
988       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
989         CmpLHS = TrueVal;
990         AdjustedRHS = ZextRHS;
991       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
992                  ZextRHS == TrueVal) {
993         CmpLHS = FalseVal;
994         AdjustedRHS = ZextRHS;
995       } else {
996         return false;
997       }
998     } else {
999       return false;
1000     }
1001   } else {
1002     return false;
1003   }
1004 
1005   Pred = ICmpInst::getSwappedPredicate(Pred);
1006   CmpRHS = AdjustedRHS;
1007   std::swap(FalseVal, TrueVal);
1008   Cmp.setPredicate(Pred);
1009   Cmp.setOperand(0, CmpLHS);
1010   Cmp.setOperand(1, CmpRHS);
1011   Sel.setOperand(1, TrueVal);
1012   Sel.setOperand(2, FalseVal);
1013   Sel.swapProfMetadata();
1014 
1015   // Move the compare instruction right before the select instruction. Otherwise
1016   // the sext/zext value may be defined after the compare instruction uses it.
1017   Cmp.moveBefore(&Sel);
1018 
1019   return true;
1020 }
1021 
1022 /// If this is an integer min/max (icmp + select) with a constant operand,
1023 /// create the canonical icmp for the min/max operation and canonicalize the
1024 /// constant to the 'false' operand of the select:
1025 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
1026 /// Note: if C1 != C2, this will change the icmp constant to the existing
1027 /// constant operand of the select.
1028 static Instruction *canonicalizeMinMaxWithConstant(SelectInst &Sel,
1029                                                    ICmpInst &Cmp,
1030                                                    InstCombinerImpl &IC) {
1031   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1032     return nullptr;
1033 
1034   // Canonicalize the compare predicate based on whether we have min or max.
1035   Value *LHS, *RHS;
1036   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
1037   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1038     return nullptr;
1039 
1040   // Is this already canonical?
1041   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1042   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1043       Cmp.getPredicate() == CanonicalPred)
1044     return nullptr;
1045 
1046   // Bail out on unsimplified X-0 operand (due to some worklist management bug),
1047   // as this may cause an infinite combine loop. Let the sub be folded first.
1048   if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1049       match(RHS, m_Sub(m_Value(), m_Zero())))
1050     return nullptr;
1051 
1052   // Create the canonical compare and plug it into the select.
1053   IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS));
1054 
1055   // If the select operands did not change, we're done.
1056   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1057     return &Sel;
1058 
1059   // If we are swapping the select operands, swap the metadata too.
1060   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
1061          "Unexpected results from matchSelectPattern");
1062   Sel.swapValues();
1063   Sel.swapProfMetadata();
1064   return &Sel;
1065 }
1066 
1067 /// There are many select variants for each of ABS/NABS.
1068 /// In matchSelectPattern(), there are different compare constants, compare
1069 /// predicates/operands and select operands.
1070 /// In isKnownNegation(), there are different formats of negated operands.
1071 /// Canonicalize all these variants to 1 pattern.
1072 /// This makes CSE more likely.
1073 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1074                                         InstCombinerImpl &IC) {
1075   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1076     return nullptr;
1077 
1078   // Choose a sign-bit check for the compare (likely simpler for codegen).
1079   // ABS:  (X <s 0) ? -X : X
1080   // NABS: (X <s 0) ? X : -X
1081   Value *LHS, *RHS;
1082   SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1083   if (SPF != SelectPatternFlavor::SPF_ABS &&
1084       SPF != SelectPatternFlavor::SPF_NABS)
1085     return nullptr;
1086 
1087   Value *TVal = Sel.getTrueValue();
1088   Value *FVal = Sel.getFalseValue();
1089   assert(isKnownNegation(TVal, FVal) &&
1090          "Unexpected result from matchSelectPattern");
1091 
1092   // The compare may use the negated abs()/nabs() operand, or it may use
1093   // negation in non-canonical form such as: sub A, B.
1094   bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
1095                           match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
1096 
1097   bool CmpCanonicalized = !CmpUsesNegatedOp &&
1098                           match(Cmp.getOperand(1), m_ZeroInt()) &&
1099                           Cmp.getPredicate() == ICmpInst::ICMP_SLT;
1100   bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
1101 
1102   // Is this already canonical?
1103   if (CmpCanonicalized && RHSCanonicalized)
1104     return nullptr;
1105 
1106   // If RHS is not canonical but is used by other instructions, don't
1107   // canonicalize it and potentially increase the instruction count.
1108   if (!RHSCanonicalized)
1109     if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
1110       return nullptr;
1111 
1112   // Create the canonical compare: icmp slt LHS 0.
1113   if (!CmpCanonicalized) {
1114     Cmp.setPredicate(ICmpInst::ICMP_SLT);
1115     Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
1116     if (CmpUsesNegatedOp)
1117       Cmp.setOperand(0, LHS);
1118   }
1119 
1120   // Create the canonical RHS: RHS = sub (0, LHS).
1121   if (!RHSCanonicalized) {
1122     assert(RHS->hasOneUse() && "RHS use number is not right");
1123     RHS = IC.Builder.CreateNeg(LHS);
1124     if (TVal == LHS) {
1125       // Replace false value.
1126       IC.replaceOperand(Sel, 2, RHS);
1127       FVal = RHS;
1128     } else {
1129       // Replace true value.
1130       IC.replaceOperand(Sel, 1, RHS);
1131       TVal = RHS;
1132     }
1133   }
1134 
1135   // If the select operands do not change, we're done.
1136   if (SPF == SelectPatternFlavor::SPF_NABS) {
1137     if (TVal == LHS)
1138       return &Sel;
1139     assert(FVal == LHS && "Unexpected results from matchSelectPattern");
1140   } else {
1141     if (FVal == LHS)
1142       return &Sel;
1143     assert(TVal == LHS && "Unexpected results from matchSelectPattern");
1144   }
1145 
1146   // We are swapping the select operands, so swap the metadata too.
1147   Sel.swapValues();
1148   Sel.swapProfMetadata();
1149   return &Sel;
1150 }
1151 
1152 /// If we have a select with an equality comparison, then we know the value in
1153 /// one of the arms of the select. See if substituting this value into an arm
1154 /// and simplifying the result yields the same value as the other arm.
1155 ///
1156 /// To make this transform safe, we must drop poison-generating flags
1157 /// (nsw, etc) if we simplified to a binop because the select may be guarding
1158 /// that poison from propagating. If the existing binop already had no
1159 /// poison-generating flags, then this transform can be done by instsimplify.
1160 ///
1161 /// Consider:
1162 ///   %cmp = icmp eq i32 %x, 2147483647
1163 ///   %add = add nsw i32 %x, 1
1164 ///   %sel = select i1 %cmp, i32 -2147483648, i32 %add
1165 ///
1166 /// We can't replace %sel with %add unless we strip away the flags.
1167 /// TODO: Wrapping flags could be preserved in some cases with better analysis.
1168 Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1169                                                           ICmpInst &Cmp) {
1170   if (!Cmp.isEquality())
1171     return nullptr;
1172 
1173   // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1174   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1175   bool Swapped = false;
1176   if (Cmp.getPredicate() == ICmpInst::ICMP_NE) {
1177     std::swap(TrueVal, FalseVal);
1178     Swapped = true;
1179   }
1180 
1181   // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
1182   // Make sure Y cannot be undef though, as we might pick different values for
1183   // undef in the icmp and in f(Y). Additionally, take care to avoid replacing
1184   // X == Y ? X : Z with X == Y ? Y : Z, as that would lead to an infinite
1185   // replacement cycle.
1186   Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1187   if (TrueVal != CmpLHS &&
1188       isGuaranteedNotToBeUndefOrPoison(CmpRHS, SQ.AC, &Sel, &DT))
1189     if (Value *V = SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, SQ,
1190                                           /* AllowRefinement */ true))
1191       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1192   if (TrueVal != CmpRHS &&
1193       isGuaranteedNotToBeUndefOrPoison(CmpLHS, SQ.AC, &Sel, &DT))
1194     if (Value *V = SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, SQ,
1195                                           /* AllowRefinement */ true))
1196       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1197 
1198   auto *FalseInst = dyn_cast<Instruction>(FalseVal);
1199   if (!FalseInst)
1200     return nullptr;
1201 
1202   // InstSimplify already performed this fold if it was possible subject to
1203   // current poison-generating flags. Try the transform again with
1204   // poison-generating flags temporarily dropped.
1205   bool WasNUW = false, WasNSW = false, WasExact = false, WasInBounds = false;
1206   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(FalseVal)) {
1207     WasNUW = OBO->hasNoUnsignedWrap();
1208     WasNSW = OBO->hasNoSignedWrap();
1209     FalseInst->setHasNoUnsignedWrap(false);
1210     FalseInst->setHasNoSignedWrap(false);
1211   }
1212   if (auto *PEO = dyn_cast<PossiblyExactOperator>(FalseVal)) {
1213     WasExact = PEO->isExact();
1214     FalseInst->setIsExact(false);
1215   }
1216   if (auto *GEP = dyn_cast<GetElementPtrInst>(FalseVal)) {
1217     WasInBounds = GEP->isInBounds();
1218     GEP->setIsInBounds(false);
1219   }
1220 
1221   // Try each equivalence substitution possibility.
1222   // We have an 'EQ' comparison, so the select's false value will propagate.
1223   // Example:
1224   // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1225   if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, SQ,
1226                              /* AllowRefinement */ false) == TrueVal ||
1227       SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, SQ,
1228                              /* AllowRefinement */ false) == TrueVal) {
1229     return replaceInstUsesWith(Sel, FalseVal);
1230   }
1231 
1232   // Restore poison-generating flags if the transform did not apply.
1233   if (WasNUW)
1234     FalseInst->setHasNoUnsignedWrap();
1235   if (WasNSW)
1236     FalseInst->setHasNoSignedWrap();
1237   if (WasExact)
1238     FalseInst->setIsExact();
1239   if (WasInBounds)
1240     cast<GetElementPtrInst>(FalseInst)->setIsInBounds();
1241 
1242   return nullptr;
1243 }
1244 
1245 // See if this is a pattern like:
1246 //   %old_cmp1 = icmp slt i32 %x, C2
1247 //   %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1248 //   %old_x_offseted = add i32 %x, C1
1249 //   %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1250 //   %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1251 // This can be rewritten as more canonical pattern:
1252 //   %new_cmp1 = icmp slt i32 %x, -C1
1253 //   %new_cmp2 = icmp sge i32 %x, C0-C1
1254 //   %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1255 //   %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1256 // Iff -C1 s<= C2 s<= C0-C1
1257 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1258 //      SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1259 static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1260                                           InstCombiner::BuilderTy &Builder) {
1261   Value *X = Sel0.getTrueValue();
1262   Value *Sel1 = Sel0.getFalseValue();
1263 
1264   // First match the condition of the outermost select.
1265   // Said condition must be one-use.
1266   if (!Cmp0.hasOneUse())
1267     return nullptr;
1268   Value *Cmp00 = Cmp0.getOperand(0);
1269   Constant *C0;
1270   if (!match(Cmp0.getOperand(1),
1271              m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1272     return nullptr;
1273   // Canonicalize Cmp0 into the form we expect.
1274   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1275   switch (Cmp0.getPredicate()) {
1276   case ICmpInst::Predicate::ICMP_ULT:
1277     break; // Great!
1278   case ICmpInst::Predicate::ICMP_ULE:
1279     // We'd have to increment C0 by one, and for that it must not have all-ones
1280     // element, but then it would have been canonicalized to 'ult' before
1281     // we get here. So we can't do anything useful with 'ule'.
1282     return nullptr;
1283   case ICmpInst::Predicate::ICMP_UGT:
1284     // We want to canonicalize it to 'ult', so we'll need to increment C0,
1285     // which again means it must not have any all-ones elements.
1286     if (!match(C0,
1287                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1288                                   APInt::getAllOnesValue(
1289                                       C0->getType()->getScalarSizeInBits()))))
1290       return nullptr; // Can't do, have all-ones element[s].
1291     C0 = InstCombiner::AddOne(C0);
1292     std::swap(X, Sel1);
1293     break;
1294   case ICmpInst::Predicate::ICMP_UGE:
1295     // The only way we'd get this predicate if this `icmp` has extra uses,
1296     // but then we won't be able to do this fold.
1297     return nullptr;
1298   default:
1299     return nullptr; // Unknown predicate.
1300   }
1301 
1302   // Now that we've canonicalized the ICmp, we know the X we expect;
1303   // the select in other hand should be one-use.
1304   if (!Sel1->hasOneUse())
1305     return nullptr;
1306 
1307   // We now can finish matching the condition of the outermost select:
1308   // it should either be the X itself, or an addition of some constant to X.
1309   Constant *C1;
1310   if (Cmp00 == X)
1311     C1 = ConstantInt::getNullValue(Sel0.getType());
1312   else if (!match(Cmp00,
1313                   m_Add(m_Specific(X),
1314                         m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1315     return nullptr;
1316 
1317   Value *Cmp1;
1318   ICmpInst::Predicate Pred1;
1319   Constant *C2;
1320   Value *ReplacementLow, *ReplacementHigh;
1321   if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1322                             m_Value(ReplacementHigh))) ||
1323       !match(Cmp1,
1324              m_ICmp(Pred1, m_Specific(X),
1325                     m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1326     return nullptr;
1327 
1328   if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1329     return nullptr; // Not enough one-use instructions for the fold.
1330   // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1331   //        two comparisons we'll need to build.
1332 
1333   // Canonicalize Cmp1 into the form we expect.
1334   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1335   switch (Pred1) {
1336   case ICmpInst::Predicate::ICMP_SLT:
1337     break;
1338   case ICmpInst::Predicate::ICMP_SLE:
1339     // We'd have to increment C2 by one, and for that it must not have signed
1340     // max element, but then it would have been canonicalized to 'slt' before
1341     // we get here. So we can't do anything useful with 'sle'.
1342     return nullptr;
1343   case ICmpInst::Predicate::ICMP_SGT:
1344     // We want to canonicalize it to 'slt', so we'll need to increment C2,
1345     // which again means it must not have any signed max elements.
1346     if (!match(C2,
1347                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1348                                   APInt::getSignedMaxValue(
1349                                       C2->getType()->getScalarSizeInBits()))))
1350       return nullptr; // Can't do, have signed max element[s].
1351     C2 = InstCombiner::AddOne(C2);
1352     LLVM_FALLTHROUGH;
1353   case ICmpInst::Predicate::ICMP_SGE:
1354     // Also non-canonical, but here we don't need to change C2,
1355     // so we don't have any restrictions on C2, so we can just handle it.
1356     std::swap(ReplacementLow, ReplacementHigh);
1357     break;
1358   default:
1359     return nullptr; // Unknown predicate.
1360   }
1361 
1362   // The thresholds of this clamp-like pattern.
1363   auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1364   auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1365 
1366   // The fold has a precondition 1: C2 s>= ThresholdLow
1367   auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1368                                          ThresholdLowIncl);
1369   if (!match(Precond1, m_One()))
1370     return nullptr;
1371   // The fold has a precondition 2: C2 s<= ThresholdHigh
1372   auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1373                                          ThresholdHighExcl);
1374   if (!match(Precond2, m_One()))
1375     return nullptr;
1376 
1377   // All good, finally emit the new pattern.
1378   Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1379   Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1380   Value *MaybeReplacedLow =
1381       Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1382   Instruction *MaybeReplacedHigh =
1383       SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1384 
1385   return MaybeReplacedHigh;
1386 }
1387 
1388 // If we have
1389 //  %cmp = icmp [canonical predicate] i32 %x, C0
1390 //  %r = select i1 %cmp, i32 %y, i32 C1
1391 // Where C0 != C1 and %x may be different from %y, see if the constant that we
1392 // will have if we flip the strictness of the predicate (i.e. without changing
1393 // the result) is identical to the C1 in select. If it matches we can change
1394 // original comparison to one with swapped predicate, reuse the constant,
1395 // and swap the hands of select.
1396 static Instruction *
1397 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1398                                          InstCombinerImpl &IC) {
1399   ICmpInst::Predicate Pred;
1400   Value *X;
1401   Constant *C0;
1402   if (!match(&Cmp, m_OneUse(m_ICmp(
1403                        Pred, m_Value(X),
1404                        m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1405     return nullptr;
1406 
1407   // If comparison predicate is non-relational, we won't be able to do anything.
1408   if (ICmpInst::isEquality(Pred))
1409     return nullptr;
1410 
1411   // If comparison predicate is non-canonical, then we certainly won't be able
1412   // to make it canonical; canonicalizeCmpWithConstant() already tried.
1413   if (!InstCombiner::isCanonicalPredicate(Pred))
1414     return nullptr;
1415 
1416   // If the [input] type of comparison and select type are different, lets abort
1417   // for now. We could try to compare constants with trunc/[zs]ext though.
1418   if (C0->getType() != Sel.getType())
1419     return nullptr;
1420 
1421   // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1422 
1423   Value *SelVal0, *SelVal1; // We do not care which one is from where.
1424   match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1425   // At least one of these values we are selecting between must be a constant
1426   // else we'll never succeed.
1427   if (!match(SelVal0, m_AnyIntegralConstant()) &&
1428       !match(SelVal1, m_AnyIntegralConstant()))
1429     return nullptr;
1430 
1431   // Does this constant C match any of the `select` values?
1432   auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1433     return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1434   };
1435 
1436   // If C0 *already* matches true/false value of select, we are done.
1437   if (MatchesSelectValue(C0))
1438     return nullptr;
1439 
1440   // Check the constant we'd have with flipped-strictness predicate.
1441   auto FlippedStrictness =
1442       InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, C0);
1443   if (!FlippedStrictness)
1444     return nullptr;
1445 
1446   // If said constant doesn't match either, then there is no hope,
1447   if (!MatchesSelectValue(FlippedStrictness->second))
1448     return nullptr;
1449 
1450   // It matched! Lets insert the new comparison just before select.
1451   InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1452   IC.Builder.SetInsertPoint(&Sel);
1453 
1454   Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1455   Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1456                                         Cmp.getName() + ".inv");
1457   IC.replaceOperand(Sel, 0, NewCmp);
1458   Sel.swapValues();
1459   Sel.swapProfMetadata();
1460 
1461   return &Sel;
1462 }
1463 
1464 /// Visit a SelectInst that has an ICmpInst as its first operand.
1465 Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI,
1466                                                       ICmpInst *ICI) {
1467   if (Instruction *NewSel = foldSelectValueEquivalence(SI, *ICI))
1468     return NewSel;
1469 
1470   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this))
1471     return NewSel;
1472 
1473   if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, *this))
1474     return NewAbs;
1475 
1476   if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
1477     return NewAbs;
1478 
1479   if (Instruction *NewSel =
1480           tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1481     return NewSel;
1482 
1483   bool Changed = adjustMinMax(SI, *ICI);
1484 
1485   if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1486     return replaceInstUsesWith(SI, V);
1487 
1488   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1489   Value *TrueVal = SI.getTrueValue();
1490   Value *FalseVal = SI.getFalseValue();
1491   ICmpInst::Predicate Pred = ICI->getPredicate();
1492   Value *CmpLHS = ICI->getOperand(0);
1493   Value *CmpRHS = ICI->getOperand(1);
1494   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1495     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1496       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1497       SI.setOperand(1, CmpRHS);
1498       Changed = true;
1499     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1500       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1501       SI.setOperand(2, CmpRHS);
1502       Changed = true;
1503     }
1504   }
1505 
1506   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1507   // decomposeBitTestICmp() might help.
1508   {
1509     unsigned BitWidth =
1510         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1511     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1512     Value *X;
1513     const APInt *Y, *C;
1514     bool TrueWhenUnset;
1515     bool IsBitTest = false;
1516     if (ICmpInst::isEquality(Pred) &&
1517         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1518         match(CmpRHS, m_Zero())) {
1519       IsBitTest = true;
1520       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1521     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1522       X = CmpLHS;
1523       Y = &MinSignedValue;
1524       IsBitTest = true;
1525       TrueWhenUnset = false;
1526     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1527       X = CmpLHS;
1528       Y = &MinSignedValue;
1529       IsBitTest = true;
1530       TrueWhenUnset = true;
1531     }
1532     if (IsBitTest) {
1533       Value *V = nullptr;
1534       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
1535       if (TrueWhenUnset && TrueVal == X &&
1536           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1537         V = Builder.CreateAnd(X, ~(*Y));
1538       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
1539       else if (!TrueWhenUnset && FalseVal == X &&
1540                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1541         V = Builder.CreateAnd(X, ~(*Y));
1542       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
1543       else if (TrueWhenUnset && FalseVal == X &&
1544                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1545         V = Builder.CreateOr(X, *Y);
1546       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
1547       else if (!TrueWhenUnset && TrueVal == X &&
1548                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1549         V = Builder.CreateOr(X, *Y);
1550 
1551       if (V)
1552         return replaceInstUsesWith(SI, V);
1553     }
1554   }
1555 
1556   if (Instruction *V =
1557           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1558     return V;
1559 
1560   if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1561     return V;
1562 
1563   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1564     return replaceInstUsesWith(SI, V);
1565 
1566   if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1567     return replaceInstUsesWith(SI, V);
1568 
1569   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1570     return replaceInstUsesWith(SI, V);
1571 
1572   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1573     return replaceInstUsesWith(SI, V);
1574 
1575   if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1576     return replaceInstUsesWith(SI, V);
1577 
1578   return Changed ? &SI : nullptr;
1579 }
1580 
1581 /// SI is a select whose condition is a PHI node (but the two may be in
1582 /// different blocks). See if the true/false values (V) are live in all of the
1583 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1584 ///
1585 ///   X = phi [ C1, BB1], [C2, BB2]
1586 ///   Y = add
1587 ///   Z = select X, Y, 0
1588 ///
1589 /// because Y is not live in BB1/BB2.
1590 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1591                                                    const SelectInst &SI) {
1592   // If the value is a non-instruction value like a constant or argument, it
1593   // can always be mapped.
1594   const Instruction *I = dyn_cast<Instruction>(V);
1595   if (!I) return true;
1596 
1597   // If V is a PHI node defined in the same block as the condition PHI, we can
1598   // map the arguments.
1599   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1600 
1601   if (const PHINode *VP = dyn_cast<PHINode>(I))
1602     if (VP->getParent() == CondPHI->getParent())
1603       return true;
1604 
1605   // Otherwise, if the PHI and select are defined in the same block and if V is
1606   // defined in a different block, then we can transform it.
1607   if (SI.getParent() == CondPHI->getParent() &&
1608       I->getParent() != CondPHI->getParent())
1609     return true;
1610 
1611   // Otherwise we have a 'hard' case and we can't tell without doing more
1612   // detailed dominator based analysis, punt.
1613   return false;
1614 }
1615 
1616 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1617 ///   SPF2(SPF1(A, B), C)
1618 Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner,
1619                                             SelectPatternFlavor SPF1, Value *A,
1620                                             Value *B, Instruction &Outer,
1621                                             SelectPatternFlavor SPF2,
1622                                             Value *C) {
1623   if (Outer.getType() != Inner->getType())
1624     return nullptr;
1625 
1626   if (C == A || C == B) {
1627     // MAX(MAX(A, B), B) -> MAX(A, B)
1628     // MIN(MIN(a, b), a) -> MIN(a, b)
1629     // TODO: This could be done in instsimplify.
1630     if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1631       return replaceInstUsesWith(Outer, Inner);
1632 
1633     // MAX(MIN(a, b), a) -> a
1634     // MIN(MAX(a, b), a) -> a
1635     // TODO: This could be done in instsimplify.
1636     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1637         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1638         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1639         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1640       return replaceInstUsesWith(Outer, C);
1641   }
1642 
1643   if (SPF1 == SPF2) {
1644     const APInt *CB, *CC;
1645     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1646       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1647       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1648       // TODO: This could be done in instsimplify.
1649       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1650           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1651           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1652           (SPF1 == SPF_SMAX && CB->sge(*CC)))
1653         return replaceInstUsesWith(Outer, Inner);
1654 
1655       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1656       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1657       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1658           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1659           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1660           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1661         Outer.replaceUsesOfWith(Inner, A);
1662         return &Outer;
1663       }
1664     }
1665   }
1666 
1667   // max(max(A, B), min(A, B)) --> max(A, B)
1668   // min(min(A, B), max(A, B)) --> min(A, B)
1669   // TODO: This could be done in instsimplify.
1670   if (SPF1 == SPF2 &&
1671       ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1672        (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1673        (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1674        (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1675     return replaceInstUsesWith(Outer, Inner);
1676 
1677   // ABS(ABS(X)) -> ABS(X)
1678   // NABS(NABS(X)) -> NABS(X)
1679   // TODO: This could be done in instsimplify.
1680   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1681     return replaceInstUsesWith(Outer, Inner);
1682   }
1683 
1684   // ABS(NABS(X)) -> ABS(X)
1685   // NABS(ABS(X)) -> NABS(X)
1686   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1687       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1688     SelectInst *SI = cast<SelectInst>(Inner);
1689     Value *NewSI =
1690         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1691                              SI->getTrueValue(), SI->getName(), SI);
1692     return replaceInstUsesWith(Outer, NewSI);
1693   }
1694 
1695   auto IsFreeOrProfitableToInvert =
1696       [&](Value *V, Value *&NotV, bool &ElidesXor) {
1697     if (match(V, m_Not(m_Value(NotV)))) {
1698       // If V has at most 2 uses then we can get rid of the xor operation
1699       // entirely.
1700       ElidesXor |= !V->hasNUsesOrMore(3);
1701       return true;
1702     }
1703 
1704     if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1705       NotV = nullptr;
1706       return true;
1707     }
1708 
1709     return false;
1710   };
1711 
1712   Value *NotA, *NotB, *NotC;
1713   bool ElidesXor = false;
1714 
1715   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1716   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1717   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1718   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1719   //
1720   // This transform is performance neutral if we can elide at least one xor from
1721   // the set of three operands, since we'll be tacking on an xor at the very
1722   // end.
1723   if (SelectPatternResult::isMinOrMax(SPF1) &&
1724       SelectPatternResult::isMinOrMax(SPF2) &&
1725       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1726       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1727       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1728     if (!NotA)
1729       NotA = Builder.CreateNot(A);
1730     if (!NotB)
1731       NotB = Builder.CreateNot(B);
1732     if (!NotC)
1733       NotC = Builder.CreateNot(C);
1734 
1735     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1736                                    NotB);
1737     Value *NewOuter = Builder.CreateNot(
1738         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1739     return replaceInstUsesWith(Outer, NewOuter);
1740   }
1741 
1742   return nullptr;
1743 }
1744 
1745 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1746 /// This is even legal for FP.
1747 static Instruction *foldAddSubSelect(SelectInst &SI,
1748                                      InstCombiner::BuilderTy &Builder) {
1749   Value *CondVal = SI.getCondition();
1750   Value *TrueVal = SI.getTrueValue();
1751   Value *FalseVal = SI.getFalseValue();
1752   auto *TI = dyn_cast<Instruction>(TrueVal);
1753   auto *FI = dyn_cast<Instruction>(FalseVal);
1754   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1755     return nullptr;
1756 
1757   Instruction *AddOp = nullptr, *SubOp = nullptr;
1758   if ((TI->getOpcode() == Instruction::Sub &&
1759        FI->getOpcode() == Instruction::Add) ||
1760       (TI->getOpcode() == Instruction::FSub &&
1761        FI->getOpcode() == Instruction::FAdd)) {
1762     AddOp = FI;
1763     SubOp = TI;
1764   } else if ((FI->getOpcode() == Instruction::Sub &&
1765               TI->getOpcode() == Instruction::Add) ||
1766              (FI->getOpcode() == Instruction::FSub &&
1767               TI->getOpcode() == Instruction::FAdd)) {
1768     AddOp = TI;
1769     SubOp = FI;
1770   }
1771 
1772   if (AddOp) {
1773     Value *OtherAddOp = nullptr;
1774     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1775       OtherAddOp = AddOp->getOperand(1);
1776     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1777       OtherAddOp = AddOp->getOperand(0);
1778     }
1779 
1780     if (OtherAddOp) {
1781       // So at this point we know we have (Y -> OtherAddOp):
1782       //        select C, (add X, Y), (sub X, Z)
1783       Value *NegVal; // Compute -Z
1784       if (SI.getType()->isFPOrFPVectorTy()) {
1785         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1786         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1787           FastMathFlags Flags = AddOp->getFastMathFlags();
1788           Flags &= SubOp->getFastMathFlags();
1789           NegInst->setFastMathFlags(Flags);
1790         }
1791       } else {
1792         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1793       }
1794 
1795       Value *NewTrueOp = OtherAddOp;
1796       Value *NewFalseOp = NegVal;
1797       if (AddOp != TI)
1798         std::swap(NewTrueOp, NewFalseOp);
1799       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1800                                            SI.getName() + ".p", &SI);
1801 
1802       if (SI.getType()->isFPOrFPVectorTy()) {
1803         Instruction *RI =
1804             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1805 
1806         FastMathFlags Flags = AddOp->getFastMathFlags();
1807         Flags &= SubOp->getFastMathFlags();
1808         RI->setFastMathFlags(Flags);
1809         return RI;
1810       } else
1811         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1812     }
1813   }
1814   return nullptr;
1815 }
1816 
1817 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1818 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1819 /// Along with a number of patterns similar to:
1820 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1821 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1822 static Instruction *
1823 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1824   Value *CondVal = SI.getCondition();
1825   Value *TrueVal = SI.getTrueValue();
1826   Value *FalseVal = SI.getFalseValue();
1827 
1828   WithOverflowInst *II;
1829   if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1830       !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1831     return nullptr;
1832 
1833   Value *X = II->getLHS();
1834   Value *Y = II->getRHS();
1835 
1836   auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1837     Type *Ty = Limit->getType();
1838 
1839     ICmpInst::Predicate Pred;
1840     Value *TrueVal, *FalseVal, *Op;
1841     const APInt *C;
1842     if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1843                                m_Value(TrueVal), m_Value(FalseVal))))
1844       return false;
1845 
1846     auto IsZeroOrOne = [](const APInt &C) {
1847       return C.isNullValue() || C.isOneValue();
1848     };
1849     auto IsMinMax = [&](Value *Min, Value *Max) {
1850       APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1851       APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1852       return match(Min, m_SpecificInt(MinVal)) &&
1853              match(Max, m_SpecificInt(MaxVal));
1854     };
1855 
1856     if (Op != X && Op != Y)
1857       return false;
1858 
1859     if (IsAdd) {
1860       // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1861       // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1862       // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1863       // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1864       if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1865           IsMinMax(TrueVal, FalseVal))
1866         return true;
1867       // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1868       // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1869       // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1870       // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1871       if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1872           IsMinMax(FalseVal, TrueVal))
1873         return true;
1874     } else {
1875       // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1876       // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1877       if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
1878           IsMinMax(TrueVal, FalseVal))
1879         return true;
1880       // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1881       // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1882       if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
1883           IsMinMax(FalseVal, TrueVal))
1884         return true;
1885       // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1886       // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1887       if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1888           IsMinMax(FalseVal, TrueVal))
1889         return true;
1890       // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1891       // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1892       if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1893           IsMinMax(TrueVal, FalseVal))
1894         return true;
1895     }
1896 
1897     return false;
1898   };
1899 
1900   Intrinsic::ID NewIntrinsicID;
1901   if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1902       match(TrueVal, m_AllOnes()))
1903     // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1904     NewIntrinsicID = Intrinsic::uadd_sat;
1905   else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1906            match(TrueVal, m_Zero()))
1907     // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1908     NewIntrinsicID = Intrinsic::usub_sat;
1909   else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
1910            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
1911     // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1912     // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1913     // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1914     // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1915     // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1916     // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1917     // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1918     // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1919     NewIntrinsicID = Intrinsic::sadd_sat;
1920   else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
1921            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
1922     // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1923     // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1924     // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1925     // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1926     // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1927     // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1928     // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1929     // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1930     NewIntrinsicID = Intrinsic::ssub_sat;
1931   else
1932     return nullptr;
1933 
1934   Function *F =
1935       Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1936   return CallInst::Create(F, {X, Y});
1937 }
1938 
1939 Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) {
1940   Constant *C;
1941   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1942       !match(Sel.getFalseValue(), m_Constant(C)))
1943     return nullptr;
1944 
1945   Instruction *ExtInst;
1946   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1947       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1948     return nullptr;
1949 
1950   auto ExtOpcode = ExtInst->getOpcode();
1951   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1952     return nullptr;
1953 
1954   // If we are extending from a boolean type or if we can create a select that
1955   // has the same size operands as its condition, try to narrow the select.
1956   Value *X = ExtInst->getOperand(0);
1957   Type *SmallType = X->getType();
1958   Value *Cond = Sel.getCondition();
1959   auto *Cmp = dyn_cast<CmpInst>(Cond);
1960   if (!SmallType->isIntOrIntVectorTy(1) &&
1961       (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1962     return nullptr;
1963 
1964   // If the constant is the same after truncation to the smaller type and
1965   // extension to the original type, we can narrow the select.
1966   Type *SelType = Sel.getType();
1967   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1968   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1969   if (ExtC == C && ExtInst->hasOneUse()) {
1970     Value *TruncCVal = cast<Value>(TruncC);
1971     if (ExtInst == Sel.getFalseValue())
1972       std::swap(X, TruncCVal);
1973 
1974     // select Cond, (ext X), C --> ext(select Cond, X, C')
1975     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1976     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1977     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1978   }
1979 
1980   // If one arm of the select is the extend of the condition, replace that arm
1981   // with the extension of the appropriate known bool value.
1982   if (Cond == X) {
1983     if (ExtInst == Sel.getTrueValue()) {
1984       // select X, (sext X), C --> select X, -1, C
1985       // select X, (zext X), C --> select X,  1, C
1986       Constant *One = ConstantInt::getTrue(SmallType);
1987       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1988       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1989     } else {
1990       // select X, C, (sext X) --> select X, C, 0
1991       // select X, C, (zext X) --> select X, C, 0
1992       Constant *Zero = ConstantInt::getNullValue(SelType);
1993       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1994     }
1995   }
1996 
1997   return nullptr;
1998 }
1999 
2000 /// Try to transform a vector select with a constant condition vector into a
2001 /// shuffle for easier combining with other shuffles and insert/extract.
2002 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
2003   Value *CondVal = SI.getCondition();
2004   Constant *CondC;
2005   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
2006     return nullptr;
2007 
2008   unsigned NumElts =
2009       cast<FixedVectorType>(CondVal->getType())->getNumElements();
2010   SmallVector<int, 16> Mask;
2011   Mask.reserve(NumElts);
2012   for (unsigned i = 0; i != NumElts; ++i) {
2013     Constant *Elt = CondC->getAggregateElement(i);
2014     if (!Elt)
2015       return nullptr;
2016 
2017     if (Elt->isOneValue()) {
2018       // If the select condition element is true, choose from the 1st vector.
2019       Mask.push_back(i);
2020     } else if (Elt->isNullValue()) {
2021       // If the select condition element is false, choose from the 2nd vector.
2022       Mask.push_back(i + NumElts);
2023     } else if (isa<UndefValue>(Elt)) {
2024       // Undef in a select condition (choose one of the operands) does not mean
2025       // the same thing as undef in a shuffle mask (any value is acceptable), so
2026       // give up.
2027       return nullptr;
2028     } else {
2029       // Bail out on a constant expression.
2030       return nullptr;
2031     }
2032   }
2033 
2034   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2035 }
2036 
2037 /// If we have a select of vectors with a scalar condition, try to convert that
2038 /// to a vector select by splatting the condition. A splat may get folded with
2039 /// other operations in IR and having all operands of a select be vector types
2040 /// is likely better for vector codegen.
2041 static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
2042                                                    InstCombinerImpl &IC) {
2043   auto *Ty = dyn_cast<VectorType>(Sel.getType());
2044   if (!Ty)
2045     return nullptr;
2046 
2047   // We can replace a single-use extract with constant index.
2048   Value *Cond = Sel.getCondition();
2049   if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
2050     return nullptr;
2051 
2052   // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2053   // Splatting the extracted condition reduces code (we could directly create a
2054   // splat shuffle of the source vector to eliminate the intermediate step).
2055   return IC.replaceOperand(
2056       Sel, 0, IC.Builder.CreateVectorSplat(Ty->getElementCount(), Cond));
2057 }
2058 
2059 /// Reuse bitcasted operands between a compare and select:
2060 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2061 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2062 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2063                                           InstCombiner::BuilderTy &Builder) {
2064   Value *Cond = Sel.getCondition();
2065   Value *TVal = Sel.getTrueValue();
2066   Value *FVal = Sel.getFalseValue();
2067 
2068   CmpInst::Predicate Pred;
2069   Value *A, *B;
2070   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2071     return nullptr;
2072 
2073   // The select condition is a compare instruction. If the select's true/false
2074   // values are already the same as the compare operands, there's nothing to do.
2075   if (TVal == A || TVal == B || FVal == A || FVal == B)
2076     return nullptr;
2077 
2078   Value *C, *D;
2079   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2080     return nullptr;
2081 
2082   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2083   Value *TSrc, *FSrc;
2084   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2085       !match(FVal, m_BitCast(m_Value(FSrc))))
2086     return nullptr;
2087 
2088   // If the select true/false values are *different bitcasts* of the same source
2089   // operands, make the select operands the same as the compare operands and
2090   // cast the result. This is the canonical select form for min/max.
2091   Value *NewSel;
2092   if (TSrc == C && FSrc == D) {
2093     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2094     // bitcast (select (cmp A, B), A, B)
2095     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2096   } else if (TSrc == D && FSrc == C) {
2097     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2098     // bitcast (select (cmp A, B), B, A)
2099     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2100   } else {
2101     return nullptr;
2102   }
2103   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2104 }
2105 
2106 /// Try to eliminate select instructions that test the returned flag of cmpxchg
2107 /// instructions.
2108 ///
2109 /// If a select instruction tests the returned flag of a cmpxchg instruction and
2110 /// selects between the returned value of the cmpxchg instruction its compare
2111 /// operand, the result of the select will always be equal to its false value.
2112 /// For example:
2113 ///
2114 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2115 ///   %1 = extractvalue { i64, i1 } %0, 1
2116 ///   %2 = extractvalue { i64, i1 } %0, 0
2117 ///   %3 = select i1 %1, i64 %compare, i64 %2
2118 ///   ret i64 %3
2119 ///
2120 /// The returned value of the cmpxchg instruction (%2) is the original value
2121 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2122 /// must have been equal to %compare. Thus, the result of the select is always
2123 /// equal to %2, and the code can be simplified to:
2124 ///
2125 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2126 ///   %1 = extractvalue { i64, i1 } %0, 0
2127 ///   ret i64 %1
2128 ///
2129 static Value *foldSelectCmpXchg(SelectInst &SI) {
2130   // A helper that determines if V is an extractvalue instruction whose
2131   // aggregate operand is a cmpxchg instruction and whose single index is equal
2132   // to I. If such conditions are true, the helper returns the cmpxchg
2133   // instruction; otherwise, a nullptr is returned.
2134   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2135     auto *Extract = dyn_cast<ExtractValueInst>(V);
2136     if (!Extract)
2137       return nullptr;
2138     if (Extract->getIndices()[0] != I)
2139       return nullptr;
2140     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2141   };
2142 
2143   // If the select has a single user, and this user is a select instruction that
2144   // we can simplify, skip the cmpxchg simplification for now.
2145   if (SI.hasOneUse())
2146     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2147       if (Select->getCondition() == SI.getCondition())
2148         if (Select->getFalseValue() == SI.getTrueValue() ||
2149             Select->getTrueValue() == SI.getFalseValue())
2150           return nullptr;
2151 
2152   // Ensure the select condition is the returned flag of a cmpxchg instruction.
2153   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2154   if (!CmpXchg)
2155     return nullptr;
2156 
2157   // Check the true value case: The true value of the select is the returned
2158   // value of the same cmpxchg used by the condition, and the false value is the
2159   // cmpxchg instruction's compare operand.
2160   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2161     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2162       return SI.getFalseValue();
2163 
2164   // Check the false value case: The false value of the select is the returned
2165   // value of the same cmpxchg used by the condition, and the true value is the
2166   // cmpxchg instruction's compare operand.
2167   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2168     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2169       return SI.getFalseValue();
2170 
2171   return nullptr;
2172 }
2173 
2174 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2175                                        Value *Y,
2176                                        InstCombiner::BuilderTy &Builder) {
2177   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
2178   bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2179                     SPF == SelectPatternFlavor::SPF_UMAX;
2180   // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2181   // the constant value check to an assert.
2182   Value *A;
2183   const APInt *C1, *C2;
2184   if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2185       match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2186     // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2187     // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2188     Value *NewMinMax = createMinMax(Builder, SPF, A,
2189                                     ConstantInt::get(X->getType(), *C2 - *C1));
2190     return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2191                                      ConstantInt::get(X->getType(), *C1));
2192   }
2193 
2194   if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2195       match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2196     bool Overflow;
2197     APInt Diff = C2->ssub_ov(*C1, Overflow);
2198     if (!Overflow) {
2199       // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2200       // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2201       Value *NewMinMax = createMinMax(Builder, SPF, A,
2202                                       ConstantInt::get(X->getType(), Diff));
2203       return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2204                                        ConstantInt::get(X->getType(), *C1));
2205     }
2206   }
2207 
2208   return nullptr;
2209 }
2210 
2211 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
2212 Instruction *InstCombinerImpl::matchSAddSubSat(SelectInst &MinMax1) {
2213   Type *Ty = MinMax1.getType();
2214 
2215   // We are looking for a tree of:
2216   // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2217   // Where the min and max could be reversed
2218   Instruction *MinMax2;
2219   BinaryOperator *AddSub;
2220   const APInt *MinValue, *MaxValue;
2221   if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2222     if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2223       return nullptr;
2224   } else if (match(&MinMax1,
2225                    m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2226     if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2227       return nullptr;
2228   } else
2229     return nullptr;
2230 
2231   // Check that the constants clamp a saturate, and that the new type would be
2232   // sensible to convert to.
2233   if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2234     return nullptr;
2235   // In what bitwidth can this be treated as saturating arithmetics?
2236   unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2237   // FIXME: This isn't quite right for vectors, but using the scalar type is a
2238   // good first approximation for what should be done there.
2239   if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2240     return nullptr;
2241 
2242   // Also make sure that the number of uses is as expected. The "3"s are for the
2243   // the two items of min/max (the compare and the select).
2244   if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3))
2245     return nullptr;
2246 
2247   // Create the new type (which can be a vector type)
2248   Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2249   // Match the two extends from the add/sub
2250   Value *A, *B;
2251   if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B)))))
2252     return nullptr;
2253   // And check the incoming values are of a type smaller than or equal to the
2254   // size of the saturation. Otherwise the higher bits can cause different
2255   // results.
2256   if (A->getType()->getScalarSizeInBits() > NewBitWidth ||
2257       B->getType()->getScalarSizeInBits() > NewBitWidth)
2258     return nullptr;
2259 
2260   Intrinsic::ID IntrinsicID;
2261   if (AddSub->getOpcode() == Instruction::Add)
2262     IntrinsicID = Intrinsic::sadd_sat;
2263   else if (AddSub->getOpcode() == Instruction::Sub)
2264     IntrinsicID = Intrinsic::ssub_sat;
2265   else
2266     return nullptr;
2267 
2268   // Finally create and return the sat intrinsic, truncated to the new type
2269   Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2270   Value *AT = Builder.CreateSExt(A, NewTy);
2271   Value *BT = Builder.CreateSExt(B, NewTy);
2272   Value *Sat = Builder.CreateCall(F, {AT, BT});
2273   return CastInst::Create(Instruction::SExt, Sat, Ty);
2274 }
2275 
2276 /// Reduce a sequence of min/max with a common operand.
2277 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2278                                         Value *RHS,
2279                                         InstCombiner::BuilderTy &Builder) {
2280   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
2281   // TODO: Allow FP min/max with nnan/nsz.
2282   if (!LHS->getType()->isIntOrIntVectorTy())
2283     return nullptr;
2284 
2285   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2286   Value *A, *B, *C, *D;
2287   SelectPatternResult L = matchSelectPattern(LHS, A, B);
2288   SelectPatternResult R = matchSelectPattern(RHS, C, D);
2289   if (SPF != L.Flavor || L.Flavor != R.Flavor)
2290     return nullptr;
2291 
2292   // Look for a common operand. The use checks are different than usual because
2293   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2294   // the select.
2295   Value *MinMaxOp = nullptr;
2296   Value *ThirdOp = nullptr;
2297   if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2298     // If the LHS is only used in this chain and the RHS is used outside of it,
2299     // reuse the RHS min/max because that will eliminate the LHS.
2300     if (D == A || C == A) {
2301       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2302       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2303       MinMaxOp = RHS;
2304       ThirdOp = B;
2305     } else if (D == B || C == B) {
2306       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2307       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2308       MinMaxOp = RHS;
2309       ThirdOp = A;
2310     }
2311   } else if (!RHS->hasNUsesOrMore(3)) {
2312     // Reuse the LHS. This will eliminate the RHS.
2313     if (D == A || D == B) {
2314       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2315       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2316       MinMaxOp = LHS;
2317       ThirdOp = C;
2318     } else if (C == A || C == B) {
2319       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2320       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2321       MinMaxOp = LHS;
2322       ThirdOp = D;
2323     }
2324   }
2325   if (!MinMaxOp || !ThirdOp)
2326     return nullptr;
2327 
2328   CmpInst::Predicate P = getMinMaxPred(SPF);
2329   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2330   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2331 }
2332 
2333 /// Try to reduce a rotate pattern that includes a compare and select into a
2334 /// funnel shift intrinsic. Example:
2335 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2336 ///              --> call llvm.fshl.i32(a, a, b)
2337 static Instruction *foldSelectRotate(SelectInst &Sel,
2338                                      InstCombiner::BuilderTy &Builder) {
2339   // The false value of the select must be a rotate of the true value.
2340   BinaryOperator *Or0, *Or1;
2341   if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
2342     return nullptr;
2343 
2344   Value *TVal = Sel.getTrueValue();
2345   Value *SA0, *SA1;
2346   if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal),
2347                                           m_ZExtOrSelf(m_Value(SA0))))) ||
2348       !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal),
2349                                           m_ZExtOrSelf(m_Value(SA1))))) ||
2350       Or0->getOpcode() == Or1->getOpcode())
2351     return nullptr;
2352 
2353   // Canonicalize to or(shl(TVal, SA0), lshr(TVal, SA1)).
2354   if (Or0->getOpcode() == BinaryOperator::LShr) {
2355     std::swap(Or0, Or1);
2356     std::swap(SA0, SA1);
2357   }
2358   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2359          Or1->getOpcode() == BinaryOperator::LShr &&
2360          "Illegal or(shift,shift) pair");
2361 
2362   // We should now have this pattern:
2363   // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
2364   // This must be a power-of-2 rotate for a bitmasking transform to be valid.
2365   unsigned Width = Sel.getType()->getScalarSizeInBits();
2366   if (!isPowerOf2_32(Width))
2367     return nullptr;
2368 
2369   // Check the shift amounts to see if they are an opposite pair.
2370   Value *ShAmt;
2371   if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2372     ShAmt = SA0;
2373   else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2374     ShAmt = SA1;
2375   else
2376     return nullptr;
2377 
2378   // Finally, see if the select is filtering out a shift-by-zero.
2379   Value *Cond = Sel.getCondition();
2380   ICmpInst::Predicate Pred;
2381   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2382       Pred != ICmpInst::ICMP_EQ)
2383     return nullptr;
2384 
2385   // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2386   // Convert to funnel shift intrinsic.
2387   bool IsFshl = (ShAmt == SA0);
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, { TVal, TVal, 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 *Rot = foldSelectRotate(SI, Builder))
3036     return Rot;
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